source
stringlengths
3
92
c
stringlengths
26
2.25M
triad.c
/* * ======================================================================================= * * Author: Jan Eitzinger (je), [email protected] * Copyright (c) 2020 RRZE, University Erlangen-Nuremberg * * 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 <timing.h> double triad( double * restrict a, double * restrict b, double * restrict c, double scalar, int N ) { double S, E; S = getTimeStamp(); #pragma omp parallel for schedule(static) for (int i=0; i<N; i++) { a[i] = b[i] + scalar * c[i]; } E = getTimeStamp(); return E-S; }
paint.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP AAA IIIII N N TTTTT % % P P A A I NN N T % % PPPP AAAAA I N N N T % % P A A I N NN T % % P A A IIIII N N T % % % % % % Methods to Paint on an Image % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/resource_.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o o d f i l l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FloodfillPaintImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % By default target must match a particular pixel color exactly. However, % in many cases two colors may differ by a small amount. The fuzz member of % image defines how much tolerance is acceptable to consider two colors as % the same. For example, set fuzz to 10 and the color red at intensities of % 100 and 102 respectively are now interpreted as the same color for the % purposes of the floodfill. % % The format of the FloodfillPaintImage method is: % % MagickBooleanType FloodfillPaintImage(Image *image, % const DrawInfo *draw_info,const PixelInfo target, % const ssize_t x_offset,const ssize_t y_offset, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o target: the RGB value of the target color. % % o x_offset,y_offset: the starting location of the operation. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType FloodfillPaintImage(Image *image, const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset, const ssize_t y_offset,const MagickBooleanType invert, ExceptionInfo *exception) { #define MaxStacksize 524288UL #define PushSegmentStack(up,left,right,delta) \ { \ if (s >= (segment_stack+MaxStacksize)) \ ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \ else \ { \ if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \ { \ s->x1=(double) (left); \ s->y1=(double) (up); \ s->x2=(double) (right); \ s->y2=(double) (delta); \ s++; \ } \ } \ } CacheView *floodplane_view, *image_view; Image *floodplane_image; MagickBooleanType skip, status; MemoryInfo *segment_info; PixelInfo fill_color, pixel; register SegmentInfo *s; SegmentInfo *segment_stack; ssize_t offset, start, x1, x2, y; /* Check boundary conditions. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) return(MagickFalse); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if ((image->alpha_trait == UndefinedPixelTrait) && (draw_info->fill.alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(image,OpaqueAlpha,exception); /* Set floodfill state. */ floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (floodplane_image == (Image *) NULL) return(MagickFalse); floodplane_image->alpha_trait=UndefinedPixelTrait; floodplane_image->colorspace=GRAYColorspace; (void) QueryColorCompliance("#000",AllCompliance, &floodplane_image->background_color,exception); (void) SetImageBackgroundColor(floodplane_image,exception); segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack)); if (segment_info == (MemoryInfo *) NULL) { floodplane_image=DestroyImage(floodplane_image); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info); /* Push initial segment on stack. */ status=MagickTrue; start=0; s=segment_stack; PushSegmentStack(y_offset,x_offset,x_offset,1); PushSegmentStack(y_offset+1,x_offset,x_offset,-1); GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception); while (s > segment_stack) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Pop segment off stack. */ s--; x1=(ssize_t) s->x1; x2=(ssize_t) s->x2; offset=(ssize_t) s->y2; y=(ssize_t) s->y1+offset; /* Recolor neighboring pixels. */ p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception); q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; p+=x1*GetPixelChannels(image); q+=x1*GetPixelChannels(floodplane_image); for (x=x1; x >= 0; x--) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p-=GetPixelChannels(image); q-=GetPixelChannels(floodplane_image); } if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse) break; skip=x >= x1 ? MagickTrue : MagickFalse; if (skip == MagickFalse) { start=x+1; if (start < x1) PushSegmentStack(y,start,x1-1,-offset); x=x1+1; } do { if (skip == MagickFalse) { if (x < (ssize_t) image->columns) { p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns- x,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert) break; SetPixelGray(floodplane_image,QuantumRange,q); p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } status=SyncCacheViewAuthenticPixels(floodplane_view,exception); if (status == MagickFalse) break; } PushSegmentStack(y,start,x-1,offset); if (x > (x2+1)) PushSegmentStack(y,x2+1,x-1,-offset); } skip=MagickFalse; x++; if (x <= x2) { p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1, exception); q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for ( ; x <= x2; x++) { if (GetPixelGray(floodplane_image,q) != 0) break; GetPixelInfoPixel(image,p,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) break; p+=GetPixelChannels(image); q+=GetPixelChannels(floodplane_image); } } start=x; } while (x <= x2); } status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Tile fill color onto floodplane. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelGray(floodplane_image,p) != 0) { GetFillColor(draw_info,x,y,&fill_color,exception); SetPixelViaPixelInfo(image,&fill_color,q); } p+=GetPixelChannels(floodplane_image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } floodplane_view=DestroyCacheView(floodplane_view); image_view=DestroyCacheView(image_view); segment_info=RelinquishVirtualMemory(segment_info); floodplane_image=DestroyImage(floodplane_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G r a d i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GradientImage() applies a continuously smooth color transitions along a % vector from one color to another. % % Note, the interface of this method will change in the future to support % more than one transistion. % % The format of the GradientImage method is: % % MagickBooleanType GradientImage(Image *image,const GradientType type, % const SpreadMethod method,const PixelInfo *start_color, % const PixelInfo *stop_color,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the gradient type: linear or radial. % % o spread: the gradient spread meathod: pad, reflect, or repeat. % % o start_color: the start color. % % o stop_color: the stop color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GradientImage(Image *image, const GradientType type,const SpreadMethod method,const StopInfo *stops, const size_t number_stops,ExceptionInfo *exception) { const char *artifact; DrawInfo *draw_info; GradientInfo *gradient; MagickBooleanType status; /* Set gradient start-stop end points. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(stops != (const StopInfo *) NULL); assert(number_stops > 0); draw_info=AcquireDrawInfo(); gradient=(&draw_info->gradient); gradient->type=type; gradient->bounding_box.width=image->columns; gradient->bounding_box.height=image->rows; artifact=GetImageArtifact(image,"gradient:bounding-box"); if (artifact != (const char *) NULL) (void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box); gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; artifact=GetImageArtifact(image,"gradient:direction"); if (artifact != (const char *) NULL) { GravityType direction; direction=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,artifact); switch (direction) { case NorthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case NorthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=(double) image->rows-1; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case WestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=0.0; break; } case EastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=0.0; break; } case SouthWestGravity: { gradient->gradient_vector.x1=(double) image->columns-1; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->rows-1; break; } case SouthGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=0.0; gradient->gradient_vector.y2=(double) image->columns-1; break; } case SouthEastGravity: { gradient->gradient_vector.x1=0.0; gradient->gradient_vector.y1=0.0; gradient->gradient_vector.x2=(double) image->columns-1; gradient->gradient_vector.y2=(double) image->rows-1; break; } default: break; } } artifact=GetImageArtifact(image,"gradient:angle"); if (artifact != (const char *) NULL) gradient->angle=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"gradient:vector"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &gradient->gradient_vector.x1,&gradient->gradient_vector.y1, &gradient->gradient_vector.x2,&gradient->gradient_vector.y2); if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) && (GetImageArtifact(image,"gradient:direction") == (const char *) NULL) && (GetImageArtifact(image,"gradient:extent") == (const char *) NULL) && (GetImageArtifact(image,"gradient:vector") == (const char *) NULL)) if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0)) gradient->gradient_vector.x2=0.0; gradient->center.x=(double) gradient->gradient_vector.x2/2.0; gradient->center.y=(double) gradient->gradient_vector.y2/2.0; artifact=GetImageArtifact(image,"gradient:center"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x, &gradient->center.y); artifact=GetImageArtifact(image,"gradient:angle"); if ((type == LinearGradient) && (artifact != (const char *) NULL)) { double sine, cosine, distance; /* Reference https://drafts.csswg.org/css-images-3/#linear-gradients. */ sine=sin((double) DegreesToRadians(gradient->angle-90.0)); cosine=cos((double) DegreesToRadians(gradient->angle-90.0)); distance=fabs((double) (image->columns-1.0)*cosine)+ fabs((double) (image->rows-1.0)*sine); gradient->gradient_vector.x1=0.5*((image->columns-1.0)-distance*cosine); gradient->gradient_vector.y1=0.5*((image->rows-1.0)-distance*sine); gradient->gradient_vector.x2=0.5*((image->columns-1.0)+distance*cosine); gradient->gradient_vector.y2=0.5*((image->rows-1.0)+distance*sine); } gradient->radii.x=(double) MagickMax((image->columns-1.0),(image->rows-1.0))/ 2.0; gradient->radii.y=gradient->radii.x; artifact=GetImageArtifact(image,"gradient:extent"); if (artifact != (const char *) NULL) { if (LocaleCompare(artifact,"Circle") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Diagonal") == 0) { gradient->radii.x=(double) (sqrt((double) (image->columns-1.0)* (image->columns-1.0)+(image->rows-1.0)*(image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Ellipse") == 0) { gradient->radii.x=(double) (image->columns-1.0)/2.0; gradient->radii.y=(double) (image->rows-1.0)/2.0; } if (LocaleCompare(artifact,"Maximum") == 0) { gradient->radii.x=(double) MagickMax((image->columns-1.0), (image->rows-1.0))/2.0; gradient->radii.y=gradient->radii.x; } if (LocaleCompare(artifact,"Minimum") == 0) { gradient->radii.x=(double) (MagickMin((image->columns-1.0), (image->rows-1.0)))/2.0; gradient->radii.y=gradient->radii.x; } } artifact=GetImageArtifact(image,"gradient:radii"); if (artifact != (const char *) NULL) (void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x, &gradient->radii.y); gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y); gradient->spread=method; /* Define the gradient to fill between the stops. */ gradient->number_stops=number_stops; gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops, sizeof(*gradient->stops)); if (gradient->stops == (StopInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memcpy(gradient->stops,stops,(size_t) number_stops* sizeof(*stops)); /* Draw a gradient on the image. */ status=DrawGradientImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O i l P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OilPaintImage() applies a special effect filter that simulates an oil % painting. Each pixel is replaced by the most frequent color occurring % in a circular region defined by radius. % % The format of the OilPaintImage method is: % % Image *OilPaintImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the circular neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ static size_t **DestroyHistogramThreadSet(size_t **histogram) { register ssize_t i; assert(histogram != (size_t **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (histogram[i] != (size_t *) NULL) histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]); histogram=(size_t **) RelinquishMagickMemory(histogram); return(histogram); } static size_t **AcquireHistogramThreadSet(const size_t count) { register ssize_t i; size_t **histogram, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram)); if (histogram == (size_t **) NULL) return((size_t **) NULL); (void) memset(histogram,0,number_threads*sizeof(*histogram)); for (i=0; i < (ssize_t) number_threads; i++) { histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram)); if (histogram[i] == (size_t *) NULL) return(DestroyHistogramThreadSet(histogram)); } return(histogram); } MagickExport Image *OilPaintImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { #define NumberPaintBins 256 #define OilPaintImageTag "OilPaint/Image" CacheView *image_view, *paint_view; Image *linear_image, *paint_image; MagickBooleanType status; MagickOffsetType progress; size_t **histograms, width; ssize_t center, y; /* Initialize painted image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=GetOptimalKernelWidth2D(radius,sigma); linear_image=CloneImage(image,0,0,MagickTrue,exception); paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL)) { if (linear_image != (Image *) NULL) linear_image=DestroyImage(linear_image); if (paint_image != (Image *) NULL) linear_image=DestroyImage(paint_image); return((Image *) NULL); } if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); return((Image *) NULL); } histograms=AcquireHistogramThreadSet(NumberPaintBins); if (histograms == (size_t **) NULL) { linear_image=DestroyImage(linear_image); paint_image=DestroyImage(paint_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Oil paint image. */ status=MagickTrue; progress=0; center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)* (width/2L)+GetPixelChannels(linear_image)*(width/2L); image_view=AcquireVirtualCacheView(linear_image,exception); paint_view=AcquireAuthenticCacheView(paint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(linear_image,paint_image,linear_image->rows,1) #endif for (y=0; y < (ssize_t) linear_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register size_t *histogram; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) (width/2L),linear_image->columns+width,width,exception); q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } histogram=histograms[GetOpenMPThreadId()]; for (x=0; x < (ssize_t) linear_image->columns; x++) { register ssize_t i, u; size_t count; ssize_t j, k, n, v; /* Assign most frequent color. */ k=0; j=0; count=0; (void) memset(histogram,0,NumberPaintBins* sizeof(*histogram)); for (v=0; v < (ssize_t) width; v++) { for (u=0; u < (ssize_t) width; u++) { n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity( linear_image,p+GetPixelChannels(linear_image)*(u+k)))); histogram[n]++; if (histogram[n] > count) { j=k+u; count=histogram[n]; } } k+=(ssize_t) (linear_image->columns+width); } for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++) { PixelChannel channel = GetPixelChannelChannel(linear_image,i); PixelTrait traits = GetPixelChannelTraits(linear_image,channel); PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel); if ((traits == UndefinedPixelTrait) || (paint_traits == UndefinedPixelTrait)) continue; if (((paint_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(linear_image,p) <= (QuantumRange/2))) { SetPixelChannel(paint_image,channel,p[center+i],q); continue; } SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+ i],q); } p+=GetPixelChannels(linear_image); q+=GetPixelChannels(paint_image); } if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse) status=MagickFalse; if (linear_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OilPaintImage) #endif proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++, linear_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } paint_view=DestroyCacheView(paint_view); image_view=DestroyCacheView(image_view); histograms=DestroyHistogramThreadSet(histograms); linear_image=DestroyImage(linear_image); if (status == MagickFalse) paint_image=DestroyImage(paint_image); return(paint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p a q u e P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpaquePaintImage() changes any pixel that matches color with the color % defined by fill argument. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the OpaquePaintImage method is: % % MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target, % const PixelInfo *fill,const MagickBooleanType invert, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the RGB value of the target color. % % o fill: the replacement color. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OpaquePaintImage(Image *image, const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert, ExceptionInfo *exception) { #define OpaquePaintImageTag "Opaque/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo conform_fill, conform_target, zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); assert(fill != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); ConformPixelInfo(image,fill,&conform_fill,exception); ConformPixelInfo(image,target,&conform_target,exception); /* Make image color opaque. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert) { PixelTrait traits; traits=GetPixelChannelTraits(image,RedPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelRed(image,(Quantum) conform_fill.red,q); traits=GetPixelChannelTraits(image,GreenPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelGreen(image,(Quantum) conform_fill.green,q); traits=GetPixelChannelTraits(image,BluePixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlue(image,(Quantum) conform_fill.blue,q); traits=GetPixelChannelTraits(image,BlackPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelBlack(image,(Quantum) conform_fill.black,q); traits=GetPixelChannelTraits(image,AlphaPixelChannel); if ((traits & UpdatePixelTrait) != 0) SetPixelAlpha(image,(Quantum) conform_fill.alpha,q); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_OpaquePaintImage) #endif proceed=SetImageProgress(image,OpaquePaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImage() changes the opacity value associated with any pixel % that matches color to the value defined by opacity. % % By default color must match a particular pixel color exactly. However, in % many cases two colors may differ by a small amount. Fuzz defines how much % tolerance is acceptable to consider two colors as the same. For example, % set fuzz to 10 and the color red at intensities of 100 and 102 respectively % are now interpreted as the same color. % % The format of the TransparentPaintImage method is: % % MagickBooleanType TransparentPaintImage(Image *image, % const PixelInfo *target,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o target: the target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImage(Image *image, const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert, ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo zero; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(target != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; GetPixelInfo(image,&zero); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } pixel=zero; for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImage) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p a r e n t P a i n t I m a g e C h r o m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransparentPaintImageChroma() changes the opacity value associated with any % pixel that matches color to the value defined by opacity. % % As there is one fuzz value for the all the channels, TransparentPaintImage() % is not suitable for the operations like chroma, where the tolerance for % similarity of two color component (RGB) can be different. Thus we define % this method to take two target pixels (one low and one high) and all the % pixels of an image which are lying between these two pixels are made % transparent. % % The format of the TransparentPaintImageChroma method is: % % MagickBooleanType TransparentPaintImageChroma(Image *image, % const PixelInfo *low,const PixelInfo *high,const Quantum opacity, % const MagickBooleanType invert,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o low: the low target color. % % o high: the high target color. % % o opacity: the replacement opacity value. % % o invert: paint any pixel that does not match the target color. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image, const PixelInfo *low,const PixelInfo *high,const Quantum opacity, const MagickBooleanType invert,ExceptionInfo *exception) { #define TransparentPaintImageTag "Transparent/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(high != (PixelInfo *) NULL); assert(low != (PixelInfo *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); /* Make image color transparent. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType match; PixelInfo pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,q,&pixel); match=((pixel.red >= low->red) && (pixel.red <= high->red) && (pixel.green >= low->green) && (pixel.green <= high->green) && (pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue : MagickFalse; if (match != invert) SetPixelAlpha(image,opacity,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransparentPaintImageChroma) #endif proceed=SetImageProgress(image,TransparentPaintImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
copy.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define ELEMENT double ELEMENT *copy(ELEMENT *vect, int size) { ELEMENT *vect_new = malloc(sizeof(ELEMENT) * size); for (int i = 0; i < size; i++) { vect_new[i] = vect[i]; } return vect_new; } ELEMENT *copy_parallel(ELEMENT *vect, int size) { ELEMENT *vect_new = malloc(sizeof(ELEMENT) * size); #pragma omp parallel for shared(vect, vect_new, size) default(none) for (int i = 0; i < size; i++) { vect_new[i] = vect[i]; } return vect_new; } void copy_inplace(ELEMENT *origin_vect, ELEMENT *dest_vect, int size) { for (int i = 0; i < size; i++) { dest_vect[i] = origin_vect[i]; } } void copy_inplace_parallel(ELEMENT *origin_vect, ELEMENT *dest_vect, int size) { #pragma omp parallel for shared(origin_vect, dest_vect, size) default(none) for (int i = 0; i < size; i++) { dest_vect[i] = origin_vect[i]; } }
neuralClasses.h
#pragma once #include <iostream> #include <fstream> #include <algorithm> #include <cassert> #include <cmath> #include <vector> #include <boost/unordered_map.hpp> #include <Eigen/Dense> #include "maybe_omp.h" #include "util.h" #include "graphClasses.h" #include "USCMatrix.h" // classes for various kinds of layers #include "SoftmaxLoss.h" #include "Activation_function.h" //#define EIGEN_DONT_PARALLELIZE //#define EIGEN_DEFAULT_TO_ROW_MAJOR using namespace std; namespace nplm { // is this cheating? using Eigen::Matrix; using Eigen::Array; using Eigen::MatrixBase; using Eigen::Dynamic; typedef boost::unordered_map<int,bool> int_map; struct Clipper{ double operator() (double x) const { return std::min(0.5, std::max(x,-0.5)); //return(x); } }; class Linear_layer { private: Matrix<double,Dynamic,Dynamic> U; Matrix<double,Dynamic,Dynamic> U_gradient; Matrix<double,Dynamic,Dynamic> U_velocity; Matrix<double,Dynamic,Dynamic> U_running_gradient; Matrix<double,Dynamic,Dynamic> U_running_parameter_update; // Biases Matrix<double,Dynamic,1> b; Matrix<double,Dynamic,1> b_velocity; Matrix<double,Dynamic,1> b_running_gradient; Matrix<double,Dynamic,1> b_running_parameter_update; Matrix<double,Dynamic,1> b_gradient; friend class model; public: Linear_layer() { } Linear_layer(int rows, int cols) { resize(rows, cols); } void resize(int rows, int cols) { U.setZero(rows, cols); U_gradient.setZero(rows, cols); //U_running_gradient.setZero(rows, cols); //U_running_parameter_updates.setZero(rows, cols); //U_velocity.setZero(rows, cols); b.resize(rows); b_gradient.setZero(rows); //b_running_gradient.resize(rows); //b_velocity.resize(rows); } void read_weights(std::ifstream &U_file) { readMatrix(U_file, U); } void write_weights(std::ofstream &U_file) { writeMatrix(U, U_file); } void read_biases(std::ifstream &b_file) { readMatrix(b_file, b); } void write_biases(std::ofstream &b_file) { writeMatrix(b, b_file); } template <typename Engine> void initialize(Engine &engine, bool init_normal, double init_range, string &parameter_update, double adagrad_epsilon) { if (parameter_update == "ADA") { U_running_gradient = Matrix<double,Dynamic,Dynamic>::Ones(U.rows(),U.cols())*adagrad_epsilon; b_running_gradient = Matrix<double,Dynamic,1>::Ones(b.size())*adagrad_epsilon; } if (parameter_update == "ADAD") { U_running_gradient.setZero(U.rows(),U.cols()); b_running_gradient.setZero(b.size()); U_running_parameter_update.setZero(U.rows(),U.cols()); b_running_parameter_update.setZero(b.size()); } initMatrix(engine, U, init_normal, init_range); initBias(engine, b, init_normal, init_range); } int n_inputs () const { return U.cols(); } int n_outputs () const { return U.rows(); } template <typename DerivedIn, typename DerivedOut> void fProp(const MatrixBase<DerivedIn> &input, const MatrixBase<DerivedOut> &output) const { UNCONST(DerivedOut, output, my_output); my_output.leftCols(input.cols()).noalias() = U*input; int num_examples = input.cols(); for (int example = 0;example < num_examples;example++) { my_output.leftCols(input.cols()).col(example) += b; } } // Sparse input template <typename ScalarIn, typename DerivedOut> void fProp(const USCMatrix<ScalarIn> &input, const MatrixBase<DerivedOut> &output_const) const { UNCONST(DerivedOut, output_const, output); output.setZero(); uscgemm(1.0, U, input, output.leftCols(input.cols())); // Each column corresponds to a training example. We // parallelize the adding of biases per dimension. int num_examples = input.cols(); for (int example = 0;example < num_examples;example++) { output.leftCols(input.cols()).col(example) += b; } } template <typename DerivedGOut, typename DerivedGIn> void bProp(const MatrixBase<DerivedGOut> &input, MatrixBase<DerivedGIn> &output) const { UNCONST(DerivedGIn, output, my_output); my_output.noalias() = U.transpose()*input; } template <typename DerivedGOut, typename DerivedIn> void computeGradient( const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &fProp_input, double learning_rate, double momentum, double L2_reg) { U_gradient.noalias() = bProp_input*fProp_input.transpose(); // get the bias gradient for all dimensions in parallel int size = b.size(); b_gradient = bProp_input.rowwise().sum(); // This used to be multithreaded, but there was no measureable difference if (L2_reg > 0.0) { U_gradient -= 2*L2_reg*U; b_gradient -= 2*L2_reg*b; } if (momentum > 0.0) { U_velocity = momentum*U_velocity + U_gradient; U += learning_rate * U_velocity; b_velocity = momentum*b_velocity + b_gradient; b += learning_rate * b_velocity; } else { U += learning_rate * U_gradient; b += learning_rate * b_gradient; /* //UPDATE CLIPPING U += (learning_rate*U_gradient).array().unaryExpr(Clipper()).matrix(); b += (learning_rate*b_gradient).array().unaryExpr(Clipper()).matrix(); //GRADIENT CLIPPING //U += learning_rate*(U_gradient.array().unaryExpr(Clipper())).matrix(); //b += learning_rate*(b_gradient.array().unaryExpr(Clipper())).matrix(); */ } } template <typename DerivedGOut, typename DerivedIn> void computeGradientAdagrad(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &fProp_input, double learning_rate, double L2_reg) { U_gradient.noalias() = bProp_input*fProp_input.transpose(); // get the bias gradient for all dimensions in parallel int size = b.size(); b_gradient.noalias() = bProp_input.rowwise().sum(); if (L2_reg != 0) { U_gradient -= 2*L2_reg*U; b_gradient -= 2*L2_reg*b; } // ignore momentum? #pragma omp parallel for for (int col=0; col<U.cols(); col++) { U_running_gradient.col(col) += U_gradient.col(col).array().square().matrix(); U.col(col) += learning_rate * (U_gradient.col(col).array() / U_running_gradient.col(col).array().sqrt()).matrix(); /* //UPDATE CLIPPING U.col(col) += (learning_rate * (U_gradient.col(col).array() / U_running_gradient.col(col).array().sqrt())). unaryExpr(Clipper()).matrix(); */ } b_running_gradient += b_gradient.array().square().matrix(); b += learning_rate * (b_gradient.array()/b_running_gradient.array().sqrt()).matrix(); /* //UPDATE CLIPPING b += (learning_rate * (b_gradient.array()/b_running_gradient.array().sqrt())).unaryExpr(Clipper()).matrix(); */ } template <typename DerivedGOut, typename DerivedIn> void computeGradientAdadelta(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &fProp_input, double learning_rate, double L2_reg, double conditioning_constant, double decay) { //cerr<<"decay is "<<decay<<" and conditioning constant is "<<conditioning_constant<<endl; U_gradient.noalias() = bProp_input*fProp_input.transpose(); Array<double,Dynamic,1> b_current_parameter_update; // get the bias gradient for all dimensions in parallel int size = b.size(); b_gradient.noalias() = bProp_input.rowwise().sum(); if (L2_reg != 0) { U_gradient -= 2*L2_reg*U; b_gradient -= 2*L2_reg*b; } // ignore momentum? #pragma omp parallel for //cerr<<"U gradient is "<<U_gradient<<endl; for (int col=0; col<U.cols(); col++) { Array<double,Dynamic,1> U_current_parameter_update; U_running_gradient.col(col) = decay*U_running_gradient.col(col) + (1-decay)*U_gradient.col(col).array().square().matrix(); //cerr<<"U running gradient is "<<U_running_gradient.col(col)<<endl; //getchar(); U_current_parameter_update = ((U_running_parameter_update.col(col).array()+conditioning_constant).sqrt()/ (U_running_gradient.col(col).array()+conditioning_constant).sqrt()) * U_gradient.col(col).array(); //cerr<<"U current parameter update is "<<U_current_parameter_update<<endl; //getchar(); //update the running parameter update U_running_parameter_update.col(col) = decay*U_running_parameter_update.col(col) + (1.-decay)*U_current_parameter_update.square().matrix(); U.col(col) += learning_rate*U_current_parameter_update.matrix(); } b_running_gradient = decay*b_running_gradient + (1.-decay)*b_gradient.array().square().matrix(); b_current_parameter_update = ((b_running_parameter_update.array()+conditioning_constant).sqrt()/ (b_running_gradient.array()+conditioning_constant).sqrt()) * b_gradient.array(); b_running_parameter_update = decay*(b_running_parameter_update) + (1.-decay)*b_current_parameter_update.square().matrix(); b += learning_rate*b_current_parameter_update.matrix(); } template <typename DerivedGOut, typename DerivedIn, typename DerivedGW> void computeGradientCheck(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &fProp_input, const MatrixBase<DerivedGW> &gradient) const { UNCONST(DerivedGW, gradient, my_gradient); my_gradient.noalias() = bProp_input*fProp_input.transpose(); } }; class Output_word_embeddings { private: // row-major is better for uscgemm //Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W; // Having W be a pointer to a matrix allows ease of sharing // input and output word embeddings Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *W; std::vector<double> W_data; Matrix<double,Dynamic,1> b; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_running_gradient; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_gradient; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_running_parameter_update; Matrix<double,Dynamic,1> b_running_gradient; Matrix<double,Dynamic,1> b_gradient; Matrix<double,Dynamic,1> b_running_parameter_update; public: Output_word_embeddings() { } Output_word_embeddings(int rows, int cols) { resize(rows, cols); } void resize(int rows, int cols) { W->setZero(rows, cols); b.setZero(rows); } void set_W(Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *input_W) { W = input_W; } void read_weights(std::ifstream &W_file) { readMatrix(W_file, *W); } void write_weights(std::ofstream &W_file) { writeMatrix(*W, W_file); } void read_biases(std::ifstream &b_file) { readMatrix(b_file, b); } void write_biases(std::ofstream &b_file) { writeMatrix(b, b_file); } template <typename Engine> void initialize(Engine &engine, bool init_normal, double init_range, double init_bias, string &parameter_update, double adagrad_epsilon) { W_gradient.setZero(W->rows(),W->cols()); b_gradient.setZero(b.size()); if (parameter_update == "ADA") { W_running_gradient = Matrix<double,Dynamic,Dynamic>::Ones(W->rows(),W->cols())*adagrad_epsilon; b_running_gradient = Matrix<double,Dynamic,1>::Ones(b.size())*adagrad_epsilon; //W_gradient.setZero(W->rows(),W->cols()); //b_gradient.setZero(b.size()); } if (parameter_update == "ADAD") { W_running_gradient.setZero(W->rows(),W->cols()); b_running_gradient.setZero(b.size()); W_gradient.setZero(W->rows(),W->cols()); //b_gradient.setZero(b.size()); //W_running_parameter_update.setZero(W->rows(),W->cols()); b_running_parameter_update.setZero(b.size()); } initMatrix(engine, *W, init_normal, init_range); b.fill(init_bias); } int n_inputs () const { return W->cols(); } int n_outputs () const { return W->rows(); } template <typename DerivedIn, typename DerivedOut> void fProp(const MatrixBase<DerivedIn> &input, const MatrixBase<DerivedOut> &output) const { UNCONST(DerivedOut, output, my_output); my_output = ((*W) * input).colwise() + b; } // Sparse output version template <typename DerivedIn, typename DerivedOutI, typename DerivedOutV> void fProp(const MatrixBase<DerivedIn> &input, const MatrixBase<DerivedOutI> &samples, const MatrixBase<DerivedOutV> &output) const { UNCONST(DerivedOutV, output, my_output); #pragma omp parallel for for (int instance_id = 0; instance_id < samples.cols(); instance_id++) { for (int sample_id = 0; sample_id < samples.rows(); sample_id++) { my_output(sample_id, instance_id) = b(samples(sample_id, instance_id)); } } USCMatrix<double> sparse_output(W->rows(), samples, my_output); uscgemm_masked(1.0, *W, input, sparse_output); my_output = sparse_output.values; // too bad, so much copying } // Return single element of output matrix template <typename DerivedIn> double fProp(const MatrixBase<DerivedIn> &input, int word, int instance) const { return W->row(word).dot(input.col(instance)) + b(word); } // Dense versions (for log-likelihood loss) template <typename DerivedGOut, typename DerivedGIn> void bProp(const MatrixBase<DerivedGOut> &input_bProp_matrix, const MatrixBase<DerivedGIn> &bProp_matrix) const { // W is vocab_size x output_embedding_dimension // input_bProp_matrix is vocab_size x minibatch_size // bProp_matrix is output_embedding_dimension x minibatch_size UNCONST(DerivedGIn, bProp_matrix, my_bProp_matrix); my_bProp_matrix.leftCols(input_bProp_matrix.cols()).noalias() = W->transpose() * input_bProp_matrix; } template <typename DerivedIn, typename DerivedGOut> void computeGradient(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOut> &bProp_input, double learning_rate, double momentum) //not sure if we want to use momentum here { // W is vocab_size x output_embedding_dimension // b is vocab_size x 1 // predicted_embeddings is output_embedding_dimension x minibatch_size // bProp_input is vocab_size x minibatch_size W->noalias() += learning_rate * bProp_input * predicted_embeddings.transpose(); b += learning_rate * bProp_input.rowwise().sum(); /* //GRADIENT CLIPPING W->noalias() += learning_rate * ((bProp_input * predicted_embeddings.transpose()).array().unaryExpr(Clipper())).matrix(); b += learning_rate * (bProp_input.rowwise().sum().array().unaryExpr(Clipper())).matrix(); //UPDATE CLIPPING W->noalias() += (learning_rate * (bProp_input * predicted_embeddings.transpose())).array().unaryExpr(Clipper()).matrix(); b += (learning_rate * (bProp_input.rowwise().sum())).array().unaryExpr(Clipper()).matrix(); */ } template <typename DerivedIn, typename DerivedGOut> void computeGradientAdagrad( const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOut> &bProp_input, double learning_rate) //not sure if we want to use momentum here { // W is vocab_size x output_embedding_dimension // b is vocab_size x 1 // predicted_embeddings is output_embedding_dimension x minibatch_size // bProp_input is vocab_size x minibatch_sizea W_gradient.setZero(W->rows(), W->cols()); b_gradient.setZero(b.size()); W_gradient.noalias() = bProp_input * predicted_embeddings.transpose(); b_gradient.noalias() = bProp_input.rowwise().sum(); W_running_gradient += W_gradient.array().square().matrix(); b_running_gradient += b_gradient.array().square().matrix(); W->noalias() += learning_rate * (W_gradient.array()/W_running_gradient.array().sqrt()).matrix(); b += learning_rate * (b_gradient.array()/b_running_gradient.array().sqrt()).matrix(); /* //UPDATE CLIPPING *W += (learning_rate * (W_gradient.array()/W_running_gradient.array().sqrt())).unaryExpr(Clipper()).matrix(); b += (learning_rate * (b_gradient.array()/b_running_gradient.array().sqrt())).unaryExpr(Clipper()).matrix(); */ } template <typename DerivedIn, typename DerivedGOut> void computeGradientAdadelta(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOut> &bProp_input, double learning_rate, double conditioning_constant, double decay) //not sure if we want to use momentum here { // W is vocab_size x output_embedding_dimension // b is vocab_size x 1 // predicted_embeddings is output_embedding_dimension x minibatch_size // bProp_input is vocab_size x minibatch_size Array<double,Dynamic,Dynamic> W_current_parameter_update; Array<double,Dynamic,1> b_current_parameter_update; W_gradient.setZero(W->rows(), W->cols()); b_gradient.setZero(b.size()); W_gradient.noalias() = bProp_input * predicted_embeddings.transpose(); b_gradient.noalias() = bProp_input.rowwise().sum(); W_running_gradient = decay*W_running_gradient + (1.-decay)*W_gradient.array().square().matrix(); b_running_gradient = decay*b_running_gradient+ (1.-decay)*b_gradient.array().square().matrix(); W_current_parameter_update = ((W_running_parameter_update.array()+conditioning_constant).sqrt()/ (W_running_gradient.array()+conditioning_constant).sqrt())* W_gradient.array(); b_current_parameter_update = ((b_running_parameter_update.array()+conditioning_constant).sqrt()/ (b_running_gradient.array()+conditioning_constant).sqrt())* b_gradient.array(); W_running_parameter_update = decay*W_running_parameter_update + (1.-decay)*W_current_parameter_update.square().matrix(); b_running_parameter_update = decay*b_running_parameter_update + (1.-decay)*b_current_parameter_update.square().matrix(); *W += learning_rate*W_current_parameter_update.matrix(); b += learning_rate*b_current_parameter_update.matrix(); } // Sparse versions template <typename DerivedGOutI, typename DerivedGOutV, typename DerivedGIn> void bProp(const MatrixBase<DerivedGOutI> &samples, const MatrixBase<DerivedGOutV> &weights, const MatrixBase<DerivedGIn> &bProp_matrix) const { UNCONST(DerivedGIn, bProp_matrix, my_bProp_matrix); my_bProp_matrix.setZero(); uscgemm(1.0, W->transpose(), USCMatrix<double>(W->rows(), samples, weights), my_bProp_matrix.leftCols(samples.cols())); // narrow bProp_matrix for possible short minibatch } template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV> void computeGradient(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOutI> &samples, const MatrixBase<DerivedGOutV> &weights, double learning_rate, double momentum) //not sure if we want to use momentum here { //cerr<<"in gradient"<<endl; USCMatrix<double> gradient_output(W->rows(), samples, weights); uscgemm(learning_rate, gradient_output, predicted_embeddings.leftCols(gradient_output.cols()).transpose(), *W); // narrow predicted_embeddings for possible short minibatch uscgemv(learning_rate, gradient_output, Matrix<double,Dynamic,1>::Ones(gradient_output.cols()), b); /* //IN ORDER TO IMPLEMENT CLIPPING, WE HAVE TO COMPUTE THE GRADIENT //FIRST USCMatrix<double> gradient_output(W->rows(), samples, weights); uscgemm(1.0, gradient_output, predicted_embeddings.leftCols(samples.cols()).transpose(), W_gradient); uscgemv(1.0, gradient_output, Matrix<double,Dynamic,1>::Ones(weights.cols()), b_gradient); int_map update_map; //stores all the parameters that have been updated for (int sample_id=0; sample_id<samples.rows(); sample_id++) for (int train_id=0; train_id<samples.cols(); train_id++) update_map[samples(sample_id, train_id)] = 1; // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) update_items.push_back(it->first); int num_items = update_items.size(); //#pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { int update_item = update_items[item_id]; //W->row(update_item) += learning_rate * W_gradient.row(update_item); //b(update_item) += learning_rate * b_gradient(update_item); //UPDATE CLIPPING W->row(update_item) += (learning_rate * W_gradient.row(update_item)).array().unaryExpr(Clipper()).matrix(); double update = learning_rate * b_gradient(update_item); b(update_item) += std::min(0.5, std::max(update,-0.5)); //GRADIENT CLIPPING W_gradient.row(update_item).setZero(); b_gradient(update_item) = 0.; } */ //cerr<<"Finished gradient"<<endl; } template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV> void computeGradientAdagrad(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOutI> &samples, const MatrixBase<DerivedGOutV> &weights, double learning_rate) //not sure if we want to use momentum here { //W_gradient.setZero(W->rows(), W->cols()); //b_gradient.setZero(b.size()); //FOR CLIPPING, WE DO NOT MULTIPLY THE GRADIENT WITH THE LEARNING RATE USCMatrix<double> gradient_output(W->rows(), samples, weights); uscgemm(1.0, gradient_output, predicted_embeddings.leftCols(samples.cols()).transpose(), W_gradient); uscgemv(1.0, gradient_output, Matrix<double,Dynamic,1>::Ones(weights.cols()), b_gradient); int_map update_map; //stores all the parameters that have been updated for (int sample_id=0; sample_id<samples.rows(); sample_id++) for (int train_id=0; train_id<samples.cols(); train_id++) update_map[samples(sample_id, train_id)] = 1; // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) update_items.push_back(it->first); int num_items = update_items.size(); //#pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { int update_item = update_items[item_id]; W_running_gradient.row(update_item) += W_gradient.row(update_item).array().square().matrix(); b_running_gradient(update_item) += b_gradient(update_item) * b_gradient(update_item); W->row(update_item) += learning_rate * (W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt()).matrix(); b(update_item) += learning_rate * b_gradient(update_item) / sqrt(b_running_gradient(update_item)); /* //UPDATE CLIPPING W->row(update_item) += (learning_rate * (W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt())).unaryExpr(Clipper()).matrix(); double update = learning_rate * b_gradient(update_item) / sqrt(b_running_gradient(update_item)); b(update_item) += Clipper(update);//std::min(0.5, std::max(update,-0.5)); */ W_gradient.row(update_item).setZero(); b_gradient(update_item) = 0.; } } template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV> void computeGradientAdadelta(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOutI> &samples, const MatrixBase<DerivedGOutV> &weights, double learning_rate, double conditioning_constant, double decay) //not sure if we want to use momentum here { //cerr<<"decay is "<<decay<<" and constant is "<<conditioning_constant<<endl; //W_gradient.setZero(W->rows(), W->cols()); //b_gradient.setZero(b.size()); USCMatrix<double> gradient_output(W->rows(), samples, weights); uscgemm(1.0, gradient_output, predicted_embeddings.leftCols(samples.cols()).transpose(), W_gradient); uscgemv(1.0, gradient_output, Matrix<double,Dynamic,1>::Ones(weights.cols()), b_gradient); int_map update_map; //stores all the parameters that have been updated for (int sample_id=0; sample_id<samples.rows(); sample_id++) for (int train_id=0; train_id<samples.cols(); train_id++) update_map[samples(sample_id, train_id)] = 1; // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) update_items.push_back(it->first); int num_items = update_items.size(); #pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { Array<double,1,Dynamic> W_current_parameter_update; double b_current_parameter_update; int update_item = update_items[item_id]; W_running_gradient.row(update_item) = decay*W_running_gradient.row(update_item)+ (1.-decay)*W_gradient.row(update_item).array().square().matrix(); b_running_gradient(update_item) = decay*b_running_gradient(update_item)+ (1.-decay)*b_gradient(update_item)*b_gradient(update_item); //cerr<<"Output: W gradient is "<<W_gradient.row(update_item)<<endl; //getchar(); //cerr<<"Output: W running gradient is "<<W_running_gradient.row(update_item)<<endl; //getchar(); W_current_parameter_update = ((W_running_parameter_update.row(update_item).array()+conditioning_constant).sqrt()/ (W_running_gradient.row(update_item).array()+conditioning_constant).sqrt())* W_gradient.row(update_item).array(); b_current_parameter_update = (sqrt(b_running_parameter_update(update_item)+conditioning_constant)/ sqrt(b_running_gradient(update_item)+conditioning_constant))* b_gradient(update_item); //cerr<<"Output: W current parameter update is "<<W_current_parameter_update<<endl; //getchar(); //cerr<<"Output: W running parameter update before is "<<W_running_parameter_update.row(update_item)<<endl; //getchar(); //cerr<<"the second term is "<<(1.-decay)*W_current_parameter_update.square().matrix()<<endl; W_running_parameter_update.row(update_item) = decay*W_running_parameter_update.row(update_item)+ (1.-decay)*(W_current_parameter_update.square().matrix()); b_running_parameter_update(update_item) = decay*b_running_parameter_update(update_item)+ (1.-decay)*b_current_parameter_update*b_current_parameter_update; //cerr<<"Output: W running parameter update is "<<W_running_parameter_update.row(update_item)<<endl; //getchar(); W->row(update_item) += learning_rate*W_current_parameter_update.matrix(); b(update_item) += learning_rate*b_current_parameter_update; W_gradient.row(update_item).setZero(); b_gradient(update_item) = 0.; } } template <typename DerivedIn, typename DerivedGOutI, typename DerivedGOutV, typename DerivedGW, typename DerivedGb> void computeGradientCheck(const MatrixBase<DerivedIn> &predicted_embeddings, const MatrixBase<DerivedGOutI> &samples, const MatrixBase<DerivedGOutV> &weights, const MatrixBase<DerivedGW> &gradient_W, const MatrixBase<DerivedGb> &gradient_b) const { UNCONST(DerivedGW, gradient_W, my_gradient_W); UNCONST(DerivedGb, gradient_b, my_gradient_b); my_gradient_W.setZero(); my_gradient_b.setZero(); USCMatrix<double> gradient_output(W->rows(), samples, weights); uscgemm(1.0, gradient_output, predicted_embeddings.leftCols(samples.cols()).transpose(), my_gradient_W); uscgemv(1.0, gradient_output, Matrix<double,Dynamic,1>::Ones(weights.cols()), my_gradient_b); } }; class Input_word_embeddings { private: Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *W; int context_size, vocab_size; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_running_gradient; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_running_parameter_update; Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> W_gradient; friend class model; public: Input_word_embeddings() : context_size(0), vocab_size(0) { } Input_word_embeddings(int rows, int cols, int context) { resize(rows, cols, context); } void set_W(Matrix<double,Dynamic,Dynamic,Eigen::RowMajor> *input_W) { W = input_W; } void resize(int rows, int cols, int context) { context_size = context; vocab_size = rows; W->setZero(rows, cols); } void read(std::ifstream &W_file) { readMatrix(W_file, *W); } void write(std::ofstream &W_file) { writeMatrix(*W, W_file); } template <typename Engine> void initialize(Engine &engine, bool init_normal, double init_range, string &parameter_update, double adagrad_epsilon) { W_gradient.setZero(W->rows(),W->cols()); if (parameter_update == "ADA") { W_running_gradient = Matrix<double,Dynamic,Dynamic>::Ones(W->rows(),W->cols())*adagrad_epsilon; //W_gradient.setZero(W->rows(),W->cols()); } if (parameter_update == "ADAD") { W_running_gradient.setZero(W->rows(),W->cols()); //W_gradient.setZero(W->rows(),W->cols()); W_running_parameter_update.setZero(W->rows(),W->cols()); } initMatrix(engine, *W, init_normal, init_range); } int n_inputs() const { return -1; } int n_outputs() const { return W->cols() * context_size; } // set output_id's embedding to the weighted average of all embeddings template <typename Dist> void average(const Dist &dist, int output_id) { W->row(output_id).setZero(); for (int i=0; i < W->rows(); i++) if (i != output_id) W->row(output_id) += dist.prob(i) * W->row(i); } template <typename DerivedIn, typename DerivedOut> void fProp(const MatrixBase<DerivedIn> &input, const MatrixBase<DerivedOut> &output) const { int embedding_dimension = W->cols(); // W is vocab_size x embedding_dimension // input is ngram_size*vocab_size x minibatch_size // output is ngram_size*embedding_dimension x minibatch_size /* // Dense version: for (int ngram=0; ngram<context_size; ngram++) output.middleRows(ngram*embedding_dimension, embedding_dimension) = W.transpose() * input.middleRows(ngram*vocab_size, vocab_size); */ UNCONST(DerivedOut, output, my_output); my_output.setZero(); for (int ngram=0; ngram<context_size; ngram++) { // input might be narrower than expected due to a short minibatch, // so narrow output to match uscgemm(1.0, W->transpose(), USCMatrix<double>(W->rows(),input.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input.cols())), my_output.block(ngram*embedding_dimension, 0, embedding_dimension, input.cols())); } } // When model is premultiplied, this layer doesn't get used, // but this method is used to get the input into a sparse matrix. // Hopefully this can get eliminated someday template <typename DerivedIn, typename ScalarOut> void munge(const MatrixBase<DerivedIn> &input, USCMatrix<ScalarOut> &output) const { output.resize(vocab_size*context_size, context_size, input.cols()); for (int i=0; i < context_size; i++) output.indexes.row(i).array() = input.row(i).array() + i*vocab_size; output.values.fill(1.0); } template <typename DerivedGOut, typename DerivedIn> void computeGradient(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &input_words, double learning_rate, double momentum, double L2_reg) { int embedding_dimension = W->cols(); // W is vocab_size x embedding_dimension // input is ngram_size*vocab_size x minibatch_size // bProp_input is ngram_size*embedding_dimension x minibatch_size /* // Dense version: for (int ngram=0; ngram<context_size; ngram++) W += learning_rate * input_words.middleRows(ngram*vocab_size, vocab_size) * bProp_input.middleRows(ngram*embedding_dimension, embedding_dimension).transpose() */ for (int ngram=0; ngram<context_size; ngram++) { uscgemm(learning_rate, USCMatrix<double>(W->rows(), input_words.middleRows(ngram, 1), Matrix<double,1,Dynamic>::Ones(input_words.cols())), bProp_input.block(ngram*embedding_dimension,0,embedding_dimension,input_words.cols()).transpose(), *W); } /* //IF WE WANT TO DO GRADIENT CLIPPING, THEN WE FIRST COMPUTE THE GRADIENT AND THEN //PERFORM CLIPPING WHILE UPDATING for (int ngram=0; ngram<context_size; ngram++) { uscgemm(1.0, USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())), bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(), W_gradient); } int_map update_map; //stores all the parameters that have been updated for (int ngram=0; ngram<context_size; ngram++) { for (int train_id=0; train_id<input_words.cols(); train_id++) { update_map[input_words(ngram,train_id)] = 1; } } // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) { update_items.push_back(it->first); } int num_items = update_items.size(); #pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { int update_item = update_items[item_id]; //UPDATE CLIPPING W->row(update_item) += (learning_rate* W_gradient.row(update_item).array().unaryExpr(Clipper())).matrix(); //GRADIENT CLIPPING //W->row(update_item) += learning_rate* // W_gradient.row(update_item).array().unaryExpr(Clipper()).matrix(); //SETTING THE GRADIENT TO ZERO W_gradient.row(update_item).setZero(); } */ } template <typename DerivedGOut, typename DerivedIn> void computeGradientAdagrad(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &input_words, double learning_rate, double L2_reg) { int embedding_dimension = W->cols(); //W_gradient.setZero(W->rows(), W->cols()); /* if (W_running_gradient.rows() != W->rows() || W_running_gradient.cols() != W->cols()) W_running_gradient = Ones(W->rows(), W->cols())*adagrad_epsilon; */ for (int ngram=0; ngram<context_size; ngram++) { uscgemm(1.0, USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())), bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(), W_gradient); } int_map update_map; //stores all the parameters that have been updated for (int ngram=0; ngram<context_size; ngram++) { for (int train_id=0; train_id<input_words.cols(); train_id++) { update_map[input_words(ngram,train_id)] = 1; } } // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) { update_items.push_back(it->first); } int num_items = update_items.size(); #pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { int update_item = update_items[item_id]; W_running_gradient.row(update_item) += W_gradient.row(update_item).array().square().matrix(); W->row(update_item) += learning_rate * (W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt()).matrix(); /* //UPDATE CLIPPING W->row(update_item) += (learning_rate * (W_gradient.row(update_item).array() / W_running_gradient.row(update_item).array().sqrt())) .unaryExpr(Clipper()).matrix(); */ W_gradient.row(update_item).setZero(); } } template <typename DerivedGOut, typename DerivedIn> void computeGradientAdadelta(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &input_words, double learning_rate, double L2_reg, double conditioning_constant, double decay) { int embedding_dimension = W->cols(); //W_gradient.setZero(W->rows(), W->cols()); /* if (W_running_gradient.rows() != W->rows() || W_running_gradient.cols() != W->cols()) W_running_gradient = Ones(W->rows(), W->cols())*adagrad_epsilon; */ for (int ngram=0; ngram<context_size; ngram++) { uscgemm(1.0, USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())), bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(), W_gradient); } int_map update_map; //stores all the parameters that have been updated for (int ngram=0; ngram<context_size; ngram++) { for (int train_id=0; train_id<input_words.cols(); train_id++) { update_map[input_words(ngram,train_id)] = 1; } } // Convert to std::vector for parallelization std::vector<int> update_items; for (int_map::iterator it = update_map.begin(); it != update_map.end(); ++it) { update_items.push_back(it->first); } int num_items = update_items.size(); #pragma omp parallel for for (int item_id=0; item_id<num_items; item_id++) { Array<double,1,Dynamic> W_current_parameter_update; int update_item = update_items[item_id]; W_running_gradient.row(update_item) = decay*W_running_gradient.row(update_item)+ (1.-decay)*W_gradient.row(update_item).array().square().matrix(); W_current_parameter_update = ((W_running_parameter_update.row(update_item).array()+conditioning_constant).sqrt()/ (W_running_gradient.row(update_item).array()+conditioning_constant).sqrt())* W_gradient.row(update_item).array(); //cerr<<"Input: W current parameter update is "<<W_current_parameter_update<<endl; //getchar(); W_running_parameter_update.row(update_item) = decay*W_running_parameter_update.row(update_item)+ (1.-decay)*W_current_parameter_update.square().matrix(); W->row(update_item) += learning_rate*W_current_parameter_update.matrix(); //cerr<<"Input: After update, W is "<<W->row(update_item)<<endl; //getchar(); W_gradient.row(update_item).setZero(); } } template <typename DerivedGOut, typename DerivedIn, typename DerivedGW> void computeGradientCheck(const MatrixBase<DerivedGOut> &bProp_input, const MatrixBase<DerivedIn> &input_words, int x, int minibatch_size, const MatrixBase<DerivedGW> &gradient) const //not sure if we want to use momentum here { UNCONST(DerivedGW, gradient, my_gradient); int embedding_dimension = W->cols(); my_gradient.setZero(); for (int ngram=0; ngram<context_size; ngram++) uscgemm(1.0, USCMatrix<double>(W->rows(),input_words.middleRows(ngram, 1),Matrix<double,1,Dynamic>::Ones(input_words.cols())), bProp_input.block(ngram*embedding_dimension, 0, embedding_dimension, input_words.cols()).transpose(), my_gradient); } }; } // namespace nplm
pe_handler.h
/** * Author: Kun Sun ([email protected]) * Date: Mar, 2021 * This program is part of the Ktrim package **/ #include <fstream> #include <sstream> #include <algorithm> #include <thread> #include <ctime> #include <stdlib.h> #include <memory.h> #include <omp.h> #include "common.h" using namespace std; void inline CPEREAD_resize( CPEREAD * read, int n ) { read->size = n; read->seq1[ n ] = 0; read->qual1[ n ] = 0; read->seq2[ n ] = 0; read->qual2[ n ] = 0; } bool inline is_revcomp( const char a, const char b ) { //TODO: consider how to deal with N, call it positive or negative??? switch( a ) { case 'A': return b=='T'; case 'C': return b=='G'; case 'G': return b=='C'; case 'T': return b=='A'; default : return false; } } void init_kstat_wrbuffer( ktrim_stat &kstat, writeBuffer &writebuffer, unsigned int nthread ) { kstat.dropped = new unsigned int [ nthread ]; kstat.real_adapter = new unsigned int [ nthread ]; kstat.tail_adapter = new unsigned int [ nthread ]; kstat.dimer = new unsigned int [ nthread ]; // buffer for storing the modified reads per thread writebuffer.buffer1 = new char * [ nthread ]; writebuffer.buffer2 = new char * [ nthread ]; writebuffer.b1stored = new unsigned int [ nthread ]; writebuffer.b2stored = new unsigned int [ nthread ]; for(unsigned int i=0; i!=nthread; ++i) { writebuffer.buffer1[i] = new char[ BUFFER_SIZE_PER_BATCH_READ ]; writebuffer.buffer2[i] = new char[ BUFFER_SIZE_PER_BATCH_READ ]; writebuffer.b1stored[i] = 0; writebuffer.b2stored[i] = 0; kstat.dropped[i] = 0; kstat.real_adapter[i] = 0; kstat.tail_adapter[i] = 0; kstat.dimer[i] = 0; } } void find_seed_pe( vector<unsigned int> &seed, const CPEREAD *read, const ktrim_param & kp ) { seed.clear(); register const char *poffset = read->seq1; register const char *indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index1 ); if( indexloc == NULL ) break; seed.push_back( indexloc - poffset ); ++ indexloc; } poffset = read->seq2; indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index2 ); if( indexloc == NULL ) break; seed.push_back( indexloc - poffset ); ++ indexloc; } sort( seed.begin(), seed.end() ); } // this function is slower than C++ version void workingThread_PE_C( unsigned int tn, unsigned int start, unsigned int end, CPEREAD *workingReads, ktrim_stat * kstat, writeBuffer * writebuffer, const ktrim_param & kp ) { writebuffer->b1stored[tn] = 0; writebuffer->b2stored[tn] = 0; // vector<unsigned int> seed; // vector<unsigned int> :: iterator it, end_of_seed; register int *seed = new int[ MAX_SEED_NUM ]; register int hit_seed; register int *it, *end_of_seed; register CPEREAD *wkr = workingReads + start; for( unsigned int iii=end-start; iii; --iii, ++wkr ) { // read size handling if( wkr->size > wkr->size2 ) wkr->size = wkr->size2; // remove the tail '\n' // in fact, it is not essential to do this step, because '\n' has a very low ascii value (10) // therefore it will be quality-trimmed CPEREAD_resize( wkr, wkr->size - 1 ); // quality control register int i = get_quality_trim_cycle_pe( wkr, kp ); if( i == 0 ) { // not long enough ++ kstat->dropped[ tn ]; continue; } if( i != wkr->size ) { // quality-trim occurs CPEREAD_resize( wkr, i ); } // looking for seed target, 1 mismatch is allowed for these 2 seeds // which means seq1 and seq2 at least should take 1 perfect seed match //find_seed_pe( seed, wkr, kp ); //TODO: I donot need to find all the seeds, I can find-check, then next // seed.clear(); hit_seed = 0; register const char *poffset = wkr->seq1; register const char *indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index1 ); if( indexloc == NULL ) break; //seed.push_back( indexloc - poffset ); seed[ hit_seed++ ] = indexloc - poffset; ++ indexloc; } poffset = wkr->seq2; indexloc = poffset; while( true ) { indexloc = strstr( indexloc, kp.adapter_index2 ); if( indexloc == NULL ) break; //seed.push_back( indexloc - poffset ); seed[ hit_seed++ ] = indexloc - poffset; ++ indexloc; } //sort( seed.begin(), seed.end() ); end_of_seed = seed + hit_seed; if( hit_seed != 0 ) sort( seed, seed + hit_seed ); register unsigned int last_seed = impossible_seed; // a position which cannot be a seed //end_of_seed = seed.end(); //for( it=seed.begin(); it!=end_of_seed; ++it ) { for( it=seed; it!=end_of_seed; ++it ) { if( *it != last_seed ) { // as there maybe the same value in seq1_seed and seq2_seed, // use this to avoid re-calculate that pos if( check_mismatch_dynamic_PE_C( wkr, *it, kp ) ) break; last_seed = *it; } } if( it != end_of_seed ) { // adapter found ++ kstat->real_adapter[tn]; if( *it >= kp.min_length ) { CPEREAD_resize( wkr, *it ); } else { // drop this read as its length is not enough ++ kstat->dropped[tn]; if( *it <= DIMER_INSERT ) ++ kstat->dimer[tn]; continue; } } else { // seed not found, now check the tail 2 or 1, if perfect match, drop these 2 i = wkr->size - 2; const char *p = wkr->seq1; const char *q = wkr->seq2; if( p[i]==kp.adapter_r1[0] && p[i+1]==kp.adapter_r1[1] && q[i]==kp.adapter_r2[0] && q[i+1]==kp.adapter_r2[1] ) { // a possible hit // if it is a real adapter, then Read1 and Read2 should be complimentary // in real data, the heading 5 bp are of poor quality, therefoe we test the 6th, 7th if( is_revcomp(p[5], q[i-6]) && is_revcomp(q[5], p[i-6]) ) { ++ kstat->tail_adapter[tn]; if( i < kp.min_length ) { ++ kstat->dropped[tn]; continue; } CPEREAD_resize( wkr, i ); } } else { // tail 2 is not good, check tail 1 ++ i; if( p[i]==kp.adapter_r1[0] && q[i]==kp.adapter_r2[0] ) { if( is_revcomp(p[5], q[i-6]) && is_revcomp(q[5], p[i-6]) && is_revcomp(p[6], q[i-7]) && is_revcomp(q[6], p[i-7]) ) { ++ kstat->tail_adapter[tn]; if( i < kp.min_length ) { ++ kstat->dropped[tn]; continue; } CPEREAD_resize( wkr, i ); } } } } writebuffer->b1stored[tn] += sprintf( writebuffer->buffer1[tn]+writebuffer->b1stored[tn], "%s%s\n+\n%s\n", wkr->id1, wkr->seq1, wkr->qual1 ); writebuffer->b2stored[tn] += sprintf( writebuffer->buffer2[tn]+writebuffer->b2stored[tn], "%s%s\n+\n%s\n", wkr->id2, wkr->seq2, wkr->qual2 ); } delete [] seed; } int process_multi_thread_PE_C( const ktrim_param &kp ) { // IO speed-up ios::sync_with_stdio( false ); // cin.tie( NULL ); // in this version, two data containers are used and auto-swapped for working and loading data CPEREAD *readA, *readB; register char *readA_data, *readB_data; CPEREAD *workingReads, *loadingReads, *swapReads; ktrim_stat kstat; writeBuffer writebuffer; string fileName; vector<string> R1s, R2s; FILE *fout1, *fout2; unsigned int totalFiles; // now I use 2 trheads for init // prepare memory and file omp_set_num_threads( 2 ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); if( tn == 0 ) { readA = new CPEREAD[ READS_PER_BATCH ]; readB = new CPEREAD[ READS_PER_BATCH ]; readA_data = new char[ MEM_PE_READSET ]; readB_data = new char[ MEM_PE_READSET ]; for( register int i=0, j=0; i!=READS_PER_BATCH; ++i ) { readA[i].id1 = readA_data + j; readB[i].id1 = readB_data + j; j += MAX_READ_ID; readA[i].seq1 = readA_data + j; readB[i].seq1 = readB_data + j; j += MAX_READ_CYCLE; readA[i].qual1 = readA_data + j; readB[i].qual1 = readB_data + j; j += MAX_READ_CYCLE; readA[i].id2 = readA_data + j; readB[i].id2 = readB_data + j; j += MAX_READ_ID; readA[i].seq2 = readA_data + j; readB[i].seq2 = readB_data + j; j += MAX_READ_CYCLE; readA[i].qual2 = readA_data + j; readB[i].qual2 = readB_data + j; j += MAX_READ_CYCLE; } } else { init_kstat_wrbuffer( kstat, writebuffer, kp.thread ); // deal with multiple input files extractFileNames( kp.FASTQ1, R1s ); extractFileNames( kp.FASTQ2, R2s ); if( R1s.size() != R2s.size() ) { fprintf( stderr, "\033[1;31mError: Read1 and Read2 do not contain equal sized files!\033[0m\n" ); exit(110); } totalFiles = R1s.size(); //cout << "\033[1;34mINFO: " << totalFiles << " paired fastq files will be loaded.\033[0m\n"; fileName = kp.outpre; fileName += ".read1.fq"; fout1 = fopen( fileName.c_str(), "wt" ); fileName[ fileName.size()-4 ] = '2'; // read1 -> read2 fout2 = fopen( fileName.c_str(), "wt" ); if( fout1==NULL || fout2==NULL ) { fprintf( stderr, "\033[1;31mError: write file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); exit(103); } } } // start analysis register unsigned int line = 0; for( unsigned int fileCnt=0; fileCnt!=totalFiles; ++ fileCnt ) { bool file_is_gz = false; FILE *fq1, *fq2; gzFile gfp1, gfp2; register unsigned int i = R1s[fileCnt].size() - 3; register const char * p = R1s[fileCnt].c_str(); register const char * q = R2s[fileCnt].c_str(); if( p[i]=='.' && p[i+1]=='g' && p[i+2]=='z' ) { file_is_gz = true; gfp1 = gzopen( p, "r" ); gfp2 = gzopen( q, "r" ); if( gfp1==NULL || gfp2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } else { fq1 = fopen( p, "rt" ); fq2 = fopen( q, "rt" ); if( fq1==NULL || fq2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } // fprintf( stderr, "Loading files:\nRead1: %s\nRead2: %s\n", p, q ); // initialization // get first batch of fastq reads unsigned int loaded; bool metEOF; omp_set_num_threads( 2 ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); if( tn == 0 ) { if( file_is_gz ) { loaded = load_batch_data_PE_GZ( gfp1, readA, READS_PER_BATCH, true ); metEOF = gzeof( gfp1 ); } else { loaded = load_batch_data_PE_C( fq1, readA, READS_PER_BATCH, true ); metEOF = feof( fq1 ); } } else { if( file_is_gz ) { loaded = load_batch_data_PE_GZ( gfp2, readA, READS_PER_BATCH, false ); } else { loaded = load_batch_data_PE_C( fq2, readA, READS_PER_BATCH, false ); } } } if( loaded == 0 ) break; loadingReads = readB; workingReads = readA; bool nextBatch = true; unsigned int threadLoaded, threadLoaded2; unsigned int NumWkThreads; while( nextBatch ) { // cerr << "Working on " << loaded << " reads\n"; // start parallalization omp_set_num_threads( kp.thread ); #pragma omp parallel { // clock_t start, end; // start = clock(); unsigned int tn = omp_get_thread_num(); // if EOF is met, then all threads are used for analysis // otherwise 1 thread will do data loading if( metEOF ) { NumWkThreads = kp.thread; unsigned int start = loaded * tn / kp.thread; unsigned int end = loaded * (tn+1) / kp.thread; workingThread_PE_C( tn, start, end, workingReads, &kstat, &writebuffer, kp ); nextBatch = false; } else { // use 2 thread to load files, others for trimming NumWkThreads = kp.thread - 2; if( tn == kp.thread - 1 ) { if( file_is_gz ) { threadLoaded = load_batch_data_PE_GZ( gfp1, loadingReads, READS_PER_BATCH, true ); metEOF = gzeof( gfp1 ); } else { threadLoaded = load_batch_data_PE_C( fq1, loadingReads, READS_PER_BATCH, true ); metEOF = feof( fq1 ); } // cerr << "R1 loaded " << threadLoaded << ", pos=" << gztell(gfp2) << ", EOF=" << gzeof( gfp1 ) << "\n"; nextBatch = (threadLoaded!=0); //cerr << "Loading thread: " << threadLoaded << ", " << metEOF << ", " << nextBatch << '\n'; } else if ( tn == kp.thread - 2 ) { if( file_is_gz ) { threadLoaded2 = load_batch_data_PE_GZ( gfp2, loadingReads, READS_PER_BATCH, false ); } else { threadLoaded2 = load_batch_data_PE_C( fq2, loadingReads, READS_PER_BATCH, false ); } // cerr << "R2 loaded " << threadLoaded2 << ", pos=" << gztell(gfp2) << ", EOF=" << gzeof( gfp2 )<< "\n"; } else { unsigned int start = loaded * tn / NumWkThreads; unsigned int end = loaded * (tn+1) / NumWkThreads; workingThread_PE_C( tn, start, end, workingReads, &kstat, &writebuffer, kp ); } } // end = clock(); // float duration = (end - start)*1000.0 / CLOCKS_PER_SEC; // fprintf( stderr, "Thread %d, runtime %.1f\n", tn, duration ); } // parallel body // write output and update fastq statistics for( unsigned int ii=0; ii!=NumWkThreads; ++ii ) { fwrite( writebuffer.buffer1[ii], sizeof(char), writebuffer.b1stored[ii], fout1 ); } for( unsigned int ii=0; ii!=NumWkThreads; ++ii ) { fwrite( writebuffer.buffer2[ii], sizeof(char), writebuffer.b2stored[ii], fout2 ); } // check whether the read-loading is correct if( threadLoaded != threadLoaded2 ) { cerr << "ERROR: unequal read number for read1 (" << threadLoaded << ") and read2 (" << threadLoaded2 << ")!\n"; exit(1); } line += loaded; loaded = threadLoaded; // swap workingReads and loadingReads for next loop swapReads = loadingReads; loadingReads = workingReads; workingReads = swapReads; // cerr << '\r' << line << " reads loaded\n"; // cerr << line << " reads loaded, metEOF=" << metEOF << ", next=" << nextBatch << "\n"; } if( file_is_gz ) { gzclose( gfp1 ); gzclose( gfp2 ); } else { fclose( fq1 ); fclose( fq2 ); } cerr << '\n'; } // all input files are loaded fclose( fout1 ); fclose( fout2 ); //cerr << "\rDone: " << line << " lines processed.\n"; // write trim.log int dropped_all=0, real_all=0, tail_all=0, dimer_all=0; for( unsigned int i=0; i!=kp.thread; ++i ) { dropped_all += kstat.dropped[i]; real_all += kstat.real_adapter[i]; tail_all += kstat.tail_adapter[i]; dimer_all += kstat.dimer[i]; } fileName = kp.outpre; fileName += ".trim.log"; ofstream fout( fileName.c_str() ); if( fout.fail() ) { fprintf( stderr, "\033[1;34mError: cannot write log file!\033[0m\n" ); return 105; } fout << "Total\t" << line << '\n' << "Dropped\t" << dropped_all << '\n' << "Aadaptor\t" << real_all << '\n' << "TailHit\t" << tail_all << '\n' << "Dimer\t" << dimer_all << '\n'; fout.close(); //free memory for(unsigned int i=0; i!=kp.thread; ++i) { delete writebuffer.buffer1[i]; delete writebuffer.buffer2[i]; } delete [] writebuffer.buffer1; delete [] writebuffer.buffer2; delete [] kstat.dropped; delete [] kstat.real_adapter; delete [] kstat.tail_adapter; delete [] kstat.dimer; delete [] readA; delete [] readB; delete [] readA_data; delete [] readB_data; return 0; } int process_single_thread_PE_C( const ktrim_param &kp ) { // fprintf( stderr, "process_single_thread_PE_C\n" ); // IO speed-up ios::sync_with_stdio( false ); // cin.tie( NULL ); CPEREAD *read = new CPEREAD[ READS_PER_BATCH_ST ]; register char *read_data = new char[ MEM_PE_READSET_ST ]; for( register int i=0, j=0; i!=READS_PER_BATCH; ++i ) { read[i].id1 = read_data + j; j += MAX_READ_ID; read[i].seq1 = read_data + j; j += MAX_READ_CYCLE; read[i].qual1 = read_data + j; j += MAX_READ_CYCLE; read[i].id2 = read_data + j; j += MAX_READ_ID; read[i].seq2 = read_data + j; j += MAX_READ_CYCLE; read[i].qual2 = read_data + j; j += MAX_READ_CYCLE; } ktrim_stat kstat; kstat.dropped = new unsigned int [ 1 ]; kstat.real_adapter = new unsigned int [ 1 ]; kstat.tail_adapter = new unsigned int [ 1 ]; kstat.dimer = new unsigned int [ 1 ]; kstat.dropped[0] = 0; kstat.real_adapter[0] = 0; kstat.tail_adapter[0] = 0; kstat.dimer[0] = 0; // buffer for storing the modified reads per thread writeBuffer writebuffer; writebuffer.buffer1 = new char * [ 1 ]; writebuffer.buffer2 = new char * [ 1 ]; writebuffer.b1stored = new unsigned int [ 1 ]; writebuffer.b2stored = new unsigned int [ 1 ]; writebuffer.buffer1[0] = new char[ BUFFER_SIZE_PER_BATCH_READ_ST ]; writebuffer.buffer2[0] = new char[ BUFFER_SIZE_PER_BATCH_READ_ST ]; // deal with multiple input files vector<string> R1s, R2s; extractFileNames( kp.FASTQ1, R1s ); extractFileNames( kp.FASTQ2, R2s ); if( R1s.size() != R2s.size() ) { fprintf( stderr, "\033[1;31mError: Read1 and Read2 do not contain equal sized files!\033[0m\n" ); return 110; } unsigned int totalFiles = R1s.size(); //cout << "\033[1;34mINFO: " << totalFiles << " paired fastq files will be loaded.\033[0m\n"; FILE *fout1, *fout2; string fileName = kp.outpre; fileName += ".read1.fq"; fout1 = fopen( fileName.c_str(), "wt" ); fileName[ fileName.size()-4 ] = '2'; // read1 -> read2 fout2 = fopen( fileName.c_str(), "wt" ); if( fout1==NULL || fout2==NULL ) { fprintf( stderr, "\033[1;31mError: write file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 103; } register unsigned int line = 0; for( unsigned int fileCnt=0; fileCnt!=totalFiles; ++ fileCnt ) { bool file_is_gz = false; FILE *fq1, *fq2; gzFile gfp1, gfp2; register unsigned int i = R1s[fileCnt].size() - 3; register const char * p = R1s[fileCnt].c_str(); register const char * q = R2s[fileCnt].c_str(); if( p[i]=='.' && p[i+1]=='g' && p[i+2]=='z' ) { file_is_gz = true; gfp1 = gzopen( p, "r" ); gfp2 = gzopen( q, "r" ); if( gfp1==NULL || gfp2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } else { fq1 = fopen( p, "rt" ); fq2 = fopen( q, "rt" ); if( fq1==NULL || fq2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } register unsigned int last_seed; vector<unsigned int> seed; vector<unsigned int> :: iterator it; while( true ) { // get fastq reads unsigned int loaded; if( file_is_gz ) { loaded = load_batch_data_PE_both_GZ( gfp1, gfp2, read, READS_PER_BATCH_ST ); } else { loaded = load_batch_data_PE_both_C( fq1, fq2, read, READS_PER_BATCH_ST ); } if( loaded == 0 ) break; workingThread_PE_C( 0, 0, loaded, read, &kstat, &writebuffer, kp ); // write output and update fastq statistics fwrite( writebuffer.buffer1[0], sizeof(char), writebuffer.b1stored[0], fout1 ); fwrite( writebuffer.buffer2[0], sizeof(char), writebuffer.b2stored[0], fout2 ); line += loaded; //cerr << '\r' << line << " reads loaded"; if( file_is_gz ) { if( gzeof( gfp1 ) ) break; } else { if( feof( fq2 ) ) break; } } if( file_is_gz ) { gzclose( gfp1 ); gzclose( gfp2 ); } else { fclose( fq1 ); fclose( fq2 ); } } fclose( fout1 ); fclose( fout2 ); //cerr << "\rDone: " << line << " lines processed.\n"; // write trim.log fileName = kp.outpre; fileName += ".trim.log"; ofstream fout( fileName.c_str() ); if( fout.fail() ) { fprintf( stderr, "\033[1;34mError: cannot write log file!\033[0m\n" ); return 105; } fout << "Total\t" << line << '\n' << "Dropped\t" << kstat.dropped[0] << '\n' << "Aadaptor\t" << kstat.real_adapter[0] << '\n' << "TailHit\t" << kstat.tail_adapter[0] << '\n' << "Dimer\t" << kstat.dimer[0] << '\n'; fout.close(); delete [] read; delete [] read_data; return 0; } int process_two_thread_PE_C( const ktrim_param &kp ) { // IO speed-up ios::sync_with_stdio( false ); // cin.tie( NULL ); // in this version, two data containers are used and auto-swapped for working and loading data CPEREAD *readA, *readB; register char *readA_data, *readB_data; CPEREAD *workingReads, *loadingReads, *swapReads; ktrim_stat kstat; writeBuffer writebuffer; string fileName; vector<string> R1s, R2s; FILE *fout1, *fout2; unsigned int totalFiles; // now I use 2 trheads for init // prepare memory and file omp_set_num_threads( 2 ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); if( tn == 0 ) { readA = new CPEREAD[ READS_PER_BATCH ]; readB = new CPEREAD[ READS_PER_BATCH ]; readA_data = new char[ MEM_PE_READSET ]; readB_data = new char[ MEM_PE_READSET ]; for( register int i=0, j=0; i!=READS_PER_BATCH; ++i ) { readA[i].id1 = readA_data + j; readB[i].id1 = readB_data + j; j += MAX_READ_ID; readA[i].seq1 = readA_data + j; readB[i].seq1 = readB_data + j; j += MAX_READ_CYCLE; readA[i].qual1 = readA_data + j; readB[i].qual1 = readB_data + j; j += MAX_READ_CYCLE; readA[i].id2 = readA_data + j; readB[i].id2 = readB_data + j; j += MAX_READ_ID; readA[i].seq2 = readA_data + j; readB[i].seq2 = readB_data + j; j += MAX_READ_CYCLE; readA[i].qual2 = readA_data + j; readB[i].qual2 = readB_data + j; j += MAX_READ_CYCLE; } } else { init_kstat_wrbuffer( kstat, writebuffer, kp.thread ); // deal with multiple input files extractFileNames( kp.FASTQ1, R1s ); extractFileNames( kp.FASTQ2, R2s ); if( R1s.size() != R2s.size() ) { fprintf( stderr, "\033[1;31mError: Read1 and Read2 do not contain equal sized files!\033[0m\n" ); exit(110); } totalFiles = R1s.size(); //cout << "\033[1;34mINFO: " << totalFiles << " paired fastq files will be loaded.\033[0m\n"; fileName = kp.outpre; fileName += ".read1.fq"; fout1 = fopen( fileName.c_str(), "wt" ); fileName[ fileName.size()-4 ] = '2'; // read1 -> read2 fout2 = fopen( fileName.c_str(), "wt" ); if( fout1==NULL || fout2==NULL ) { fprintf( stderr, "\033[1;31mError: write file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); exit(103); } } } register unsigned int line = 0; for( unsigned int fileCnt=0; fileCnt!=totalFiles; ++ fileCnt ) { bool file_is_gz = false; FILE *fq1, *fq2; gzFile gfp1, gfp2; register unsigned int i = R1s[fileCnt].size() - 3; register const char * p = R1s[fileCnt].c_str(); register const char * q = R2s[fileCnt].c_str(); if( p[i]=='.' && p[i+1]=='g' && p[i+2]=='z' ) { file_is_gz = true; gfp1 = gzopen( p, "r" ); gfp2 = gzopen( q, "r" ); if( gfp1==NULL || gfp2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } else { fq1 = fopen( p, "rt" ); fq2 = fopen( q, "rt" ); if( fq1==NULL || fq2==NULL ) { fprintf( stderr, "\033[1;31mError: open fastq file failed!\033[0m\n" ); fclose( fout1 ); fclose( fout2 ); return 104; } } // fprintf( stderr, "Loading files:\nRead1: %s\nRead2: %s\n", p, q ); // initialization // get first batch of fastq reads // PUT NEW CODES HERE unsigned int loaded; bool metEOF; omp_set_num_threads( 2 ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); if( tn == 0 ) { if( file_is_gz ) { loaded = load_batch_data_PE_GZ( gfp1, readA, READS_PER_BATCH, true ); metEOF = gzeof( gfp1 ); } else { loaded = load_batch_data_PE_C( fq1, readA, READS_PER_BATCH, true ); metEOF = feof( fq1 ); } } else { if( file_is_gz ) { loaded = load_batch_data_PE_GZ( gfp2, readA, READS_PER_BATCH, false ); } else { loaded = load_batch_data_PE_C( fq2, readA, READS_PER_BATCH, false ); } } } if( loaded == 0 ) break; loadingReads = readB; workingReads = readA; bool nextBatch = true; unsigned int threadLoaded; unsigned int NumWkThreads; while( nextBatch ) { // start parallalization omp_set_num_threads( 2 ); #pragma omp parallel { unsigned int tn = omp_get_thread_num(); // if EOF is met, then all threads are used for analysis // otherwise 1 thread will do data loading if( metEOF ) { NumWkThreads = 2; unsigned int start = loaded * tn / 2; unsigned int end = loaded * (tn+1) / 2; workingThread_PE_C( tn, start, end, workingReads, &kstat, &writebuffer, kp ); nextBatch = false; } else { // use 1 thread to load files, others for trimming NumWkThreads = 1; if( tn == 1 ) { if( file_is_gz ) { threadLoaded = load_batch_data_PE_both_GZ( gfp1, gfp2, loadingReads, READS_PER_BATCH ); metEOF = gzeof( gfp1 ); } else { threadLoaded = load_batch_data_PE_both_C( fq1, fq2, loadingReads, READS_PER_BATCH ); metEOF = feof( fq1 ); } nextBatch = (threadLoaded!=0); //cerr << "Loading thread: " << threadLoaded << ", " << metEOF << ", " << nextBatch << '\n'; } else { workingThread_PE_C( tn, 0, loaded, workingReads, &kstat, &writebuffer, kp ); } } } // parallel body // write output and update fastq statistics for( unsigned int ii=0; ii!=NumWkThreads; ++ii ) { fwrite( writebuffer.buffer1[ii], sizeof(char), writebuffer.b1stored[ii], fout1 ); } for( unsigned int ii=0; ii!=NumWkThreads; ++ii ) { fwrite( writebuffer.buffer2[ii], sizeof(char), writebuffer.b2stored[ii], fout2 ); } line += loaded; loaded = threadLoaded; // swap workingReads and loadingReads for next loop swapReads = loadingReads; loadingReads = workingReads; workingReads = swapReads; // cerr << '\r' << line << " reads loaded"; // cerr << line << " reads loaded, metEOF=" << metEOF << ", next=" << nextBatch << "\n"; } if( file_is_gz ) { gzclose( gfp1 ); gzclose( gfp2 ); } else { fclose( fq1 ); fclose( fq2 ); } cerr << '\n'; } // all input files are loaded fclose( fout1 ); fclose( fout2 ); //cerr << "\rDone: " << line << " lines processed.\n"; // write trim.log int dropped_all=0, real_all=0, tail_all=0, dimer_all=0; for( unsigned int i=0; i!=kp.thread; ++i ) { dropped_all += kstat.dropped[i]; real_all += kstat.real_adapter[i]; tail_all += kstat.tail_adapter[i]; dimer_all += kstat.dimer[i]; } fileName = kp.outpre; fileName += ".trim.log"; ofstream fout( fileName.c_str() ); if( fout.fail() ) { fprintf( stderr, "\033[1;34mError: cannot write log file!\033[0m\n" ); return 105; } fout << "Total\t" << line << '\n' << "Dropped\t" << dropped_all << '\n' << "Aadaptor\t" << real_all << '\n' << "TailHit\t" << tail_all << '\n' << "Dimer\t" << dimer_all << '\n'; fout.close(); //free memory for(unsigned int i=0; i!=kp.thread; ++i) { delete writebuffer.buffer1[i]; delete writebuffer.buffer2[i]; } delete [] writebuffer.buffer1; delete [] writebuffer.buffer2; delete [] kstat.dropped; delete [] kstat.real_adapter; delete [] kstat.tail_adapter; delete [] kstat.dimer; delete [] readA; delete [] readB; delete [] readA_data; delete [] readB_data; return 0; }
opencl_dmg_fmt_plug.c
/* * DMG cracker patch for JtR. Hacked together during August of 2012 * by Dhiru Kholia <dhiru.kholia at gmail.com> * * This software is Copyright (c) 2012 Lukas Odzioba <[email protected]> * Copyright (c) 2015, magnum * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ /* * Debug levels: * 1 show what "test" hits * 2 dump printables from the decrypted blocks * 3 dump hex from the decrypted blocks * 4 dump decrypted blocks to files (will overwrite with no mercy): * dmg.debug.main main block * dmg.debug alternate block (if present, this is the start block) */ //#define DMG_DEBUG 2 #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_dmg; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_dmg); #else #include <string.h> #include <openssl/des.h> #include "aes.h" #include "hmac_sha.h" #ifdef _OPENMP #include <omp.h> #endif #ifdef DMG_DEBUG #define NEED_OS_FLOCK #include "os.h" #endif #include "arch.h" #include "formats.h" #include "common.h" #include "stdint.h" #include "options.h" #include "jumbo.h" #include "loader.h" #include "common-opencl.h" #define FORMAT_LABEL "dmg-opencl" #define FORMAT_NAME "Apple DMG" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL 3DES/AES" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1001 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(uint32_t) #undef HTONL #define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \ ((((unsigned long)(n) & 0xFF00)) << 8) | \ ((((unsigned long)(n) & 0xFF0000)) >> 8) | \ ((((unsigned long)(n) & 0xFF000000)) >> 24)) #ifdef DMG_DEBUG extern volatile int bench_running; #endif typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } dmg_password; typedef struct { uint32_t v[32/4]; } dmg_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } dmg_salt; static int *cracked; static int any_cracked; static struct custom_salt { unsigned int saltlen; unsigned char salt[20]; unsigned int ivlen; unsigned char iv[32]; int headerver; unsigned char chunk[8192]; uint32_t encrypted_keyblob_size; uint8_t encrypted_keyblob[128]; unsigned int len_wrapped_aes_key; unsigned char wrapped_aes_key[296]; unsigned int len_hmac_sha1_key; unsigned char wrapped_hmac_sha1_key[300]; char scp; /* start chunk present */ unsigned char zchunk[4096]; /* chunk #0 */ int cno; int data_size; unsigned int iterations; } *cur_salt; static cl_int cl_error; static dmg_password *inbuffer; static dmg_hash *outbuffer; static dmg_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; size_t insize, outsize, settingsize, cracked_size; static struct fmt_tests dmg_tests[] = { // testimage.AES-256.64k.header_v2.dmg {"$dmg$2*20*fd70ac1e078f01fce55a2e56145a2494446db32a*32*9110b1778f09b1a7000000000000000000000000000000000000000000000000*64*68a32866b0e67515f35dc67c4d6747a8561a9f4f6a6718a894b0a77a47c452471e04ecef9bf56f0d83d1201a509a374e00000000000000000000000000000000*14*8192*70ebe6f1d387e33e3d1093cca2e94c9a32e2c9ba47d461d737d49a7dc1b1f69407b7dbc16f7671689ea4a4641652b3f976b6f1c73c551a0a407d5a335caa169db4a6a25bbd27fbbc38fc71b29ee9b1eae349b0d8a21d57959ecca6bf74bc26ccaee69cfee4999b55374605491af6d0b9066c26995209cd1b71925bcb45a8ef5727a6c20338f08de4357d4cb42cb65ecdc2344a5d7387633c913258ba40699ea5f88804b5e562bf973096337b17b4fc1236d3c8a80b9b48aed63c5a0eae3ae924a883e948f374771bba46923658f225fd2795ce0e795269f589e0ffc81615585e1224cddde654d689a3260e69683c6198bdfcd87507c23cefe36d72f8878cb27bbe5dce868752a7cce067f5a3110f20ebd31ecd53840103e0b2d44385656398edc487bf6d1a5ec3a56af54f9d4254fd20988df41eb85e366f13da1270a3f42c6672ad5faf00fa21e9ba3691bde78ab2c267a142f275467d5b853a107dbf1d75839f0e87b3b4f1d2cec88cc02a26bc4a63aa6836b0c43c5dbb44a832050385a48d46968361ebb053c2416c02458b76c95e50970922556d40b100967340a32824e6b6e44c0c1e0da7ce989d9d5ad91560156" "ed39666cbfbea71f28797a5a7a40e77665612e977ecb8b7fe71d500eafc29d9a0ec1d0ff1723fea7c405bc181ea93c0df42f5bf886eace3cfeee8b0dba52ba8cd2ae009e75d8845264d12dd632ca3236bc1b643437881b270183d2e2bd20808ae73d32bfe88347e33bef4921fcfac9646b74f116be1f04fc353d2222499d5247fa842d0d0f00fc9642ea7524adb65c18fff87b6efd060ec850d7de6f59869387b3d4cc8e38014d52d94ead07d16b8d94327fe5533941497c9be2dd6c04142ba57e29daaeef96d0f2d109522651d797715f4bc5f4cc3fb69fa92623b5ea3e08ff78dc59913993c877f4e2c8964dffd2c8cde6c6b6738da2883505486df5b633aaa8c66acbc2886107f3dd61b1df29f54a13ef27a7d2785c02153375240885e5c54297d88827403320799e05213761549eedc1c159c922087983410d2abadf9ef8ae460d018c278a9ea724f52b866e3d7ff2374496103b5137297100c970d195fca8c1286a8f9d3859ee12c84bdaa4b56ca91e307580b61dbe435ce4021007e4a2a8085976549cf1d195f439bb6e642567f91a0224e98796614d9ea6bfab8f6d13f91b7a80a54e538a1a785cd07b5d7ed2b7e45a0658b5722b5f8844f5139cff3b33ce244946757c020c54c8b5e43324023ed11001201213ffe4829e37135686a8bec1837b35fb234049570868dc5ba9c84cef6890d9ec400a794b1723eb209a60758ba9ae9abd23a7ea9f94fc6b73d29a560e24973c9160f195fbe82376c81dfeec1a7f912a8c22c067a26786a22f0b7db298" "3631400f120010706c78acc36ddcc29c7055fe82105f770e2dadf131ab49af93539fb5186d32dbe4a4df6cb0fdf6840c0609c8769fe242cc60d87e04e6e3be1a7884a05d9fb96c3bc1bbc769d96bbcc0413492eefc5502e9c1ac7c3f237b9851dc453b5bfa899b7b68e5e3b92711e7c92945feb6f6e452d6216e154a952cc28a3740925554d9fd44acedc8a44b0c25bbb6aa637fe9560437c08b17992c74de38fe1fb8fd5f66c2933c2d573ddc914f68f42d6cb350f126a51f607a2dd23b63e6382ec1e6ae434f47cfcd1e7d96c8293ef2994f850a27ef2d8210a0df0c219eadd2376ce36a22db56827d92a90d5e2fa55a4154c39061bd5490ba29f8309cf3e2056f761762dff56803bbe0607faef510d023b249663368977fede0577944f2ff05ead4b432bbb07a7d90148ebd1e30bf1204cd9069725d9fdbb850d3d6fde5044da1b9ffa222d99061c8ae217bc5b249960db545e6fece3ea2faeefa7702f065764b326ae0e62f3b8745cb73f35bea1bb9f6ed4fcda591f4d84da0415a0552306f6691a64a1d0efc8ac93559a79e57e357b63df48506c12dde74f6ea8fc5eeb1846c394fb8fd0fd40df26a42e53692db51bb36403305c1aff797e20adb6f8f1721e316705dcf8fe6e6989a5c3da253fdc6cb5de426f1c018161d72e34e6791d73023c5df69c0f83d3ea1d097f3a7ff37720a66868f40d3b87755bdaf508086c7e478ac1efc0dc421987af6db9b2f096a7270de91f5b3b84ee6d1d268d581718d3c534eeffbe2889388e9930cb051b5752c1a" "b1faf1e367866af7d4b37ba25c15a030d9a5f32bb8912ce853fe7988dc62aa61264e3c5a29d18c5121a605558b15004c817cb0ab1646138cbf6375f1a179852bc22d80b83891edfd38e25efcc0dbb78062f479a9dc792e5822e09ba3e0b8ef71c62ad7747dba8cc97707f31383baa93108d5c7253dce2395fa24d77c42cbf3559b5dc0235c0ce49ef9e3cc816598698c8f8c5b32abfaeb44f3c35a01a4f47421a166d5aa893aaba80e57eb576b838c95ed6f9d5b3d389a8f86b97fe629408ec7c7ba7fd95d7625e950c7324fdd35989570b24f2e1e24d52b65ed6116e728dc3a1004d3d8fbfeeaea1c7dc5d3dc7a029f97f8dc7f740e2386eb27e9793680d959821031fda08c7146f46e8ee47ec28c7d25574eb690de09849725e490c39e524b74aecfc68ff0d760d115b4d0a126609cef83b6c80731dd17f4a307331464953c6b41875b6e5fea328fd59f275e2fabd25717781cf9d5cc52286246ebc92527eeac7acc6e2652c6fcff405e7b4a78b8f9475f46bb82a68a6e44037d61de0df58a8b7a81f407aaa260f3a49c4a2641776404fc15bfb77573dc8728573a1872e7e093663842d9368e74cbe3ae547355fa101daeaa0f97dc0a63927e54ae59fe13aac4f488e938fa67a12876d103b4a56b6eb88ff0104330e5cdc7c6886b46545d523bfbfc88f40f9654fcd0f8c4f443a225b50b44af9674166d3de36b6ac63a150fbcda2e2511ae2a42fbe51c08f7238366aada5c6be8eeb41963c6a5374a94b332012e860d6cfbc1b8a4d5a9825b88a90c9a5f" "5615ca503698ad00df2cd93467b66d9b15876bc49895a081959132bad2e63757aa4e5ff77c6f25dd2581a3e9bb8e213c9313ceca0fcf5f8416882849fbee576d8ffb9dc057eb96bf6b81db60a82b0e6f315a13dd31706c0e36f4f21b9ce977ff6700cd77db603120d59ad8088e121cc3c502e37774b098eee7c8244f9bbe0d4a9d0deba3ec22e5abfea69ab72cdb75a001bb53672fe12b4fdbdf7e82c0bb2608de5d8e1961fb4524dd1acc890361923fb691bc5ea436246428a70b5021f9eee2c637eeab574babde4c0d55f57925e511ff623af5c4224d3ccb9c8572179e2610b4b79817ca18ddcb5302151f9facffca96269ff5fbb11e48209e20145bdd70d72bae54f6fbb89a3396bdaaa3d45413e3c5bc672ab98dfbeb3274156096f641494c1c946baab7c388a16c71ce5009b32f45dbbe37998906570045027950bd758b7ab2f72c243eccf9551d539946a99779848b16cddf9f163fcefe1e1ebee3ba7d5240b92698ad56a036274ca798eae19b0dbcf39a1c0ea1a58b29dc0e3de89def08e6c5800c94db47b7eaef5514c002d687b4d99b00fbd44137f56557830d63156f43bf73db8b330bca0ebb4ea5d50941b758929722aaa5452cd4a4e00640165dfc35fd35daaf929997adeb4c4f7611d66befb80809dc7bc6c763879c3bcd8dd0fe6b621898717fd095fb7eb403b07591b931a8e16ab488b01acd636bf4f1e71d5460532b8a3b00d7353e84c071de5cfa25de685cb85b569e08d2f177727cda11f196b040d25c97ccb83e355db98c2bc14844" "1ca95b5f612020bc53a81184ccd0c5f14bf6d9fd6318ec28bafe8d668cb3c98c56ad416007bef4a3ed9e12eafe8f9e7d87fbb02d1f557b497db1a2c0fe40ec3f23ea88332513c68f724cc8a8af6636c9f332a8e55c2d41fd81a23e92e9ffacd3ef14cda669e7dbe31ca08a5238c7fbfe7020933087bf2ce0a7489fd5a3becce5de09628234f60c833002aa8e9c9ec51f57c8e4ba095c1d054750d46d64041bb1f567a82d63bb5e88fb70bdddad0ed7572229e56b90e74dd88ca829f1ce8424bd24a0bbfe3dc3f77d244ee59f364b36a4b05fb511b5b0d7f876c65ab4233803543b0a68b9d2d6d45d292f91eb4700c2dbf431e40c77a4fcc3ac3fdf3a2bae3df35b6417b8f1eedfe84cc65a07c426780871d16ec5ed3201ea4eaa778b71f04cc1999587bb4645bbc43e365395e9188c85bd024f758304aee979f8e67d07636fea251423e920e2b7258580d1918fce772bf02ee66926fc5f9a3dd6a8c89e6ce7e4fc03d4784296df1a9152a1fc66050983a287e3520bf3e04d900d25316c8bd5ab489bf97a2f31f4061f895111caff9968ecb22d75cb9e5400ca1d0fb044acb4fb9cccaa4766cf6c63ae5a7a3f9af90d1b225067f671d85cdb4e2e21d2850f351d995d54520fdcbb8cb30bfa82190ab2071eb8bf350f984408b206597371736110114d12d79da4027f9a58c8fede63cf16fa552d2a956ae2a49c83b0afca3056f87f1e27bdeb9d14a7e5cf30550017a3233c4f386769021a853b971746aa28aa69ca980bb02979779c5bd29259c84911e2b252" "61b92be669e8a731dd74edce66b6f3ab5944695efd57c0004ff637eabfbc02ae346528fedbf2ae80d420580adc4d571a37fa1397fc2b85ec458d5262c15620c88f2dca0eb1bae4ec39d67fef56ecbdf89703919e5a6767d0f77bf6f0f60ba21003d033c9dc3057df18d855a5801110fa9a29a42ce10a44a39ed883df249ccddef8aaf832387e70048d9ad6014cc17f9a2bf7146696ee4eed388d06a45f7bd7696e57500ecfada9e9eb17926b16bbd90146e406e281141f0a918c320cacc9d1f045ac1bba87ce8d1d45cb6303988d5228da6ad33df6d2a5bd7f265b8f610078e9db5fa3db0e08286e500063f0fd6860a11d9985226ad382a95bc3c3941d43378ea1bf28fc85749f616092d77e7c292e311337168b52eba08ffc0f76582710a1a7d33c55162b3c7fbf227a324e1f4579e035ae0fa17fafb1ea964aa977490b5a3fc16c75e1fc50a6d17e193345b71369df804c61a71bf60be4281c3d1f945c690368c23caab006f9dfc913dbe6119d6fe8349cdd424db7074726e8bdd0ae99e2bfb9b800ddb965c06e0587cd10108c9b431cad4fd10d3654a22ceac73553a6b2b2218ed6526c362df46cfa776e2caea0de61b9d5c0c74e03e299ceb2221ed0f30ffc5876354d5607c3eafc77f78e4fce5e0c7f6ba7d417ac5f0511e2635b41b28dfb4f2fbb73d351a69fff920b76f5687386114b3d5ab9cad056c88840a023b7e2df73f007852763570d38a966c8258365b014a12a3497f506dbe55c073244333547223785438372884ecd8b66aa0a794ab5fb" "94b0a519bb3cbf01b43463c0c7fc6ebc67754ca25686002e13edad54c817b0aef64698637d18a4a8bba382add892f4918b720aa99b09ed2a6e02b7140f89e3e00680f37343d3e47412d04ef78005b8b9a23b92d145a8da9c5efafce374955727367a7f1a179b990868550cf960c6df6baf2cddda5fe3e689de8dfcf1474db419ecf88cbce9de7a58e9d8a15991fdf5361846273d195a2892fbc95ad079ca8153910984c4694edb4c790f430043c4019fbd96fe49d8afa5e7d1f6674e4a125bfbdc916b0d3819566898599443ebf2a87b1fdaf41378227d396d2d320dc5b860705bc87f45eba2b6473234fe054267698dba0913ab1234b46697c54e2b19526d1ad4b7e3eab40a413f86170fe9f2a71eae2fb959a021b0b43516f1c8a3e674f37ee235ade79ca296364b0cad5ebe8449e09b63a34e8711587f7f2fe6e181a787b1d3a8f30012ce9549abb834fb80c673c575a25d3c33bb6d846ac231f411dd6422c59215e0a267424c0c57e6c9bd5486e8b6327e9dd16b7065eb74ef91ec9204360b03d08654a4e418346ec2d4d21edd5608a76903494791546d430eac38178d158d61951de3c61fbe5d56c22cbda4a3d40297f7abd83913e8b483d9a80cf000810d90a921f453bcf9e35732d2579c1aaef4a6980c666e3b273a9f91d9918f850bd6e4475d8aa5cb616cec58d6ab6d70dbe2b0f7ad85618b6e60dd4ff5d0faf19dfdf27a9ee48cd7b2d6613e76f04ab6ef5f0af12966a90875816c27c4297a2bf622ddf66fbe7c211670d0c46c7295b93bd2f1" "22568df3dc46e9294c7258a0b7e81b2d45979680edbb7ab323e4857d84306ccc16ca79c711144eab7b37e3437245d7b78ced1cfebfc45892791b9ac6cc1211f83e328ce3f57af3d89b5be89dd2efeac9d738330bd0d8d4a059bfac06d1ad73bf6d427541e559c3d16eb5adc4380c1b25c1b8a9097ce7eeeed1c5d6884dd1a32ee2bfaab8371593a0eef65f80e705b9b56adfc0db4c272024a71947755032a5ebc1bb346ee8a99b01b408cc0b1658a319ffa5ab2eb87e9aa8b3dd9d9d92ce3bc04e4ebcc011a280143927676360f249ccdaf7949bb23770a06ff5861661d36d761508f7e9ba149310d1347c3165e07997853d415abdacfae9579d1dc0b5990a05ae9e6dce8931ac2db9414546dc64f8161a64cf30b9ce8c50ef2a99775f03dfc2c611e780a5cbcc27cab920a87d940acd8b3fd42897ab6f51b29214275bd564c50eb7aab3ad19a2c903c84d2ed5a23c49c81d87cf3244505424332c917d7b671d4a90765b8953c26bb7ed5dfe3e93632610ab44296afee2b5c631fe643a0a78eb9af94d700250f5a82bc57d24825423f1ecfd8cc2bb0daa229670d0d9a4fb342ee8c9b7b16d86d29abc2a57633303b918ac78ea8d2672dfdd4a06ea0bbd756fbadfb0c09e2426a65e90ca829ea00ad66ca8c9e79b9aa5ddd02d435cb23014b1033da00381ddf2dcf408660d1eebd1f6c7bf5ae9fc3fe47e75ff7ca482716534a9f3365f5cdb48f3d59fb19d11bb8782ef96e394296594812e8a7da23a953f6117ce577e55f3d6cb1d3a4007dc7d252c7123a8" "37be12884e54ad10757af405beffb5cff189133bb7df5fc009544b2d62ec44fdc0c1c8240d4413af5b36e031510b1f1537a690ba7049cce9df4bf4dd63f6987c513992fca78a1cb7e8d670fb43a52ea2ca2f49724e35397041e5c75a365b510f40fa9bd076377274d6a95af801981d71972da0a08b536b024f439c43d13902878798153ed825ddd7dee8937181823076f036caecec170edf1b5fbdd84e530bc50a7acc257bb9679d72de3f115602d18d2d12e6ecf4d3242ccbe9a71a1483e7fe40d2447ba028a76aa92c13516ebde90dc4d204095a554cbfad79d6efe4ec540c7b51593413465b929742b729ca688f67ee9d9fe76431fa81217fb135d0dd6ebc91904efcb0cb6dee22867e5ddd7453f530d04935f41575de9ca457da55b67791d2e8b83890b5be543366b92ba6579a6f19f8e82a0bd87e379967766e5b0a58305b984778c562ea03a8b8392e3160ea4532b6ce5de74bc8fa0e8ebe88fbd62a73d7106a309f5a5f5d7617664b015e166fcd87906caa80ab4eb3e62f73e527b5d951a0ed0340fe17bb7b2692e4a31d14798879788fed12413bac50e490ab93ed66311599a6c1362fc60da5319ad907c7ef7852985ce86246276a138379d2004772d4d9a989b83b3e780bdda9825ad06a4b3dcc9a9d4d8025cbdee7cb2e02ea1f77bc90bf4ae56903859025b7283ba6410aa91933466623b996e9ad07e3095e376b11a27ca451c246d5561501e69c6747013ecda44f8d1fa50a75572453c9ddecc07b1aaeebc04cc7e976915f5e68d1236ae2ff" "dea4b9fc4f8e91b03982801e2ba604b46ad80f966838ae09d2734c6482dd16d7738cadc1276593a336e2ce8cf7ce48d1535c7865f7b90445ff3ab9e56f58e254115bc07710de50d7953238d7ca419013d104d90fe79794995c28f219c963d716bf8942e0cc5cb432aafce4afb42f74596b847fde5d87fba9adce5c17fe590fe58e60379393e521ee194fe063211d72c29d58f7dde89addb6b0e20515ca7aa270df2ef2d77f92219781502c49292c6c4a985242b9447521cdef5a52b53b5eefcc43e8036ebe90b51a3565cbb180ea1b3e3d20f63b8f420c2a7f01c475428d5f63c66f122654af4edcbafebe34970c152767cf623eb4f1ee33931a79622cafc70cdd2bc7ccd55ecc1e0aafde3f66f5414315048d3c5c51638c35fa920cfcf7a18ada48a589c12e4da2c801cb8bf3b182463707a17891cf296ae8aae6a8a88ee3d602cc1bb7647861f65ec1a278433ae08d8c8e63727633425fda0b86d78378ac80b1bc1a48abf270dc2b5ea71691eeeb979950cbe0ddfdc451dcf8e3dc657060f4c3f96512b21bcb228a966381efa94bbf5ff4bbf38a803b6aafc719a545e4d0582a62e81e6468aa04eaf131f8d2f545c060651e115032f5b3579fdfb95a2328f5c9a0308874630e840ae1dcec1b9543c36267a9651c94c91cea42a93a91ba3a054ded4a8343864b449e46abec49474e218c8c541b00eb0f8997e710025631ac28be3f08126446dee0cf61bc69b85e4fc021f203c796cbd2ca16ebc8fa15f55510a08ed334155233c6459d2d428df31a3f376c" "d81a530700b3ef08631dc5b50f787d4efe2bf219bd17f0431803d9d946255716e8543bf77fc44a48abc70a97feae8398c2059938d39fb4ac5f7214d92bb89fb9c45b6d117fd51f6207935beb1a89963fb9d1aa020669bf809c21154c20e720aa1178ed2bc13fd548e0d7d01eb1d028aa48318a02dc7aa412e2ae01ff59a86dae40771ad3f48f0fa54b6e679854be00deb9938e37ab3a4c9a96f3b7849ac75b82619cbc806c42f4bc4feb1141f6a8391bf9335f643ce5cd2791590b28b19d03cca7b5cf702f10ffa0317327e828deb4791f71500f243be77a451e5759c6c711b38f8f62757c54d7fc6dc586a90df7777d8cf1c72f9c0947af005d770f4a74b6c9413738c3b5ab32306ff5b41a6446c2de3f59a27b79d877d3f05fe22d11afd69e49e59f35b3725a0ad126642f388602b7816abe397a9c9233cf7d1e12a00362306d2d9b81fddb279544f35e23a8c198930f75986f26e6f292ae8debe5da0a7a5b8add2be71efc78179eff7fa2a2dad35863b69e85e8172073f434f48fb03f7bd1bc78fc2badbda261a68f7bfa171c898897b3b0d4852920674b8d9ffdb37ce66c1b6aaf9b375253a0d74eba4d359737f7fddb42471969d81605e41f615399c5fd6cce1808e9b511ac54f75f774e84b00970474f5136447af04b4866ab6c54aabf7a247c6caf3ee891fecb14073f3cfdc7368ac00f6b1c9b23e301e49257840f949a57c28a95c5c490bca91bf979d40403f7b9458bd255df757e6eea0bf41d5175548aa46243d98f2f0f6c754d6e7e58fbea97" "7d7e0af8b7d0a6bce07d0c483293868a914a50aaedfb9b239b4c3c472381535b287a4146fd52e7bf882c9c3eff7bb2fae15d5b96bb1222d81d26dba563ac550e716b6c08b062cad6702a33a9db4274fa2e81af815e8325101d5a9ce9b345e29619da9e45dcbcd7b0935d7dde07644edc6b049eee9371511bb2cac50ec1170c7aad835c54fa52c8e0a0e8446356488e09c2f07b17413a7ddb872d05016aba129cc36de609831863747310f0fa443480a47524dfc5e1f34eef3ba2fefa29e596e7fff86a924462781930fab55e71fc2f06271e62878e51e0db08ee5dea31f1d2afe9a4f548ad6a4f4763c9d0eecbcdc32323aba1c9c12554a5cfedb5310b4a03caf426a80d725fabd557493c46f2a174aac851d3d39529d5ad919fdb7fb0dc1e5b0ffdf706a9f5af36fcd2bdde28d68c5af4a1da4e67cd44f97b555b62b39cee1274b7c3dd3971ace3da6101c87f9b8f28c5e13d4066a3e63543825dd8bddc3e90b6dc75bac78931da98929a337817f68deec6065f6f7883d5bb10cab909c9945f71a672eb2cda9fadf4a8d9da906e2a5d1f589193b4e791772663f1bbe751498bda065f90244391169d80490208083de39bec984af73dc99b10d85958f372004a03962c45c531b347851dc5e26bf7bcdd68c9b129524d6734282bdd431f991170d6a5c67138a5405d8005b355ec7ce95496a8e98782f6d978c42c30a17db9c12671d82f2d3e257f66980f20bb6380303f1e89b10035ae7bdb3e55d31f2d1574784aed5c95aa09aaa9614989d957a65d893dbd" "abbfaaf30cae0cad575e39f5311aa00a6979fa52ec12dfb2f731a3ce5f8b6097a612c2ce98f5898eb2d1780d0cf9ad30ce5395ae871ba7ca6a0884a13c09732cefc5aed9d7a28c09041cdd62e75d7396432545f0c16496b7f5f516fb2cc603c0ec10a51ee952b7cd0593ec00dddf67e27dfe3f0cdc5bf737170243a8ed3c1f59733fb47bde4b6578d7ef11f95790d4c678d95ab2cbdb1673d2d516c189af00f996371077276e672f1223926fdcd6627ff86816906edad3aa97e3a9e7346562add05ec1a94c2dbb7f3b28ef537715a1d69761bfb8c2092e608311af2f79a4f8188665a48539944374437bcff6e59bdff4e4b9e4dce11307d892915071157698460b9e9fd68ee0d1acd21434810fc8ae702fb8dc794ad5364c79fdd74c8a70f390556930fc2a23064f36411c626179d1d745d4875f5c2b37292cb8ba37bb78d419f05e9a5d2245a38da20b6b14eba2d5ca3d58d23bb5ade1322cf337eb75a97ce98c167b6305907c3fe18038bee1e2450c3095480f99c9f12d2b543b33866e5546a39d539c6e2d639356bdbcbdb3b4e0935ac76e0fdaf54cfdf241d2c5ce135324885f8cd69e6562f48979352bbab357c6861c66b4ff7d9dd5d32a8ab8b6e759a2f5ddcee847fa439a5f9e3989039aa60751019eca6c7dfcc2464ca4a1ae12f079d200961797cb0e52cb046d1f0cb1d97c4699e07f019b48edd6f4a71b99ba26c2e5e72745cd9bb9a7e89d8eaba646461bb76818fcc447de2820196e32cdcf4a57c527c52f64d316b513f6a611c929890be5b0" "3b3d3352cef23bf86d0e058b1cd9c4a10a9a01060aa9c9cc4bf42c7c6cbb677724db3f0c3736461c1828e67c9916e953057024371bb4ad8995672f760c47574bde9df9e73af90773cd46c9df8cb655f8c37eed8cbda40da06304471e32bc828a7dd9457fbe4d63a15633009c1a9f003f3db7f5b2b5e3b22c60f747d5627bce3eb4398a543cf24b18cf0a56728adcc253d7f5343245c1426b5bcd9daff94394499cb6d7ac2b4e63ec424c66f5dbceaf877fc13f47e744aca7d8b5d89c8d5621f4e13488b141062ee04c2312528a0a987a5d32ebc6ffae45657f4b2d1420890970e363a124b75374594dea0560320b36133e31d6a978f90ef079b81484503c7fc3edbceadfc9fcea06f271a60ea6c5d434b694ace1b506eaf013aca2c6103acfe6c565a5a24cdf638f8ee282ac812e32cc2662a8e2d4a31239952836c4896870d973bb65b280f0370f4c3a54c7f4723b2bef522ca4c233d7646da3fdb9743e273afa1e3bfcb947eea9f323ca908bb4961b214aa906cca1d2d56eff25d60952cc5897ee6390f9af4efd5d48b2aee8734cf6b8042f2de75b107f8d135d9a63148e88e43df815fe7871a354741f8863af4e114ed0369515bca104f8d3b24a2d740b8617de3e96a23*0", "vilefault"}, {"$dmg$1*20*f615ec6c463799eccc6a2dfbedf12c6bdc422a2a*56*a595f4a81a490e7aa6378034661da57a424f922c971d3db3f856f8d54b0784bcc5d7182905c4237153c5d250b8aee1d26410b1dca7b1cb73*48*74a060efbaf2c79d5523219d8162c425befbb2094fb46e7ffaedc7cd4f192e6f0c47d8aa91e0a3201346725d3ddadfff", "vilefault"}, {"$dmg$1*20*9c82b419bdac1b3e6b71f8a6b99a7501f34b6950*40*5da479e292e0acf67a9fa3e24d0a767cae2f645ff63836665068637188f4b80295de79aabdbc2536*48*9b136165ee73418631ccf28d5e77073788ae921df596649a7a7789585db0f13f446d5927967e2ede20ce8a4f5389185d", "vilefault"}, {"$dmg$2*20*839730be2331c69df4f729ffe8a10c26653bea94*32*1f24e25712c2d70d000000000000000000000000000000000000000000000000*48*3231e20aa642889a7e087cb87c84ba1cd52864007cfea677796a6f52e16b2609696dde9230aeb5603aeb1f70f6701be6*14*8192*75884a049d2b7a40c14002ab6e511bf3c73ca79a2bb8285a3d2ac1d5b9b0cbf92d4a483fb762bae8485dc3fc9cd7a54141da2b74a86ea833d253d56f52eecb9dd4d40b9f846690378cb8a5db74fbc6d756ef9fcdbb5d21805ed43a7fb45d6caf6b3d2564f4a7760030aad69ed9e56789e8b2699bebfaac3cd73130fae1d8ef7f003e765e86eb84e990f3c24780022fdff3ba283ece4fa8d31716e5cb1ea22e408431eeb2cda1460217efda86461e940cb10ae602a84ddd22be53064e66c0973a04405ff17afa020b24f1bb4ce42750b28cf4e98c4f542576e712f3c2fe0a0539a411290f65ca763a94d865fc24b1beeefbb6b055db453da38e62bc383e74b188b86c54b62f589334de8ce3ab2e4643f76eb4db95bfc088bea8c4e88cfccd19b89b818fb698982f73df634c8a8148e4c8d3ec2dab02aabcf48ec0a78686fe0b4f5e589a067d6c54f0732e559cf9db5b4ae1f0468f5681226d3b03002cb6ec528b96470f1d1aee5d3b51b4c5f45a2702830ea35056e02279e76fdd30b3ac174cd91b65fd6a26a192f6e632b0fae660d0861059a62bc512f610f4974c22993bbafa364fd2e8eb53d07244d165f990c876320d99070fbfa6fe7e0ca42c0ef2f17205ca" "7196376d4026a8a93fa83a99cd3b6cde354ed3122dfc07ffef91c24f2036b0d83467e120b85a92fa04120cc8f7af3196adb6420f519c610983d163964b0cbd048adfb89266d9ccf9845cd17ed04accff9d106b7bfffefb365e97357fdb9ab2d0956411c0c73bdf235a9ea4b50962c8f258583899ff2c0bad6602e8a3c14f3c870fa14686d15aa17f5cfd1ddeecc7b061cb5c00db7d198d083a690ecee97a1b4b0251349beab744c4bcb53a4c1702d1094f6591ee5ae15a29271ee3d3d22f0f833219c3676236c9e9620a206ab6ab08fe5fc663f4f2ccfdae6e34adc68e59fcba5363f44cbc5d8345f184ccb38d52bc2bbe6ad996c3d4316ce644698bba6044209d108c698c3d18f4b64161651224cb015052d2e9bee0079b779d77b6623e9669c4ff99988bc612c4099f6b8bc9719444cecbc5f87bf9ca6dc30f3b346c3cf20cc342cd4d156ed67c8be0f1801c3e672bfdf2fb9e6c6f1ef3570d059405a8a0c5bcfcd70f7bfc1d2417e3ca205be70a5ffc9b4d1d123ff64cf72b20df25e9861e1da57fd1311451e542c25100c19d1d70bba2c26752e4cf1c59a6373fceceebf2b4c392a45e2cc7151f4cc1c7292720b5f0716cf7ea752a8a44cfcb7f638c5387a410efbfae90598f2d99cc79baa298e30076d5ac8a2094dc14d81953c09fca8b41f88cbca2274158b93fe5a151b93bec1fdabe1a6c67807d5f9d46b2a19ba85f9540cfb54656fe473216ee1922046c5b6cd08b325e0c25a420765a61e5f7a266c9e0ea1148f0e62ec65736d4cacef77940a0eb" "24e93b7b656e3b591f5827e78b577b628da26c1e5bd7544dd439d15ca21a3fbe96d3833ab1bddbb03beb8f0fe39517958b7bf43afdbc68b5061b41145e151d228bb5e5220b31a86878be40060839855db438368e40dd6b8d534c5c39009455c0a783455b41b572f2864eed60e5dad80979b97efd6dd08549c154b76f748101396847efd56a97b82cf62a25e26ecaebfa35d545cdf886ecc22460cc0e2983b9da14ac41dd1e1dead58a2c29a85f6bc900268d755d1158939470c4793359b50da19addd3d8f722c0a889ebd8dc69bd955b524bbe452cc98834613ea48d7a73a9b93820c0ba718cf664d82a1745451a204a2845d4e2a846f0f18923ad0315896b1c1ac1942fbdcba119ceed9e02b0e707b28feaba44bac94888ba1a31670cdce6348d58d2072eb13ee805d569815fb28749c392d11eb06d8b1746ba8eef3313072fdb4685f1401717933fd18edbc99e3d89d08a4c7798bc1d724d6bca02a31642ca0ac6223884580c0be8f6508a6650b783a9ef24de3713f65fadcb2da6d68c4bbbdc216ff91ea7bd24bd7365b91087c14edf70dbd4eceb2676797ead7fbedae77a0add9d22a515e2a79d075958d8fb87aa62700c62df007abaa3a5e002403205fe04edaa4aac3da6d08ad9ba909974e9091148208db90f330b2c2c702521d4b1b32acc4fe6b7ffd9f96fdca05b6c404afcc789fb9ad8c52063fc0f9b9cb4116ee11f07aa17dff57b889a4f4abaedc51a07481c1e954d78ead32c6e808d3eafe7cfa9d2d4ab4886abcd2f64ba2df2d8d507cabfa8" "d01f785409d71896461adaeb4e34d18f9b2fa38779f0932c27ba2f3f75ece12f6eaf7a0d728dc02e97cd44ff175b592b8234c3e3b5491726c58dcf0a1b77698cd38d861fcd549aa793f8d2b58d6afd1d9b7bb96c8936c960eaa7072c00e69f68f948ee24494b8152bd8e5d6923c8eb26023dc660d202e41663888a8e8550092b5e1610452c79069b3cab41a2e7459dc0d361ded09c9f1589999623f6deacf276eb72996a355e4f7dc19a5217e9dcb2d6a3e4679bed9f980a5dc8f24a1c5f4eef00d706566e12ac8deeee964ab9501be5e57e326a6fcb794e4f4fe14922704206a343724913ca2e1d26e3d83cf994cb7aaaf9a916ea6eaa06987a9822c5a8e556b16ad72d5f5640b3490d6b0f290f9f2db7c3ead435e534406dee40366efb98f0b53930a83ff9bad177b84343d204a1083801f1d68b3aff78ec4246f670f924969e4608b419ea9f5aafec40d902492f62844d9a83d65f38af2531b875b964abc781b3537c708fe65f70a11552990447bf6db287412367ca918a39d9e2b2e228451807b01174afc33f5f67d45f9c765015da6abd318c980fc8bcba60ccd5193e7a8caa54193aa83bff7b77725be99780da88b3209a3cec620c17f979fb16e640473b0d98a2f492702ab99f2f0f83bbdcabc2a6dc4986476f420f112ffbc7bddac8cffe59e82ff558151b9160e2f99bf37a05654253321591ef31d01b32b8d69297b3bd57f127e9f574fd472b6d29b6e9a0e1fd43252bc1f1b2c8c959f3f4d80177b4fd6a77dde8fcbaf1eabcd5e7f6d38630f35d" "efc161ba7432cc9af6bc73baabcb343c469ab18e4cf88eee21e49311b4f20077bd6e30705338f047a9c7bbdbe4dfa6d7be3a827c92823a3c8f36909f9e4df4dd91426b75ac6b5d953357929b0bcd91ebd24e651a855755edca82c4664d3c89fca6001ba88688e5ec8d5e5c3fb145b963b29424192530601d74e3b815be85ca44640ca89c57ec4ac7084639b82e23f065ac561779c040cbfe63310ec846db02873203feccc3f88a28fa78d8d567905abc9f8f561b4a29ec5c380849ada42100c15efd3d73fc203e63a315cc27b82f62c4ca0df9ea213dbf7eb39552fcc38edfba0ce7e25dd097bfad5224369f1d2a175ab88ee5a3371daece3342e99c60cde76a1ff5dc7e5ebaa7e0fb59d4d088cfbe7704126b2697d62d7b82289a35ea778ea4ca347410513513084f1fa971686724761f711a916ae1e92402ff3d52f948fdbd9c1d961c6ad6923c8ae9cf3a4eae7a9369daa5cbdadfc786e873b90ed1e8f5933ebd011081ae7ea236c11f0c53e00c1c0f9206f91e6954123b5caa08c7615a787c1661dc17f297c8ed2ff6c90dfdd9a262ab5e9a4489d6ed7ac032f72bcbbc2248e7f1675e2b2da0bf85caf89921fcd8e78403f11a28970f673ec7adbea798b3eff87fec642ef77c15b3f3d19dfeb74d1ef6a38ab938692207133aaeaf722aec4f6082a4cd742bd37fba0f1f83f01cd2fad6a169c4716940f7d74b8f29001f406de5897a5e5d813b995df132cc57a5d9bdecdad9024dff7dee8b89189d35085a70bba2e5e0a8c1c71cc593238f3acbd1337b2c" "c5a8647ce6bbd669eb939279d3b964d661112752bd7fb877c4c6ccb5ef72ff5446410286fc69347841c5595a3408e0c73fed8984d0c0fdd2544a168ccfe41386702f6ab7b3675a78b57f9782f23e0471e6dceb176dc9eb871ddd92dc0b86b2a11293523189c75019200a45213f0cbd86823f65f28cbe6569a58512dd469431322b7ca5b9b8ca57e56a139dc4788ffbac10fb57441f2435584651fa572450a4719c8c9b4a322f3aaedd3693a55820c725b63096d3f211d830d39aa89be83d59b13145dea9231266ef6b1eb1fdef31203922308cff81b166426d662989a350ec712dba14ced58df7dda0d0fad05ad8d9c6b247307d481f79e6a3cffdb2ab9b21a8208d6d7faa72b6f22a505d2b950884474862f6f67effc81c6292f3550c4e8852c39c52d952648b256e961d478c0c6979300c5188c490ce5c1e34ff6dcfca63c0f0571ea616651ef6f9781f2d355dbca208e56948ab9e26c5d2d3f8509952bba3e93241837b11a89caef6c956c9354ac10425a6d8d4e82bd5d7411d18655393d7c542a7c914a5ea6aba717a226e0f51200cc949f38c703f4f6ce452cc1d7d6ee8acf26d34f74981f6850b11610c11d1c5e6689c1b6fcd6b6e997ea145851c6655560c33dcf5ed7315578263c39fe6a838c5de867f1b3cd482c0206f56ebea0617ae25b3ca8d7e13849bb2b58ea4e21409762d549636bb7cf5ec32d3216d827d94cba1f36e7632e3a43b3203fc596cdbf879d1aaee90804fa0cbf46d08ff4c40aff8fb2b46f7ba8ce21d17c2d3d025b67702054e" "9d76716fe7b5c9d2f43036d86e6a17924d2f160f91110ed1f3364a1177aa6193baf59878ec84f450914faad409618bf25cae17ba5545abd33833ebf408990fa4236d322089aa42eebea965e59456250fa14bdb61a32be8d70372891a83e7bf298168c5431e0b326229c36c667217bedbf64e3a07019534a087e84cd1a9cf35a889d9e65a7be63e8d638373774148e127b328734963437e7f00253d2fcce7bc0d798c09326ccd4f379f8a29f2d308ab2fece6fcadd653b1a3ba53a078e51a1a87e8dc03c5c118444d82d9166c0c4c1bfbe8ee09be6f8cd497a20132d4b6e1edd13683b363dc6587de2f11cdd51674ebdaafc41654d639b6cdbcc040f5889efb1f64e1b873442493ebffd8f867f0e1ba2cc629bc5239ded578336a9e88ee8b2d1b71f6d9303cbfb8a35e4015d2f9ec25eb4618c2ac17166e8964b68a66e60cb7b464e36a2251243a218ee542dac96062ec7db751273435dca23bf3e8aaea895ef1d6f6bdc98fcb6a9e0658dbe734450682cd1a3fe16161a9fbd035270fc86684971e20f1f1869546e1b77a481774c9449ac6499f376bc3c0f0efa589abe3bf676fb385ea50618c681eff6e5359678f078292da285c4b5e66d5ddb43499abc3558490aca6481299c351c6b053739d0065c187f59767e7de24f1b7bcd2d80d0ab2e7c789a9f5172a8411a88d2c69d8f9d2744ca7e42ba8478648df29919c23c0f4cf14e2428c792f2d8abae1073b97d86c2d5cf2e5beebc7fdfc449ec3804a81199d6c4f24d9b040bd1feeaf141b7eea626c1fa812" "e499b74e86dded2641ce3e11a04a35c8b8831a4de563c3614b4048eaa656d8dea460d2c46f6d748be434718e9f54934804756fad07d2a8ace694bccbd7bf2e33c09199a22a98726d2e1a690b2a9c33e39c8746d8125d93f675c571247b0a060114eff4c32231898a05e3ced4721edaaee9ebab9b46692c65f086d9fcd34b86a499685010ae0f4423625263d0a2a62672624662a6613bd4235b7402573af1b0571c364f7c14e277b84e4a102b1055a1456b912431f9ce9e875056f8b48345ab09bf06b3de6126fae32e2bd61d2fdea29a2f3cb46d963fa40694c02657352b9b9918bc50fd7e26584e51ab5e4bbcdcbc18b9bc17d3efc5935ae5077a269fb8e912dfc91a2c287686590c3e2671f6d29365c044fac2c077fb5ff280b0a4d69eee3b9538b4c8a029a3360902ee8291ca9f1088074f307392b70a7a43ceaa07c47d175b286c052e2412237da3f6acb1eb6b1ec386dbcdf5b49d2391615788f401ec234b58b112d296b389ede47243c01a1a6d18ca5dd3f2646d483b97e41370faa1c023118a1d2006694debebe35046f6e5852952bb520c9991cf9dfdcf89e51fe29d3cdad6f1091fc7c450782f06b09cb8aed1e1f95221af7ad369e49ed672fbbf2d255549d0fc0398dc6b4d37d038a8dc9e8d9b4d6faacf3c5fd10663107cec0e171ea6e1c26eb8a1534646e0813ab0fb449d15b4865eb2e9914d404d06c1e284f66e39d09e99eaf7c2f36997ac6ecb9197f8ea7fbdf7da38e427dd5179ef265f1471a096fd24d8ea2a2ec3b820c54356cd912f06" "9accfd370ca945e60c72b5d479b15d52a5c3c4423c73f4ec06d9201ddbfdaac2e304b1408674d40c203ed48fbf4b126904900349228b28fe262539c9a12270632f28241198381c6e7174d275227c99178ef4942655ec95acbc19a3b96fd1e07b5e0e91488c979e7e25be5ea733bc3171b2874801157c83a6de754ecd05cd78d6d2846e7ce19f641bdb53075dca078ad0ddfa871c16e47da96d007b5e2b2854d151dccfad21875fcd12df56dee7f4aed6a54fa248ba2721ab2f58c1157c85a3df8486f99295f2c9b8e8cd7a65145b69ca93d0ac4fe328e31c07bc1d0af2db886266def575d74be200ec9a4ccb0213743eace8d7d39f810e3877876082238d72c375a5cbdc4d7de36c2ad90904a173df80195cff86f19a0904d18a1f8a92cc4779e5997dacba58770c5091dab5b832dfaab2d0fd102b99e3b8a799ac6e7357b294a31db5f9bc3d04036a4a6e18dd47dc88b0f07e1c4271e5106f329731ce4dea9f56f6d63beddad788d7eeb955589a13990cbe3454b07f63477642613bd77f3bc5d024dbc5c55a0c7426ac7cfe63dd2da9f0d5a7e816dfe5856b646b648c302c16b50296882c62334c9b8e56ba6dab63a9c787fa153d04e5e64503c6bbb9bfc8957d2fa607ecdd3714123dd52b6f9c1a3a73f649dfe67fd7195857955cb8c5470a9f363116cbb580b793033280dfb63ae47b384e6aed677251b63a7a27447f37e9817f10f27c4a0560ef34c0255617cfb90769aea2e5971077cc89022f8a44493d5157ab2962946c7fe600a24f002cfc6108d345" "469a65f2f29b55e4da3f4c767324f173a11567ccc401628f2934989b29875ededce223de3134b7e99384f94436bed28329daff8da5690984b491d43f14d86d5a5e783545442f913dfa39f25f6360d2143fbe4c7e234a40f65b2c48ff5835c3fab67a92d0adbac9e63993db052a832b1c7b6045a495b82ed0d7f1068ec96fe1519493f7376a9f9f331f6ae89420fd1b523278df3e78c7b957f599767057113d5a1895801f1fff1b7021fde8360c4fc1ec8165132244b680645df7a1c0673728ca6323379739905856537091dba18f762b7be6f5f7e95212c402b005d73dce6a7775e90093f927edcf0d9ca24d04809f953ece372414d5f987ec2ae030dbb547db5ec17bef47dcb097fcd2fdd873eb93a99e2209425d4fbb589530fe41bdb5daf8ad8f83e48557a01d2ff6b658368e39bc8324cc2756160cdf56b8d7fe231aa03e82bf0b3f55eeaba71133a6bbf72342727a52ff7d158992895c61c0bab4cfe42ba5e4d5f239ef5efb6433dff84a02e2a5f12bfc35c1062e4103a3f8fdd1c5be28bc83725023c8a72d2cf5103a7c97a23b2d9903a1870726ad2bbaef7b7a6dac3e36c1b92769cb3f43eea1faf95c53db0cda2a8bea38efc1dd11695bb5de4baf583b175a32d49f98c37510e9e56f3d9e10bb4aff163abc91a36f24fb38d33d87fb4299d5ceb5144c69cb741b03d35436002d7740c38753e284a808a77cc1d4ff9e63b9ece720e778497c25b46ccf757449cb3b3fa8e5bb6d5a9f6eab58c97e9469cc6192b7b31362453faac839327067f41f25ff" "34c2cd40e9fee3a0b8133f266407587ac40db20e7d7d397e90558e54250111f540a44a70d427497b5a06c8ef87f6bba0082e00d42adc7eb38e890dcf5cd426c1bc2b4c781b07670382aa0d13e227e05c1987d3cd0241b5ad78387e19dfe4804189dd8a10cab05c79409b9414a6a384cfaadbefcbe8e3521fcbcaf52d92dcf1611ba3a824b576051aa24f42cadd7b7e9841375646740f2a6271d81d2d5f4819ae6a5d3f1feb6f7923f4252872c3a2709a8b8556b3977af8c4423bdbcf66ade1b3c4303539e06957e8930aea8ff70d6a202407aa44c6c8dab0232a33ff3f3ee9f61ed664bfadde8d294022da21b10e0aee583379d8dcdc078639cf3a1ee18d6ee1740bf1b917ff56070bf807b90d5a19f37a5c31214c6a19532f364d463595262ca057f5865f0d55636ce080acfd4e303f03372af014a3c32d2efec8f7f6cd6c825e5edf309ed16008e50aafa2584804c1897f6433e350cd91e155ac786dd9c3deb22a39d69e85331086842f32ba7cb6b4d4f13e08d90acaff24315020f7efb2b74214b14e840d739378afadcb06d45e7bcc17f2a03ed54d0da71d865508900334386ab96e11b88d2811c84539e4e2a93aa27d66620500789bb4d595a8b2e5972b1805d88af2b722e1e9b8aef10ca3dcf5ddbf3d20a6f101bf8f8a8cad825946dbf0c64193689f461bc0c62d138f902575ed601e26184a10ed9df17ad4be7c9672147c0158f132452ea502948a749b474cd0a63ae5cf942609e4864985b4060239d0cee6c78ce4dfdf5750b51ffbd5ee920967f5" "dcc52df6771e286eb83dac1c576f1a073687411cef3701ce6de66ed17bfe0fa5f03c63f96fb40ad70b478aae1e16efe22cb9e8c2aa57d5498803d35fde7f920b32ec686e6091a9ba6eb91fdd17b3302b760d084bda32244f704e14af619a5c9e72bd14c4e69f51177a26174c16d2e3eac934f184d460df5640fd84c3d3dbbc6785c249a501203374c0d58852d52c4c64a6d70ead2af1bca1d61f6f4cd00c3892565e085d3e603a0586d176f478062b092b205807fe7438a065ae7dbcb14f69c92cae4000dbd6804bf4eabf112813ff0599a29b1fd8bcf9d0ba7d9b14e40e38826b48204d8c0a50fd804167c88056cfe77e7a75ac36b5bd049571639b3f02a7e973abfaff1327080630a4bbaf6a096005ca2ccd54f076f2c3311e6e7b48bafbc9de38d01c8a01ee41d25ff0f775a2db4e34566e377683bad9a133482ab87907769bd783bd170b616d48974ad332e3defe94a2e7d6eccfb4cc43cad93b53c476e7795a087fe58cc074b591315daceee3c02af54d9beac8162b70dd9863bcd7702b7c8c72022856f78b2d249cacaea6c1dbf1317ca9e35664c518bf4155501ae77ecc3f47be6e7151c4d5fe56b893c69f1f939cdfd2b68830d9ea47a89fa7b3d4f620e0909d5a97f2637e2eaf223f25fb5ce7949e3ceb87d93db628872fc469f58a749e8b4841798ef505ef2712a3ba713386dc56b83e504c3d24d2ae8200698f9b3eca8d7971f7b82dbd5df6deb34865e2e6336fcd2fc3ff00bf9c8d04992f012dc9473e347ac05aff1040f010b1683c10dcd0bb" "49b7b5883ceb6c0bee4bd2ea6d275f884a37fc7151245274f208a457f4bcf180d793de68f09c7b03e7e430dd34e553362f91c4e721926eafd54d6c8464082d2d4a4c5b4b44495ddb06290f01913e68c7cd95963242df31741eae89eec41d0af689518ae335aae42c60041154356ce475ba0bc7f6c5ec798cd7c493aeac5e08d7ef554dc23832161a615a6b902e1d4f7bd076f3bf045360cdb73c3b2d7c158b74d2b718b95189225a0824a38836d1d4dbc5a2861e62f8a8c2723cbf1fe8951860f0cf7b4c6bc4c307cca509435e077f3947b8fcbb8ba1252b89d61b69b0328a2b1c31255c2c9df670bc244af42599cb5982878fa363627b321302255f2a20e04b70e8f4f63638af83a98ba40c55ecc46230798224de084d2cc203841d91c4f049c9b0a98535f3f905bb80b24679de883470c8225af80361031354483d879f98b78cdc5aeb07b371fea8355d146f9bbe16c9178f3d83ed63e2812048a386ef85d6c35ad696936a008a524f358ec8a2e40081c3c50b73fcdc6199f59e14b6ee213a8161f675d5938ce72a848ba9e7ed930198d9ae6c43dd86d94d88c5312be17b9dc590072e382607390e247869674ff446e8c37d89b7276aa61b5ebeb0ab18f500389a326341ee13283965dd4cce69b666d2c114372cb0e5b5d9921cfdb5e12aea0d95ec0a73c8d07b3b3e0dd8d159d323feb4bdaf6ea184bc2fbed75e7cc13bde26aa597ea7eaf0e37aa4be069c2c629af7debd8692befbf74d6c9939165e3238d8b2b573001ce957942b199e5c57935ecf5ae0" "c3b161b96f1f637605bc29bf5230fc65524041d9970e9b4bd6e7469e0c0bfb62e672b30a7094b014c27a06e3982d83a951ea4207a4d7b38eb155259b847ecba4675c3f82c48343a07e2d5fe16d3189c8dc0f4bb1fe2ca4abce4638a4462f0dd79d69c240eeac8ee4bea297bc1bd5683ca97a352712bb4461fd507f9125f895fc7ca8fc76c7f78207224d0fd142669137ccbac0f023fe1700eef77abc804e9b9da27ad5c3a767202a0d0a36f8fe86e2a8ac5f30303c39fad8b65a206239b881910f9d904f96edae31e4befce7822a7399ad06355bc3c7198eb1a4b2c7c8b4c92a604dfa4905109c35edb62dd3c817cbf5261f5069bccbcf98da9ee5ea192151237b31131953509157f833bb1b482cd011c361d768347b2d0da11b1dc43b392d609f0c4806d7325e92f9d76ecd278fcfb9d91e9993addffa55d66acf9211b7cdcf28c73bd4e7cf83a869532c90f9880bb963cec69cf40e117b3fdf9c0c5c9d6570a2458aa9d14716ecb8b6642a4cb1fe0fbcf8298ad0db3c676b9836910658f03bd47ded56ed210cb1e2f1088c87f4e225faabf29e2d450468ff6614f282e15b4a6fbcc9463a16f802d3ba071fa5b009403478f1088ca8a8d9eded648be7394aa6bb3590c0725ec87fdcc53c4d2afea49ba11f9f2b3231c912bdd9431ad941a7d89f70d8e1669e90553b047b5f4a033437fe3b84c05105227efb5390e6e99b597fa1c35a1940f513ee8aaef9485d1ffdf7ce94fd34dfccfa8f178dc113c32082e0345f6d39294ef283b6f9a566a87b1122e74411" "8e643cd6a2ecf14e47d68254d26942666fcf957586497c72c9e5814ab3371fe4b0f9a7fa1e5d9629d0dfe9e93fb388865a599076e7ba983365fb3bf574d335787416c099c545feeea69e3069d841b62e4db9833e6865e24cda78e2bc46ee83ad5d79bee507c44007200e64b5d1329930bd658e6f051cdefdf758e5b023650c2abda7a6827ca394c086057c617dfa8c161ea1f953446d8e0d5f6d5c76bedde8d596d1641a973e2b53bddb8f7bfcfbd0fbe4883f4d6d4e6f930e51d47ccc40148e6ed1b409705e9a777f1bf86af2621cb1f04ba160a5faad78a0949032e9dd7e34bbe6b2fa1c478a990d3b7c474a2f81af7f7246bdcc669df005adf397cef71869237c53126d1301ceab14011a529d4897cb00f7d93f35031facdcfda8110b9fb5d55a057ac9087a9cc8f1034e03f79a806db8a8e726e8afbfcb2c7c39d3315ecad3a2e542d94753b88717b7791c66c47a45f499885f6c096cb1093d9dd6082ba8eb2132e4a80e22ee309b7f74af55530e190d73315023fe4b52fca855a06fd111fbe1125910f4ace6dcf228447c007cf82fc50993de0202d28aed32ae795d2d75ba8c975b78c657af*0", "vilefault"}, {"$dmg$2*20*186673f316ce762e8f2b2595b3e8ea204aef584e*32*df036556654b76eb000000000000000000000000000000000000000000000000*48*71793cfc457320157f12b1351051f60e59fc80a728f82f0156cc8b3f20f75bfb4289c65e6c8c21589f3dc6187540551a*2*5953*3c25089e22f54dfa868b7460f43185a32b6988681952eca4a493ff4699e2340f8cccd06ba2df28334dd01b83f8bafa3754b7afce8f859ffaf64d33950a817d5ffa9671894f71d6ef35aefd00d237f7f8f413b8b8424db42e6fe7bf503d1d4222d77d5c3c2a16f26a1e15d7797cedd59fbeb45f70ff7731cf8be628895f13cc2937f82c92e0d5c6b6ee0214c668ad1ee4f41501dca668af0f83ef252bd6b6444f9028f12ce15134fcd8610426b5a6a75ac25fa938f93280143b5c991a683fb008a08e133a962dd4e3aa9ddb57e72955e3a840c3599b84d874d61cff4236fb487e2a344ee3311d30a531a20ec800ec591607edb97599b297ac67e173a4f7d98ce2d73b66c37659bc75becb65b799f0a1642a4282ad623ee574091821c971363128e307288b4377e1e90e831b800936f2b5eb05fd5d0e505d71e7e34311950812131c5b742ea238bcdfacaf35e23a4b5b9ee2a7c0da6aca0ff02595fd4229baaf700eab8ce7ea772e133bffd5665ea3ccde2edf61d11e64dbd1919454f977a31292416c86e3e11b762a3c6f0c27cf1a07ba3c4197f21c8959e0f04fae6a086be6e77b47495d0cbfcfce05e34ef361d45b1f8c5068f0174cbb2ec9a9f37eb6ae1fb0887" "17630b97bf46c801ca598878e6a8a96b232266479925e8f170bf76afa4acbcc6c7daa51c2b9a1821e5b5df170a8b57aa371019c240626b2f2a9d60587c34383ea7c12b300fb478e2b62ca9bf54b00f04f4970a68d6689c4087713e9b6be1e7c92ef16a7cd527d1ef33140d8d3994c07d8ae237e047bf478f164aee1c6300545bf986e570a403ef626c5fd14044611621bc5d5f37e417175a22288c2fb45b0e11e946f755fccdd774e5ace72bd2ba44be8f673235e9b49c0fd4d6a912493fa797bd97462de0402f77da7eee2ea6c0d02fa880ba57390eb1f73927d4616b95067d18103ad4b10af7a40b35e620211acf4c9f47fd12080b2df1d350d17afb649ea5e8a038157561b107e7d1d00284a59541c0b759bb424d2795ff1d3bfd7749461a9f67502df649d2d69e72036ab4f8869c7bb35fc999a9179612524e2f9bbb00e7dd5ef8fbdbfc486447ad5ea93b7220608aff49eebb98a1de88c68ce2b9846a63ac6b8878fd645bfc0c0fea6bb746b15301f58d2b9d2ace73828a623885fb495761be85780668b436fcaa6367776dee9e3af641ed5755f1cca7a931c97162f6879c7a3bf6eb47f98590d07654be8fd8582c5774f89bebf6fb113d75d28afe74443a64af360f41b9d243d8fb865039d924fff4586e3c76d9d0d43f8487200e802adb9e01460eb6ad5538d8549999c4b38c41dcd878b8dbd049b853aaa4426e74226fa19d3d501e6a93aa99dcea681f0044e15a05c2d08ae49f625ffe88181d2c1fe55e91b6f602409fdf961af1da851fff67f1e9" "c9ac10dd3960f460bb8f937ec415870cb9e99e150f5b2a2308f2136960d199ccf5900f130a3f4610cda347991cf34fe46717071dd5ab2e8dc5bc20757fe6357fa56a18a606b25c51612975f51cad52e5a20a8eb2cefc79732fe19baee7b8c65167e2949a4ddc8d1e262b47c97286c2d0fb7078b3f553453445053d82a865320ead1ff4bf4fea84cfd7ce21e7aee696a15f92da1f3d73c394d47a254247492fec3b6582c94cad0df1b1b097048c9c91bae6aa269f5a074b796bf86770059cc767aa07fcf84010b1686437042d16d693775a03d9832857bdde9f7d98392bbcc579db3bddbc58d8cf08f04064e3eb92d87829e6617efab245cfbb6d564c5fa333ef560d6105c525e39177ff5530dc154b691b1dabf14d0da99229a04ca5c6e7956d474c0ee578b1b287b0a5971506687670ea848820c44875c74e69a79b36eaa3cc2a5a27fd5098f0fd3c190089736a271ecf3f14b3259cab95b941bbebfb5be132d875328a1b0ddeed958e8ea454ef80724f878a2a690bef56fe3ea62f47cfb6db303ae608957dbbd57735195d6b1b2ed73e69d1ac4b4b4fb01c20eddcb29e8b44bbd71fc25515885a56b8b7e55edd4c21d5e8cc43417e94e57cc49f279d0ed740b286d4e27c0b909729c4250ea2d1857f3f7d801a87afcee46f455f8a53e211fa0a311006cdde262ad4bc47941bc52db89c4b454b7075bf29d9cad6c98b7e84318a071789a78d1a83ece7a24cbf17691aec06c5fb7bb8a832c0aa33b27a5b3a68ef36364fd85cbd19e8f75e184c3d1cbccaf7eb" "c71211506021ce0d38bf8c0885a205d7f4a60f7fbc972c7e2365b07d5a52fe8ae02608c7bfb1650ebdb4f2620f2698f5fc90c7b42a34a31732d2cdd12a4bcae3ce399623211946f74c67c5e82c0f53701bb4460504e17c1d6fa14288a63d97a86068be8ec36670adc16670b5cb3c09972b596cd441e4bb9b50471708bab77691417517e91883df9f0b353c2bea3d0acffe5410097edd2b3886592cc70ccaccbbf64d168637a8a3fff0d143e497e5311a9b13b4adcbe8d2625dd1fcb5ffe9c83ddd4a1cb3046616296faed945fe7b29ab6f912be6959f8768ce28958f2441a1e161147145a1621693b9f2d24fb9c7a89535456dab48dbe15c689709e2af6a6805edf923d8504f3d2cb8220ff9966f854c84e9ff04fbf45e42a5c73df4f719b9ed287695a4a03d5c0a3a964a7b6e95bcfc36a292b23774812e8567a02cb8a5baaf89afb900b3fb7be40c9e8432656307fbf2487c0d1f3baeda11e803f9f298e7e0c478f9fac11a43ca32e2cda46ca6491cc7b31aa1725d24805587722248dc326cf81fea4fc1ba9a58bdce9e34740e3732b96889b36e917cf029c7027c5cc985f8b3f0fa4e504325d56c7e653ce903e8410a6b06a2126b3aae2030404441273c1e486bc8285dc078c1874635e75cdb753a0fa821567e8116179b78039f8cc52675d538fe38a71f46792af445b125dcee671bf7789f2e874b25f05a431ce574a2d85762ceade5e5cfebfa5ff62b1ef5ee155fe418b16638c1562b29be425e05ef0237f03bb42181f55d4370272a13d5fbb353358d" "a434519cbd0e4fca54f9cad4a7735238098d3984b0cb9360eccfc63b3b4339e0ad2b2719552085d7445681c919f21a6b482402c271e34d7f9fbe4fbad68eaf825c57d22ec0a2c5ddec8c1273131b867a3760626abe779e37ee632f41f212e9a9aaf26fd5cb28df689d9c4875c49db62213faa1e18c35b5d2df1fec21852e7c35d20d6df85ca2a6b10898b244da31dbb6de3a3a8553601c0dabf1e5f4755fc77c1561223cf0b1ee43441c3aa9d855df0831db6a7f6949ff0ae1cdd465aee616b789c268417de07e9c0f0ddae6b07ce5186b3b83ef96fa1ba9fabda1bd79986efa852a348364e33e89458550049522e64491a9b24514665af058b4be4ba690299d3c2379b25ec97575a9312b38d3106f805e829bd77033f4d5f1b35ffc7289c118749b31f17babb56f48aec597049d635c055d056db0434493a379d15010f3325690444e1021abd622d18ea7e0b5d5b97054708ea9087b4721bf857e3504aafec84516feab2a6f6309a506cd3e931ef3ef47807feba8ff0b6dd56eb83349d99be8633675eed19be804c06d4d81b0a256ec95cfbb2b6565d7906537c5adc404713baa8fc2e0f425c577660df47198e91d2eb3ee7a9a5025641aaa759e7e1f3dfd85c83a17a6a59df4af62bc669f28d12544254f4e0527a6b10958664af9378e41aa9f88ef3041ee6880f23a858254b5d0fa7899655e9d06f12fa863b63c2c950a0c3eae774149502f0fa3c3a44d24add7f9426ceaa21dcdc5408f0b96d63dcfd97dc4a3ce03ccd56c8d48ccb253e82d50123e8a51" "76ae5d1b9cf6b6c11d2decea9f91e9ddfea605eec75391ffc4e01f4988c0ee78ccb3adb8a5e16644eb30e7e76ff251192fb3a8c48a68224a2cfee4aefa616ccbb68abea13d335a4b212b0b9841a42b418cf413fc868a842a26950e11061608a623a5dbd520aaebddfd1a559705e8cadf6abfa272925651f84130223b0056be28b618bfdfb164d2c5db86d82ac0eb2c457198a6cf8b0c2f2560eeac4441df45a9192cdef63a00adee0aafed7e0ab0bbb0c0b9a066f9f45f5e0c6a9376a069a45512081ee3edd2e9679d6c46d71e3740c5ada7457fc5d21610edccc2bef851d18f89e8307105855da15dfa749c44370b8149de48309f99fb5040d05d0739a64cf253855c185550339af73be6d5cc2de3186ff4b004ac816c1f4afcc83ec3ad66740c57b9cf660de7ab97b0771189fae5957751eec58a3aa6d3ec6121bf767d13533ff413c84c1ef47142f51ebf515c3d60a3c5cc3b9eaf9d43d2a84b94ce02db3f254862cf3c6330574fde5f8257c215c416ac3c9833839d5b33436fc12c21046025a4b0be90f18dbf002e001b8541b888835ad138def9910c4546fa0cf496bb4415463cb10004959dc6b0e379c18090bbd1aba6e9588fc21a89778ed1a1c0533049867569691aef6bc310fe4853e9e9bdd94a58943017a197526c70d2d278c66e94aa97abe5af8d9faceb0fd4e102bb69c824a1e4709be2125de420aebb11506bd62ae6b32eb1bb2cbcbc35dda3c992193086b11203775b33dcf4206a976b31222fcfd8b0e6beab7eed02f9f6d0dc2959929e1d" "30c856a672379ea1a20bdea6e023fb7ada31f6f9e02f354f464b2261879372c0c92ea462ad11a83d54bacfce3febcafe14753d697e905a7c77031beb83076444aebdb99cd1aa470d5774ed91cded7eeccf7fb18860fc39577a054b17aacae86d02c2dabbd3ab068c982cb095d135c11daedd863bf9abafe991656d1f7773cbc05aa66c4c800b5763fe845d06c3b19f4f73dedbcd50ea363aa11e8274d541ab754209fe7fc159e7bbe317f8d9ba602bde8fe02171f8daf608bcd4663eb401c7a3f2cc814bd8fc195cc192d4d6fefbb15b9d9738f5e6ade7826d65b9d8477ef500afe2e40077b6ecd7d3ed78233fe980332a313fb2fe854d6becf9ab4c1008cb1b16a513d3fbed8036ddaaf372e8891c59c6e9bcdaf2d88e22d528b975d1a36af2fa792028a3e1161a74545eab1cd6284079c2353ef1c49e3e1242ea52d22d8c7d64f553e4c396e7d62c4a6619ec698b56cf25cecb6673d8a3a703f65e480f1b8b91e4427e9f1e9dfa1939134d03cb3115167567835d449f50cc9bae06adc68e3211d8e0cc1faa34f7bda6e1cfb088fe980397f4643e89052d2bfeb233ad81c3cd466bca1b1007e2e6459e3aa1e51f1a326a2f5d89407c05946b0dc7741f458464b5e4ceea5e367a2e4f0d007e9e31b24f5b7bf69aecdef4ef57de58719cf9fb5e8f5366452013a5bb69c3f1807d83e26bb63493dc141ab1ae8eeea11c495650b346919de060c4af1a80823fb10b4cbc333b9d6d05c6a4c293a7fd524c5259a841500617ee442222ef2cfc71a0e4bffa87903ff5" "31898a44452ca2b132c4a633c91c7a24bbc885a01001988ab845e53a350c3b283dda71360c7a9b47ae40f72737ab6be068ed8ecbde1d0bcaecb729c5bea691ba0de6867e6e6879fdd99efec2b6de4c2691ec9031189491a01329fafb2f0d0cc28e26a22bf55be6ca866dd4a473153901f244c63967e829d9ae2ed83451a365558b697055a3b9a6bcb1bb40ae56f13d4b60defeb1a06cc6831e175ccbdb92a34462e786ea28e2ff25b813b63b30ea3b8d9a0921a5a5bf45576b39fbab6071fb1412670c936b5fc31d668026d297c5b84739021c4e763686e4011a2bb7e109db8e1d6bc853235a44ddd93f1012f7168ba3091a2a92a3e05bbc761fd97ebfa22265e6c1c2bccaa9d327d4ad61de87d3b5f0c5b29e604f79827064e05eede8b574c8982bcc0439db27b15bd7ea9a38923a1982fa7063f9f1572963c75168d53756803f6f60604ab33388ccc1294fb0ea143fa5e128a060da40f4dfa0382906b878a602c568f3c99809cf1d5912f224b2adfdcdda84df149217bf8edae18fb4bd825900ddc57ecca2eb7d209ac44e06e674c2b7c126756bdbad066dcf187344824050b16ff9414fe957c37a048c3a260a8dea72f7a12bf5b35e1c2205866bdf85367d94af939bf52a3027e2c560ca096a449b7297687bee98e4cc56e1449448461d028e435fef26f060097cd96bd605d5a1cf6b1cc95c49037401878b85d437ee43bcfbd7b2b8c145c05a33fe01226a637dd677bfd28c8acebc4a30494917c253957462cdd5a3d200e350f5d92c5c57bbbc7b2392e4" "569610f35e3707aae8a481b8500dc8dcfac689a018671a0f3634d18fc7bf4f7c58933da452308e348a446ade0bdd6f02d29cd8d273544ba46f1767873717fea45f0e0980339fc187acb7045612e95db5dd9c89169daccfef2e3a01c4d19984f8b1cc960d054285119f23e746d743a0db459bdd5803fcdbfe92137e80d47c84c547848ae563695cbf113253b8a96e368bdacf59ff73c023d043348c1dfaf143ed13424662c2da644c25b9d22598813e1973f30ab103c0ada9ed247ca038a056d18f2e7c8443fd2c95366b387e9ab972170cd2b4438455dc73619ab3444da0d64b0b2d3a9d640ea917b1c09d17c37fd587eedab367235e1748dad753e4cbc74dd53017ba65571a5a65269666df0a24bc694a2d24e862830e7808ea8ffc1fd6cf4b29564c8d77d9692d7fd55e496c69f5f17fe145abc0dd1818f2cf6eb979c33eaf41050901dbbe5a49c8bf9983b1284fce92703b45c4131b3204fb9edd58b6cda3918cc490051bf9d6751b7702e577b700230f1820238b959e46f7dc3a3abad842814c69a76be5376c1e7b35e3ad7318b3439008e4c3801bd6754fe67cc7aed658d89550a30cbb1193eb5d2144eb7f84c5c6ee9e13947daa3534ad4902ceb9cedcae471547bf95e2337760322b55af97457d23d174b1c6f3e1d3585feb000953e298e35aeb467e90342bc61bd05af59c72921b2fd4795c19bba268bc6bf4f18349ca91b89cbd6814a62dffd4684ab78e998f7e3833b51ffc495ca3e789e685417a0d972bf4192b0c50016a64ba839da14c3c5bdd" "58a74e96e56c66d73e2869323093892c5272aba5e6edff5a8976c5e04976c8bc1b8cefa630cd924b5bc7d28dbc67b8aac4d7571623c4d412acbfdf61603d2cdf1bed6fdcf8d88519a3ce3c4803317587c4a7dd33147f66aad06554d69138959fc3172298be9f5f83748b83c6618758bb45058fab1bbc1434b993890288a42910b91bd52ac1abe775acb09cf7173ff9fdf0e644ee94b000c8ac5cbce24d424800a9df431e03c650b3f4196115f100b49b7a41f68ce27e5dab5865b40a0977cc1be995d3504dd3bfcdc8db2a57765b1a80f6cdac0db795336bc9ffa4cc163df1d9d6e034d5b246cf59ffb2f81ec02ad4c48eb652be03c97a11427ab519d8fc8d704fea98d597e44cfeb168f3fc1385f1a1dc5926dfda78be4c3a3e1d024e4492e952cc8471ae1f26150cc065bef433c0431128c7df6c57bd79dbd409fb0684137465ec0687ec2ec45c6fb76eb88bb7bfb4df3fe69421dc7e0809e2474f987a59980fdd92b2a66ee31fb9560b4657a112ae523caec636642e44b507ed5a900fd65e29d35c89d252708b7f2c2daa29062b94577b0406ab9cda76c921694998192078e2ba7a90386e1544444c228db678f9c7da51a06b9c0a22ea26ebd3dbd8880a6e981decba2f659ddfcd15af8d06031e2d8ddc587417ab536fd4cef49372e0510c58060f2900e030fc894f1edb6aea502b0e2642a8cb1e0d22cc11a43cfe8eda906711e059d6e4a55959cc337dd54428eec2c123f5cfe185a78f442266f54213537af2f4b42176951bd9b0d1b70c61ef5e728acd" "1a5b0c8f0360fc3d4106d1f1a6a100326500e25cf6ce2c7f230e5e54526c3affad6bba78eb0a275ef942e441919384b0420571655eff68e32cd97a322e22765fe736eaf329f41b2ea005ad56acb4c092b7bcdbf2bf3e54b058827259bac8bd94ea73e1d61cba79deb078857c63e255da3b8ed4bf5d4f603d8e3e19813fbe997afbd272102aef06950ab6daab60139fae51f0fa8b48f3e056a360f074692f982aac57ac3472539e7484862997ed283dda8be4b22b83235299d1b20df4ccbf0fa24faf392a8433535d3f3cc3ad7453b9b150dae24b8c78f149b53f5394af065082540b46f6ec3e70e2428b873fa564b548cc1e39fb406ff897662ac7e901384b3094c328bd484980c120518a8504511644b0616215df50ce1ab6106762d52ef24d40b9851168c69b3068682525f1050fa3ae139c9500f89d1b5a96c35f71e25f8ac229518a79fbdbfafcd67d7356bfc3e9699f0e5a8c9fceb068f810cf2c8e3042b5fef34778a3edcda569dde4fbc240996038e50e233652eb5f303fca7f8f29c633684566f6548bbc311bd24d7e0ba95da8f02917048d9777e5f142f83cce4187ec1af72b6b6c3825e38646f9f29697f6fe3b3cd76*0", "password#"}, /* test vectors from CMIYC 2012 */ {"$dmg$2*20*dc39029a22b86bb4f930499578d0dc9eee69398e*32*bb47bff69b10ae67000000000000000000000000000000000000000000000000*48*c4559cada09552ab075e73dbefa4aea1aa21209011946e423ca707753a91c87f6c4cbed3beae20a244d33568f852068a*6*4315*504c0c37c600618fd54da114fc0eb24d6f24585568543126ac56c034cd8d7b3dd991f1418d0c95791e091921c02bf695b7835f7b0da2c1b96524e72b4bd3f671c592aa176b6a58de77a35a26bd1d0c313b2ca23581027fc52c7c63f37439404218d720171d3b178125e6ce0646bd6fa1033f2ab7b6849b3a35a430cbd1401f73b5deb478d6d0f58364579c208c613cb2349fb19adaf98be2d4a74a6030215793fe4f1129189626bb87c23d26dc2af51a98e1fabf2f58e106271c7759d104b9e5171d8f952ceeb14317614b7a14a5313029aa4068b898f7e0f5b68683feff0d375f2ada37f20135df443bae913c7e96a29c6c3388b4b51432add89ee22826ad0b1b0a4ca9233e691f71a5ae2c76b5e5a135dc793e081dc53781faa4f844928db94084b53b39f1820c8342b563e3f46b002bc52ced63e4588388e69c9e85e2002438a1a703de411717d24ea88adef3051b27def61e4b9a31548d3714c3bee39fed866254033a123429043d0c08a052d2999a171b010ffd119f90bf9222462508ac914e0a68daf93f63caaa0c4302c9b1f6447ac3856b09eb45096b3a294731f110b90826b0d611e6e045397b07e5aa64afd271f1c92664e648af648642f786c0c8aae" "6218f4282d8efa713dce232fb24df4073a0e04edc86d940e8ad22db8ca751143743f9f12585bd788551cc7b70821b5c42b133cb7781f60d1b9c345e9adb122ae444be456b8e49f9bab0e2033019b52f2ede4e7f56cc1d1dc3a48bf0666cc7a4dc6b4ffd5077673f2f6761688e4452a4c11b82598cc0ef57213f6c7c12ecc67164ae501b3e87e25a361d0615e48cde249f0193f2aa69a1eccf029340531becdee8eefbddca18905451b48c1085d4cb965786d3892d7144841300b8d2722e92af50fb828cdd8e825dbfb16328f7cf792f311f84078d45306fa570661e1ef2b34d5d36de2fc4b295f5e84fae8d55ca22bc15764932d0c5dd3cfd914b2b8f67477b2b5139c822ee2c511a03f7e9c717a5e8eca6c4b54f9c3b7d85765a78f03b29fb979811ff0c655522b341bb54ae3bc412eb760eb689c6b4c3bfb85a8ce794946214c574105e577acc01d3f8885e72db52075d05a75260a6e4a54872d087040ff38f8942cf150c3615088588cc53fed11040bed573c0e9ab14b987f9223ad089bb73284443f61ffdd61616b8a783e85618217e8bb491a31b7050421f4b0a0bfa5003775933db00e47e4452adc1433da2603f6dc5b9dfe58efe458da25699e512660ac6f1129dd9d7b176a24109c6e6e0c201d784addc9c7f8d4f309ef6fcfb02493abb7c836ba3a371e64fea941031a59adbcd4ef59f0dbf31f361f4282a0e60ced4d9d17675b0422faa1c2f932cb525ee07df7eb2643a67963aa99daf5b119884557ef1585d81eac5c8acf32438636a10d043bf" "47093fb53a5b3ad544a38fbc3588bea3ed616167a79b2133efd8c509f53626b9cd7b71828fbd5d61b1df6ef3713b5347f65e7c0770715ac1fae561cc548864f9cfe281c6e5770f053f68ace64702c81c97976f471ad11c7551789ca21a4d5480c5d3528503f2f7fcb268c34498888d5fd3edf1c71d12581c393db2ff863e22c1f6c037106e5928aac9118702b45bd36782b2295782f93458dc120e79cb3d1632c2c5e527e56060b79a751cb7653b8c0ed2acc32168b56fe5b50ff9e49a71dc9b82f812b53e095660cd7d59c04f31ee47773a04eabccd7a4a6455ebc7d719c9eaedc4e6c935fc99642acd3e60e0f564efae90d7d1308d6ddfe7eb89520c234cafca6bc7e8ac96ed401bf96e3c9de704ad124b0f9381f22d9ce846fad0b14eeb5f93eb0e0fd0657c480fd2a1109d735f3825db598e2aa7e624f282673947c38aee8832ec8d4dc5d6a7306e3477ab4e37588788109a3ed76741f8f2a796d0f5bef8247eb298fb973c4e5d13666d87b0bf5a7a553f208050dd7140f64fcc27793ea82cf58fd86ddf805a700065888bbf6b5037815afe8c03eaea355c90bbbb448de13773e977fa4c6f06e7695e80882cdac40301b537fe254eb1ee437a6ccf3efa68899a7188e6829b58977917a9d6124cd2af7cfa567fb85aac9c6b971423681a0b6658575ea0dd32054800e08be5683faf46165c56647e1c346961608bdd8e6f999eb033caf73f000a71961cf2fa8c319f4084c0ab499caab87d13aca3f057d17748522f08b36c56c1746e49d731f9355100879" "d7d114000293520c9ce71098d26b2114030615aeedabd5a6f7fb9a91f98b7ff00ec72c82136a00e5a19384084e0aebc78bb3cf05c3c1e3872f56e254c68694d930eeb46ca8e99329eb923ee0f1b5af0b7276e8600e25f18642247111eca41da427e5b9034a6a22627734ee024c2e2c4277edcb3a0309c3007c19416fa131086eccc6f73784e1a008dba5166e7c8aa4cf8efc3a4e14f59d665800982e46341b9b098508510c7dadde295a784f7a7085f5ddab5b6881b305f99d87ce3883e557280bf2a1f3adc69b7cc9d4f339623d21d569230e57a2bce611de7495d403adf451725d7ef11df4bde5a31a95bdda0d0c2a7869ddeedf2ca7e1986ef430ed44bff6ae6e44f740b2c65364477ade4dff6f4eacbffc67a2e0494c81e0424bc9220bf20aa795e2b20db6076667088b6863243ccd2bf897d4b6e1e58e2662cac593fb9a86220d65964e7f6e0f1987d07a4a8242c41c001ec38ed2442011d8a56919800b4d590338eb8db02833031ed0422bc08b11dd59b59f1d301e82154803076053464120217ca64bacc02465cdf629732cf709777452e177f4a4d1015fec4c36337ebdb8daf57f19bfeb247a27131ec5280038f3d1a766e071470ffb685cf4d9763b7e1b5776589874f3cbd4761d5fd35638918ad144a4a1bcedab9d652477951a716e4073cb36640fc257031f06e4d6f586a9a0b6172727933179e4cd433ba940571f3eb908535a12e9cc3ec1e8f8aa9975bc17241779d972a8fd8581dd3850905cec48061dd5fff1b295757e38ed8568c3a2967" "ba271e00fb507b10bdd5ac5b90426e48e596ed430b5a3c554ca1cd0d18a90809d8db18853e2580cf2b2ca52ff686b7cf360799bf69c008f87191ee372b44f96696a12632af003eba51adf1e6101628168b92c718c6f7aecb765125880f180047ec3b89fa23bf57e4fabbce38ef0fcba829123f0a3ff527dad6d6b5b0c4b0c4c4cd13787e98c829bec08728acc5e90ddc6bcfe2254eb29ae8450ae87841a39958ab80a38c8a742de64a44e25df0360a9e8672148347d7812bdfcd9037723edbc5fb4a8bba689dfe3baf113778a498e2689e8cf1ad194df422838a618b0cb222aaf020705fcfe1475a8c205690379cbe2d0b5f9a0de41a4d2e6ff85f1f19a97712bdbf49bb90051ab934407bdda9bdbc1a57b0e874f3b2a09df45b7d01bda15330ccc57a752deb2751e495e394471f09f33d98d8face401d418affeeab86be36cd8cfb0f435d9939822041f256ad860733ccf137e582e1cfb5a8b96ffe646d1928657c05c67b8589a90fb32e078697fdf8a3ec58dc6d350a7f50c83d09e5884317829d8e850b7fe17bd2ba4d7fd94b86d060a3a97880fb350b95cde4542cb7d1a2f44f8ea065ae30fd4d4b5fb24f787b8462115b3a918155bae098f0fd7ae2d4646d3731d228909f690cf0116e1ac15899513957834e0a74d8c07f0c696cd3268d631ce1292f66b2633a3287a7e058781aef9d3d566e4e41395fa7e1793aa9f669aff116b99660a5a29fe127a0459eacc3fefa4be95a13499dc844d9faf72dca38d8032932084faca23e4022869f2034ace2de0" "b286e71f2b569951214fd2eaa3d32da48a234265acec4967c74976b5b5d635eb12cff038a4a23d6c8e86a11a408aee5eedfa7209a8ce8d6bc10271e4b5627e16c5f8ce8000882c461de0113efd8ae9cec6ac4819ab2d6f8a9f189fa2929807fb20a895204edad9821d180c54e865548f9b3eafd8073a734e61d574923f0d1f69d266d970102434b0bab705465833ec9926b03798fa8a95ab98d35863b7490db07fa1abd600abcc3718d105f26f96d20e593ce0c82efc68ae65d03e4e2ed3faed27bc5799e359588fa884ac79c1ad4f5f8bcbc9a2a5605f97551710e2e416aacf149941265406490d32cc6bdde994943fac2102e57785dca3c20358cd431cee285768d9eed6ed32a9919e13f1a38304db6a57f637b6a5c8adf4e829baa82ce674ec7444fd9f7f1807b8f65d4b68ef7b6c3fe5bf653e81525f7900916f5d5809a52c070256e6b4cb332fced5e460c9a2f62bd73392bdf4522be7c211577559f59f62869e0a71f832ff493fab76bbe70f3c0b902fdf45cf49793afdb87558f1a6ec289018035d861990eca1dbfc412492cf86503af00c7db7a0a2c6374eed42b440293938a36f61e1c4c187cd50d974f2a0989b05b8ee207398560b516aea520044e37229fe0efa8b7038441fd584d79c010c0f31030d60eaa4dc1fbdb5a254c089198bb5eba6fe20655808c1d22b9604af1247e2b820823b3c622be2b01ca5f16f86af880908ace8765520c813afefef18e2c112a72fcd4760da91f7d1066cb5c8c902745b83be8defa193bc8b6b93a82efdf17" "13a223660c6ff4dbbbaccb1a4e5482cc238388448e8b9c24c9aa3acac9467e1f6d96d6deb1cbc9fbbf77b7e756068e22bc3b9e6c275987c5eb99da6a5e2d90a1e0558c4f9fc392371c07a7844cb947b19dd1a6d9c1ebb6496f36bdce2967bea2971cc1c6330b1c31054c07f8d853858a46ae9370ff1d6ab755beb120a61b4774fba521baec6fe8a079862a0471cdc5080c0f073f7e3d33f0f25978d098f61bcb4905c776ce6c0562dfe08d8b9f17de4bc2048d962ad7f4baf132cd0152a904fea9530e7c1f52a85c0188d6ca38ff9b692b2a68204a6dfbfbec06f2d800b4444503bf2dde736be4108845c5a28909cdb42391b5a0207c157003b8dbd4e43996ab5017c5f21cf0d4d9b3145c0cb70fefa767b4689cb750fa7657c4a788b7759f86496998fd4b99b2ad1b2918bf330c1a81e8986eab031e9f86cd93b7d623c72e1a394f0862a193f21eeb858524477c3192fdf5b61ce9dd5b0bf3b3d7adbfa828f1a9ecd4dabf5e318fc40262f0dd204f28b934d1af7b0d7cbcc20be21f1c7e04fdf76104767892404b14965bf8d53003ca9ff0a8f15f5d9b2e152a662ddd8eaf7902854d8561ff088fe2e880a18a036d06c29997dddbfaba32ae4ed70b47413c2a037122d830d55bfde89ba645562cfa1d29f428da108d93562bd291748a728d1b3090b8a7f56293a3135f05d6876021e92aeede437dc7ab610e1e5af0a00c880887754d76b42b059f32f9159d25ffc56a993661d06a7973d190fd10c4ac998c8627b494444389c529e41982726f47135212b67" "8b69ff36ad29e225856ad2081bd393249f469648e6ea4445e0011adfe320b4eb5cff1d9332c1779edae5d5d66931015e793f730be8482b5f488ca6372edfc71abc4b8aeaecf8051bbcc848d736eb0aa0d7ee4cdb9eaddfdcd4200c3e2f58a97a162565409abc44b8e982fb883b619fa80c7c4f2318954767ea1c63c70124f4342118f2c798adaa7ab5f6ebed1b0a15e12f40978ca8e5f0972a47cf397746f9f482902abdda10ee7f4c610935070f888b5ef8eeb07933e1d6ecaba243fb475b4c788cf8b453638ac43b9f6eb74654835678b47d9437a14300a12553fdb10daff3690e0802dab80fbffc401422a465e10e6414975358249d68e4ad5a1f1c93e295bc10b8c5c11ed98c7ca5773014a2739c0592dfa30d8756be1f66e4fcc01beb2dd58d87800e71d136c12b8f73298cd37b1bb5758376b2111921fa9f7040e69d3620415ace96ebf29fc1a87e392a9e701f4075208a1a8fda7a59b28997c017da70c18d2bbb5c91db86d701cae85a5742842fafec723be9d93b4225619c7188f5bd23c900ef3863068785363ab861b58aab8e91b562b26f72a812e7892ca0bb6ed91086a2935ba82938b367b34f70cbe40c02a8cea92a78588f90cddcabd2738c9a18450f6d3a87c7f827a1773c2c7629452f64e1528258a8ba75bc53245c705246963369f1179a765bed41d*0", "654321"}, {"$dmg$2*20*0e2a3f19e5f9a89ef8371580fc08738b0dd02ee9*32*57b5e138dcba821a000000000000000000000000000000000000000000000000*48*4a33cb05d5fc441fe39477724556bf2a3445d2826dab91031374075f9b5cda25084769a7af11b2e678d79514be8e5f63*2726*8192*585b8129cddff9f9f5875d62364faf4dccb0625867ebf2cf7ebe08913e340c8bc5b62e4c4152b2274a19c3fb7d0f6ee32e7b6c502073785bbc213c28890b9910c878702b2e16ea0c0b0ed1462b831b1eb02a0a5ef586de3e1bb7b5f70b64e713f2bfe7f401ccf0a4430981b89d23afd47d05d1d28d64917ad2895af8264350f306b7a0b67029f6da75fc60137b99131d3678cb8c596295bef4eee92110d09c52cb30486709fff75b80753378918af4db98e69905245ec52c2c6ce7e71ea62b6e530269af23836fb40cbe12a1498d3d4e66ac26b04c31d4a1cc169909f51c0468edd44d051d79c361f547d7f4891195b96950ebff98f70b36106772abb775308cd6d42fae3a60d748330dadf7ca90bd474d05cdc678a0cf41a5f4461285ce0ef0a6df3a400d0116d1d1f17cd10be2c8f164ffbc3797dc022ffe52b69f0303526d3a17c113a56e67e54b4de121787dc62977af8bcde3f4fb596762ce31460a6f97d3d07874ad42f97ace146ada9b63f579a411fca985d85d64bd3262d1d2ab5721119b0cf8348abacf7aae2f57d3b667a5997d0fa448d3da4c51a6f59c6686a92a35ff4d6d951dc74acab9d956e9a942d9356291f56046c612ff09d1e10d8a0c60" "bb2a4d273b03962f5399ff455ef480018dff09125f6c343f28b13acdbe7f0309e64406d2c453d57d6e78f10caf01d8dd274e0ca6e4a82a208750de92640ef97f67dddf90b0c6de767f185b6bf17a119a735cc97075b93fceeda807d0ec20bb4ed923ed8855202d7d285b767727bb5db55241cd21cd5a7353cc872f0d4a00fa0a50608eeb4cfbda71109a4a2ae97f2c01a40c4968c32ff2c01f05ee768b2ab22f12697805396916d8fbc1b06eeb320d619b0e472b763e7a72acd949e17620f69839543c3852c83e5c3b1cbdcfcfe0e3507a4fecfaf3f27118b6738ae8e33801cb1a2b4168f8f614dea5e673878964d6e27a1d8d8aede3bcf366400cd0155cf502cbc04234a2a418638531ef13c48917328d2bc1736e85be9cd80cf0d99b98d0baf9dd9bb3f840fd15d74788043be9f791540248b5dea621487810371995e5fff578de770699ed8de1f5190cfcd5d47320594299af29efaf204e0a411670c6f4f60652422a7e25ded5fcf26c1d83f805938c1ae578bcab6ea5c679939e5fc6593248d6b8fd55c454d2c69e8c756982c01ff76b4911ab494d90df56d7743f4d8017423a045eb4215963317164bdbb473620e8a17507a9cf26749c6141ab7b94af974db92c875ecfc4ba4421a37da4454867ea3f7d8580185eed9ae3271050d039c25f7b72e18024f91edbf3e1bba71f697c8451302b1ba97c8463b3699754fabf472ac399bd3a783b51cc945051ba1b411ea8093278606efe2b34b3992033fb773fc42cef45fb0482992d5f867416faac3912b82" "eaa852935b54c1c05d2b5be854fa75ee754235ff1e84a53564070de838fbea7704fc249a98c7fd8a4d4ffdc06d5fc0ca39071fc5be83b0e37591e14ee76379f4c5ac64b21f016517ac44a12161543c43d40a8f92237c99de44ec220fdb502d82e96f01f020eef2752279a5aa3d3928a4cb594c5e145d016375e3d7a89d2bf12d4daf3886393c31615fef9e4201cc0208821e932e8b26df396e7c29f2c0b74c9f59ab79fa44b4f9c1156741e3da93df51bb23b756657187f1902f3d5c79aed88190b4a5f814ee1010b2fe82a3edd867457dbbf0598566d80261f83db810d058e785261635cfd1260c6b3b43081deedbf0b2a30d801618090d07340a6ad528b73c7d652efdc48fed161b0a0529d5d1e80fb0a63411d53e75e9ea9873d25a3bcb243faa406293f53a21b37e80023a302682943a30c8f1a5804a3700fb92092677602c39235246f359503cb79d2e084cccd2b40840acc7ac7b18b4e1a665e3833f5b4aefb40f0b36b70dd6b125ac9999d113fed15e5cdcb6ea6043036df3dec7f5638379971758e50f1453af5e48ecddf1d46e575cd2cde1b2091c1797df41f152fa77621f69169d42398312155caa88850800f9a8792c364021463467248e385bf45cd40c7869efcd6e9a24152bcfc8370ae901c7757a19627573a8832e5ea62c344fcd60230a3915561b6fd957750af61ced54ca1ff1a8edfe5ebbad51a79777ebd4e66c63a248687220e66d923c746f56f009f9d3f1f186d987c057af87f7a70a213c9c6eb93867983c3191ee956c8991275c5" "5b07b2ef0eccb8b0287414a154afaca67f218ca43924fffe6e6161690756e3d6a19a29ca972987f603727397e5f4fa19d0c3f1e74f026d35c028bb81450c7b5493a7d837e83504ae7369a49b2354c6c6219c79ad8cf9f5bda3765541d9691b84d19cf1fb9534f859b58257e80a7548c12ca2c0fa34b8b6248b30213be0eb60de5bd04621c163e4ab00d80adec931ee00288fb98e5eaa8f6ec83af863b8a3634f955b54aff779725479d80f2fa51d25e721b159a3dd814db70836a32b3a4e55c4def271a1918805f31fd3af464c01006560b36e1ce0a745d3bb121710083101d1ee469b971400d49483b6c4d858cee24614786f227f320fe6105d61fa8cf21136e9160770167e1b7451a3d9171f56bc436f097d73dd4c21c245efd72b63fe21d1600213ab4f2250e6c5a16cfd3823de93c9c56ced668faddb77d60f4d4d9a9a3b3cb9de0eb5694410fb760b7421cbf6e40ca4e8bfd4577fc3528e0162ea4c9aef069b3e4f199120a10209a6acb1eb6e39fbb23896860eb1366c6eef023c2bd63edcf73aac6094d25cf3c1cb0caf82b1010503fc8e09bc537e8e690f8bbc0ef492f848f77442cbf28bdb42aa8932109ccefbd2ad6563fd3d315cb79a0a5f04772105e8564e01c1e22f1c2ab98813979da0a08ee8812acc1c18097b8f1fd95424ec0d1b63a85e84257d382400c5f44f570382ae8128fc0935a5f7f518ae3808b79ae7aed4990edd9257ccc74dd19adcde363d4c7e5a4594e3d3ce88d308cbb48fe26edad968cd54cb715e460c7b421f6debe9c70" "3bd684a52b6b9571a7cde4568d7656e9bbfc5559d2c60e11054cba9eb54120bdf13c4c5103fc777033014404d6b4a65ea0a716f76a1433ecb904e9ac28b0bb8ab5c5b0216f62c18aa29b685cbe1c9172d51bdef81e7ead1ebb5d6c7cb078fd32cd63c72b163d2848de4c6dd59b35e853d6ec578b681af969941c16692c9010576f6f3777a24e87084c4b78a8502d083c137237a60705080aa90b2441e2f01ef9eef5b0f2b25b2b745136cb143405fe5c7ca013f88392428868bd9f06bbe41872c4cb1f98b16d74d064e66b0c435b52913b8153d47f52fd95ee73ab1f25f1533febb72e9dbf65d11a7568a17d2e8ea2616019297846551c6a3248b0a23e91ac1f38b21878a28f828e8aeb19893478aa2ff2f16833d1b69fbffe68b569afdd1980cdf6d8d4ff52d9e2708568db1a1b50847c8310e4d85dc73b59ee31a63bc894712f2d2214973c2741f4db4f3ca9a337e1f6c4ed3858370626b62e975a85e94b498f8c3c2073e6d6fbedb40e8a356e6d6c77c2b5e13ee52fafab4c8d369ce17a5c40deb98c98b60f433889e092d7da5e7e991b73c15127364d70a879b16ae774d65834fd0029c3a1239143b6398bb19ecda0328f39f39ade7a090b2c5c4e75e4922c50f858195c7fad64e4305d04dea5b85d4dd5a52ac4e60681c2337d3a2eb0b47745563f69352e1c17b08a3625f7ba530dc5a393238b6a2b92bebe6b94966537763ef66179b5c622ac068acfaf796ed4f4214d7fbb36eba5c9216cd5ee1d42132c459042063c71a1323eaacca0a94dc119145" "cef90f744d16226d7168dc9abf46551dbe25ce179e85bd44cf15374ee498f3f3f8fb5800c6cbfc427a834e3f7b3b6b6c7333c5ed46eb2a0c93e4eaaa6f95072221d7cc27d36ad53fd5fee1e65d91e37957a9d34901602d5f49799db3cb4e47e2c5bcfe36008ff0fbf166d9e541504aeed187251b80cc72804687f58b646ca3893e8c9e4340c9580a2008d268e07f7a0705bf062c6b1ebb3a62a4c961ad2f65ec9d44c67ad3a39117d2427d9c3d067df7c089bbc905b319b30d61d099265de1ff42a97540bd08a1ec79a4cef4f692bbe54ca6f95d6ecb82d3ad2316d6cfaf9a66a8b5e5f00847b55509cdd344ccc3fc640da87be6cd4ad8ab3e510b31831d3151b2aea6675c97767076360bcfe1b317c3786dca2e4b3e90818064abb319cca7bae051390063bc6a0a0a133187a60a6eb82162a5061fba5fe17f157e9e589ad83d2f1760f4055879445b0934c954622476c29c9c577c053c723786c8d25829db7a896c66eec594a6b798ed278a824550795b0904e154fc06ce8783a773a8919b624dab70f92000b832475b77db27d0b5bbc5578765adaeac6f61166094fe11603f37a41fa047156f2e57d80a47d110901d96e33b5247a587552e37b7a0712cec420a5680ee8e5550ce5d0996b235b8898d67126415184bc9a0ec172d9f78f595182400c010d905fa73b5a6fef2f722b7f9dc51b9d21d85ec554c9f32612fcdd89577c47b3cb5203132e76ed5a39af7e9cfa2c92369464e14f8333fc29fe7a662b9373011f0d4627c9ba7b0ab0c050d0e67c625c" "dc83a0e244dcfc7f5b58ceb0d1ca2f16349ad8b16a48dbbd63da41eb5d0732a13ce5a7ee7c9088739eec6d63e0a410fb53f83cc75915c0b6353a75fd2d219986ee35bd3991161fd054f0d39c2c9da696ec2968e801cfe726cd512ddcb6cc28af65b1f8e542d1ad6a6d76dd1582dda6af4f6c9363ad7117e0ea0102cffc1ba0d94dd8abdb5ac37ef9b444387bfac2b811479086e550ce3452f77461febec72ce35d06ec70b94779b794dab1a3fba727f364bd0a65e7255da20d77ac6b85ffee926a1c3c635366a4d5c8233b798e565752103c66d5e7f18f315f7fe2641dec5944e51e373f19fbe1b34dd00f4604a4f741a5d4a8c720bf4e51511fb3316951ea63c3129c4f6242a9014a78a050e633ea5bf85960fe340c54043d9bffb969f8abe458a8c9dd02e9416e0f3504a5bdbf6cd0b4013b4b548bbe59a23149a24296e0c326d69affa61a878baff7525bea12a4bacaee6c216de31e22e218a3bffc996eb7a3b8570caa06193b56452ab7f3430c758c3b447db98c7a1faeafffa497d938d9b952e3ab3f6774333a02742375e7e1dc39cee15313d69e8cad1a251274ecf48f273cb79c58aac657adc8d77f7cd1755ad9a2fd43b69cad9d2f8bd77695dac3c43d2469e4ab34e26c7debaf33eb2ca6cb7fd0a963a37b7dfd5304b9d5f0bc1ae0940bb40375001e9920d4956f4011f4f1263c3b7cb38afa1d8f7c8c188bd226ac3e23867f3989d76a402a9476756e03c6c3bc4e3ce78095125ee11e7b47347bab7a638b0088a3b18f23abae9ab2f94650a30e2" "9abdbba8ae9d9d03cf5b12ab23f5a6464547bb7078b91f533ea06541941483359a8562e709608e0c5d1da2c7206c5af49be0df87a3244903293bbcc121fd2e20ff909a90ed836f1822ee2b40530084f02bd9c42b350a4703851d197d9c465485112f1bbb21aff46daef510159a1f354e5fb7b11508a3ffe12577b40d3bc16631f8a79191745fe828303cbe5b6d9578cd80f736971e1f108f02039e0bbcc12b42e8860cea15cc18505c3e4242ef481930f3e2c4b64ccedb5b4d9837461efc7c48f8b1a6dae1041e696b99fd8c9108ac1fa9d975b4d5a740c4e5bab92004b7c91cb64e80a67aff2596c919b73d88943538e0996a775b88857187e9f97828f8661f89252cd0c5577b27151b5b0021f17937a9abbfd8ac3946fec79a4063af00802d54eb08461f951cdbcec92f593eeba457f381a7a98f313ba28d21d2574fc751449e1c3b497e09b90f8e1840e7a56159915d98b36647dcc15e1b335102074741f1dba46f0df9e7114ca29d02a7e4581fc45c48e6b31cb291760a05774fdfdc0448abe313ca496bd2d1f011f4706072d69eb0207b0289f5dbe4d1f73355b206ab3d5c777d1d9dd65281a0dcdf598569109e8fc3b56af94e4340929457d2c45d9a9bbc37741dc031136a11955a465e0baea8c11c06ae9321dedadc498570efc3191e67354f0cae6a763e84aaf74597dc1d329c81231546df2fd965d2ce0fa2026e0ca896d48bf8cff97e9e1fc5e035a13a1dce07810a9e87c21988d7e9bf19dd68379f346d232f83d776c36791ed1ede88f8bdc1b" "62e3e7857fddb802ef7771be6a2428b7bb7e419cd95042d7de60359365efec7397b4d7fd32a4d7e8b924930606e7adc49333809812635939f79a20eae6066fc494ad27aa5be989663ed12f9f1c82d092b7a4af546f6dd33ab862fe21cc45c2c7c58842360070e206ac341c26ef2f92cc7629d873a219ea1177ac6354e7192f4c3f3aedb580c322e1644c92b9882a96addd01a35371c07b6cd3d7e4e38d089559ee41bdaeaf81650dc263a69fffa6d2713d3a8ffcadde7601cd2a87c23187463d3f3305a36ea01743d2cd846cc5ac96c89241c86b3c38ab97f1ab7b9685e68260fc116b7d02db8cff929b871dc02379d203aea4160c6302a7bad3379ce2b77effb3f9eb37d7826181ac8f606e67026fac0f43e39c72a04a6278f89d16a6c14c6d6e3dab80e9089a83c7a370726fffd0a2e6a9a6a950fad60982eb28b638ebf2315932911b91e465f076e97aacad4c6e19ec46a8ba9e7a19fca03b7796cd6d8efe6d2fbbb96b3fd3f85d4622fef029819efb34abc28143faf10ba4879fa69d493908649f03853ea84bf7d5bb21c6c541edf0c0aa96347b4102cde3c27a58ba0788ac02cdba243a3f52e0ce4d682d41d432e632635cdce5be1542b6b6a8708e144a6acf80ab3ff5842ca2db90e9d75401cfc99746a0919ed81983d2171b4093b1b07e5e5c45992f657c892e91c16cc6017a66af6466ade21f4b378a6fea6a8e4bf000ee986bbc0a170467548e7f6e797381ee89fc431f7aa562110555dfa5c275523c202744541d51701d70a8f3006ddbdfa5f72" "9563bc0234d0b2759efb747633221706cfe73d47743ce6e6077943ef6d0801729e1301ff9bbf37f50667909f1cdc70f95040c841106ce566de5dded0fa485ea539978a88ca8618e566e9da4f2e215d544ee62accbe75dc17ea26962d78bcad516e6bff3152642e346444db494a909478bf6d80aec53f3ffb3311c6283711eb96fdbdd8e6d94c71cbfb9d7ddc7f092df5092199dfd822b98e21239bb8dd17f0c101909bd38d309bb5456232f5a1b731990a4cce847394fc40b859a8d89c7c02c388e7d6ad42bcf4818de33d696ed6d6ace4c23d51fc9d7d82d0602dbea094aa2db51d9aa8ef5c1f4803e40f6f5fae44da3c3c6ce9b1003d95300871353762062d1ad49a31cae73d569bf07d147a0c8d212e60b1be486df08bc353a2e3ca7337b83e3db43be03147114c229fd32fc2eea5f64d5d5d9848709ad7335dab3909c1232d93e76eac218e7e0497ad5b7b1ca8d9ad5447879b20dd370398eb8ce4bc6805064ccdaa6d8ed1e98e259b7654a75848705dbf2c3804b455a9e3dd2890f8d74f0e968dd050ee81af2f98fdfbe831c16dae6589b9b2a16965713b8fa52e5d2d4df504411ad9c14929e560a5f7e74e98d72f71223a5eee41a40d85c177183c510881950bebd3f0ac907fbc5a4efe70a60da6bdfb6870d7fcefe04fdfffd1492c5033ec79b8de002c41895ea6e84393db391b9692983c84148928ba0fae6b2ee3aed2289a9e053d47340b5faa4870fa632c1b81c516a58a049728f941f57bc34ad53c236d33dc2ab6a196e896968d0a2bf651889" "825b8f358ef4874b0e75e39331e513c506b29a61495e78722bb25475ec2ddcda0816ff634062a54721c9fb425ff286336e7036928cfac29216dd0eacd3e5328b6979f831dccf403e87ccfc4346f5743d972d5047f6055bd86c98b8fb720a3cc3f459750ddb870a845c1ff4bc3499b1c92b6e591eca7e94f1f8d2fa3c57fc97b573a738f7f55e3b6cc975a813ffb7f897930b8de8382c5883ebffba463ce72b0c50c721db403cef01d5be035730ac3c6f6a3f78681218656f397966753c04507e08a09f7176c3e37de40b9c7faaef1b675fd083c9cced4261dbd4a289f6aa0ba04964e1a6d328ef05786933d67d6da009aaac7d4a8ca31df5a15e3874eb9b288edf7d794e1abdf9e411c5bb87f7fb27f76bd62968bba4d53844e76487818ddd38620854debdced8930ead6b46f3bce6009683d3ffedfff0be83cd8727bbcbf428c761b79a3c06a7c2de7b99394030b51eeb954cfa3fa307a37881a8dcbcedf9549e2600b72f3665946d14071d9d22894020346466bfd2062e092f21e38e920609df77e3b8ec024334c9708a415d3408e22645f06cd6d805e8da2f4005000aed542aa995816bbbf32597d9025daea32fd07733e080188d6c5c7af4ce8b7bb25d7c""50e9f3cec80e86a8f9f6d4e78a40ee20fc3c83bbbd07020f0092cdac8ffc2d52c24166d78da8ec32ebc49f815264c5ab29ab84f3b44ba75c06b80aba2966a617830efb08fd3fdda831fedeb67b7d593c661538d422e1a9fe378acf51b0f2a07f34d84624e0b90af172e5976a237a7dea10f" "a7cbfd3203d1b4985a1af6c2d2300136226b2edf519fdd2b7b5e3fb5b0c70f2e3160305fe9dd0c09b98d522666e5100532f516bfe24d12d46b5decb4d4cbdd5fe9cd647006c1c7eba14a56262fa7a3b7b6d7b22032c1d444fe023d66b7f51004c6176f4c198a2998beab66ca70e1343187ae697e9fbfa6ca6443d617552e6b7bb73c59613ce0a7cab58545bb40636f54ccdf89c507098680f4486f821b2fb2c7baa182686b0b6f893fc9575df701196b14255b547b925387cacd5f4a762b1d4b7f713e7aebe4f75ed648b8666e60a4f8d92f752451d704e19aa102bb3dda418c80f3b4f395965ec36fd9474088ac213b38220df73c8159401ff87751bbe392e0aab031de59691a0a77ba2ab7cfbf4daf09fa4d7d61dc5b456dfdbf7a60eab671ed1f1a67fd58bceb34e981a2dc3c3bb8a7a14fc8443b47a123662d96b4df2c584856ba257f39749d51caa70b147d50c68d4aafe51ee195f1ccb99b7015de726b5f0e85bf37617138d2b24d1cbe985d8d1cbb40a52e4c57e20c799e2f5ffc0557be9d3e2bc5b99dde628c4dffd5c8704c78689e967bc870c0fec80c3c69a2453b052a46e142309fb21bcbdad7c6c5a67df409bfb9899ec58ff0973e1813f47ec6428e35a932c117b5dc70a8f5b1a9fa402d59fa45714b4bd79bc214d488939f997add26d13c147aa4d4239d8aa0e3c70994eb4a8debb7cf292b3ff59bc36f97a9acad107fcc556c24a309c4a15dab16a47a71f31324dcc8183fdaabe1fbd1cb3808c1c35c311ea51188759d4e1533d39a9547f" "04054e2ef994c97e213669f08db02702dd8b54154e7376f256dedc67fcd3dc48f5e0be91f1f88766415d203bb4bb11c4a0f6d0888e0c98d3b8519aab741b20ced0e02a5638e40ad2ffc301318a77e57787995acea46eb8ff7edb535036c3b3781d63a02bce56499cd03ae75ba6610ef27124da36dce85ad406c82e72a0319dcd6e05dbc66523be5015036de859af45be32c664c18ad712bf09d361769be3e568d5f51c943ec2c9f74077cb9f5757de92c643a2963d69c2cc3f010908e661f3a6ce202d50d72a436319bb2337ab1babd4f2cf1bffc3de25a09dfc5cffb31c7080c5473b4ff673fdae11e64cd492a784a106beb65bfc01f9b7b97384d877d9f4440b7434240e98656703edd66279f1bd5b7cfacc8a6b511f1db9060e813f2e37a8be5de25087b0520e7729a873e125d7cba84b93cdd333e8756630d9dc9e1815832c8dba1a3c51776948b184a916ae44694664192af75a616387f47319bcd5da1d94fce857c8e76c3438ae5c7c810310058558e01b01cfb5676f1a5a5d027bcd1ec62428a82b78fdc9dfe69ae9c0301f6f2dbf1475e1cd1804d05cb04583ae62efe63a6f1d20d5c5675f4822ddb8f6f6af3d639f56839b1993dc40223341c04d829849dea53aba7d0d2a2db0a89881a2ecee4f66698aef5ebdbb3c6d65ff03cc1a00b714112f0b111e7a97ded2abde97767e0ea6e19a04f96d708d419f457022ac21715ca86305b8d5e4f45d6382c7ce8d87a8f0f2f1a18134deb9a33b334bc04697479c4f438f5e58a62a1b22b49580fd46eb4" "946d07c505e9c778dc56524880e8fb565487da236bb1340d92dbe21516f40a05dc3cec3fa4a56bc93ce57e7be50ef2fb38c94790acb9702dbf2ed30d6b5cc1e0173ed4c19e2822e79e711a523ecdeb6742d90353c904876e66b30fba8975d35418f0ef3fc8e5621d8d243973addf756d1e4621618fcae42af188a22f47f0f8bd0e821c16c8ca2a15e35d855ccc5c9660ebd2fe8966e6b86326905267b80358328483d0045fc63af4edda4020ecba5853f005b9058dbb81092cc12ebb3205ade902cef207f783a3921225f3a8a108eccf02cc303b11a2a7db60c897f31480db900fb1a6e1ccd1ba0aa61214037e50d8eb1ac777fc4a467ff9b9ffcaf34fe721300067d33a25f9acd43888ba09cbd26e8b269fe84065b5c44fdf734545fe21689b838eec4a00860f654df33f87d0f115a6fc1ba4f0de641f06eb8a19d2e75aad7dddc6f00c8d598015541fc8bd22540b9bd3babbbf3e41212d35cfef1236edfa5746b733de738c60901b87bfc3a4c7d49eb16e7fbb7ab93083cab5c225f79ef03db6d490169b5ecd2791fef9045e017f9dac41dbaf841f050729c6adf789b8008a82e61c80cc4d06207dbfd6b2a9cdfb67ac26280fa9ecc298dac1878fac6188066b9d8637f772136edaa7f64fa491b0bb4775656f5f1a3135686205b8217a590c088cf448892e134a29ef4cc61bd76886663afb18ad504b204ea52ef61782ce9ba44fbf2e18e1d59302a1b69717375be70a295517b069d26e161c91ec3a1a782e38efa6ac867dbe488cfddcf8c200135b059a0" "da4b4dbadda9b742b906266a879da79da144eba455fa7cc5062d326996acdddec0eba8666b0e1e6c7116a1e5f04f1e94e5d85b77b2d35deb45402a589d46734810ba3a74414eb53181f75c2f0bad61d9f4aaeb94f30a1051f5ba2b2b30f1445bfe889da81e550449d863cd5af77d49d344b63666df8206bc04686ebdaee954da5f14692bc2bf1b4b01cd6b2bfad93dcc7e5c08a5059d047f6ffe96a17c828244b234a2abf28674b15d14b735956c0a9bd438183666d6926912358edea95ac5b1b6a53784f47819a3cfd4ddb9af8e74f30e06c30e218edda9eb8207dc7cd931d6e926af59f8238225dd037b47c7a4c8af558d981a7c9a7dbae3fb66345874b27cb229f1c82b841cac0cad018e8f75d0731d5a8ea0c4d530f575de7d39d77fffde64c9d1fd87b9af3759d8a275d5a1d95f1d2d0bee007544f5c39ecf4013c80cd89821f79af3979f23dfff87d093b85b892b93bec546c5eccabf41d04c65bb571543f2312ed5e3596ec5d6bf8e57e9854164d34b48ca0ca4044a526e038332348eb801a6ff342bf25750abbcfc27e7cb5e7b026db3743b210b91d1fb688c8f16d4e40203d39272f22b5bd0f796f0fa09c90*1*b48bda800b2b3665adca330cfc990283a604b08074521335437c0ed7f2a997069c88d620b638ee988edb3f6f32be1ccd01ffb14b66b2c213d31aad92b25f66f226f2793b5e554475ce8c1a7f9541ce66c594379303ce730fd77a6591c97f5bdc400ba7e8cbd496c188c2112208778ff9699674b117631d8f385ebe45ed91dd60a" "4a657ca39c11c135e426c03ce2219392f55c635c1736f31b1a7a892273b6d9e2867864606aa0244b82c8be1748123f0b8478baa9402521583f24ac86c11801fe340e64628e8840aee6a093b1bf25aa05c74d1c1dd8ec48321b34a53bf78347a59fa9ee394a60b845cfd4c2f5bc53541065f1c5a0d3953d9808b26ee51d17dc026ea97a2ffae213bb9818f3c4009480ac0d1774e6237546204339db20ab366a805ba8c34304070959a16639006ced72bc3ba6430ef7e5a10e9a969ee233efc23b2d99bd8d49c3615f0da372cb98e077829f07e112a5bf4357a3cdee0268bbee69d31fea1ac66564d4b1c7c303f9b41e2b23b3c7825d1ef93ae1ca1aed1607177bf92cdce38fc68325a652efd3791e922a196eba24e9816c52afeb1d84577b8a22125c1d90beb57cacff4b2a637061d69bf7f1f006d102ca2acb8471909689d36196ec300691ddb9369868f3fd577e463d8b74c7a8e95fe2fd2954136f9650f7301d4a91d9c41f647675d37c1663d4b5c50cfb175facf30598a9be1ecc2f33fd4ec7e1ecc7dffbb1180a5b224b4eb6d0e0af4ecad6cbcb2a26cb3365a723caa2eacf9404083a427d5e7e62e967875e53a8eaf4f5873627717ce802b6b66d627f3390b50c0c950dac739ab46fad66920de3fb8edb0ad0a3c93e7b3beeb90a26a1553aecf4d1f3b17b7f852cf5441bd626012ca14d8e4aa2c43ef6a272f9f6990672b2ead99d839617069117aa10f840c379fc62de5ebf5c82ed59a5a1f76b0fec724ea809411709d88fd2f986c35edf9a562e3fd" "bb13577e2ac78bb854768ab38850daf931c1b8cc3e6f3c244fb339d288348f88f792954e90b68d664b7f941b634aec4b2d54995ba08b999d32d007e85e7e0df4dc6022b0d6d7a23ac5bcbfb2dd6cdc300fd0e4c9b4403a53a67a1c8979774833ba4b8f338b1932424b8654e02ff039967bb43c3f0661bf22f638a4caef57d50acce63e472f1316fdb93e75218d630d958c1aef855a9a7bc54122a26ff94d78e74d48aff82a485f584b8acbea147666712d35a7167dc5f92ef4059e42c28ba66fbdccaafe71efc630b8ce7fd840bd2802c2d69a4b09a11cf17c9321d9ccfb1623bfaa89786df732b405e2cf118611e9ff153dd2db2df1953fdd888f023e74e23f3a5595b81456b6ffb33e91d65f08fc8eab545412b18be47d14ab77827073286a735187bed1b12fbed879969f7d06c53041a6bd79bf6c5260342480cdb50cb617c2b4111da501ea98f368320094c5353a36df520824ec52dd15e818bec43d80b537c0d809845645429ea4f7635528cb7b8149924053a76d3c05b0c31e5970eaa014708c64c902be5272513111a73e682ed9f473c87b964a4957934424bf957d1e86c6c90a967a8643eec2b65f08d4c91252cb9663a4e5aa4ad9180166ac633c0e5f5170656373489126e6be09e9e8bd6f226f0833bd392884dfce749d68ad51b1f0e0ef5fc5a8876e54558e191abcfc4632409547a8a5c46c2b546db07ba324b4d327ebe86f87dac27b64d6e0c8250019c1114a4f8fa39523dc3f5d597aa33af245ecca15ea8cbef7604eca5ed804ac4f57c12" "6e335763925b88128b7289566270a5d7d1602481647f74d71bc1eafd0913851bcf07047dfef51b41fc02215d136885e647001f9f47546e9ea6ba0beab1d8a276cf9b85d780c05d4031f55d35d54c56f7fceeae9d62c58e7e928e591c2d6b1d14391f829f3e30bda6132bc513227cfad357be2c6f045bad7be72d01ceccd059327a72ce044edd534a5ddf71831bf07ebe84806feb621a5b8d71f4a608878e5e5daf3f8b4b3eda75f74f03d1ae5aebd029f037f66253f542aa06cd6c29ac5ed27ecdc7641fb6d54c98e71491772944303d3b6be683ac44b7bda5d49209133ff564cee31912b8e024cf628e0719522b11eff2e32874818f9a0ebde427657558a72943d6eb25c4b9d523336f37453af157035a3bc5ffd13847a928450d4e01f2ce7ca51d456939363c3e5a69b0d25311682c7b266cf86d12b63dcd322be77594c7f929a77467566a8d86a7d2b583b95f76626244738251fa762e0b2825c7668d6dde8ac5579c1a06318e5c5a6b2b1bc93bce6cd4853c50b6662482549290b15500722e3d6772c7541e3c864291dcbed84496dcc9ff4dddc974aa8b17b7ccea56c856f24ee2277a391c3c0c2c5584111ed24fe64e478e3c4d22380b8183222570fa3c70d29230aa21fd21808baacfd41e2430fed7c3316235e6b4c2c3331ee36d9e5c94ddbd73b351897cab7ede8a7c417c753d8023cf46694acbc9aa6ca556da7de108005330704cf54b1ec7bf7df02e36cd736237316b3523bca0a53a2472e68d30d95b1eb49282b27530bc69cd154b7a4dce75d" "a3efc65c12ce45de7a63632d340fc61a1789129df1554813a15c9a6ad101c07363ba8d967b70ae1767f8927440678bab989dbe994922779c3c277055a35bf12d6909caba8a4b6bec7f49dd32426d858e53164c8db77bd1b9321b31e6c1ad1e92596bec4ad39d5b6944c7585a5ad0c6f83f64727a7f6397f784d865ba3b9c85343f3a2828a0e71d75f19036ea0f17e265750d6a01513be2bee0bd0a837996971b87305dafda12679bc118a1df188888396e10074254e4aeecb6801e00e8f3ade2889b65aba9e29d2d146001740116c893df1899175dbbf88ec175216df3d93a88fb6957adf64a3849e26194edb91188c0373fdf9be85a520c173817ccac3e4e9c88ce0bd9448be3f6cf3eb92b9337ecf2e63db5887e1113ee31529c373e83ec02012ddaa8812fa5c6b8be8febe29d0c286fe03832aee79018fdbaedd8bec03345c05faa1231ad148bf4531679738a537ec490bdcf78a0d9dd13e6988e360273c388b91006a66176c93caf3594cb098d5f4287a37d79b636eb566eaeb73ef76a4a480fad73caad3378d17a9395bf71c6c43f643b04b4f1773939329470e51053467b67ed8ac0807b8806d26d16f6f4fc15b3f3cc197d24ea26418cf970a5e7009bd871aff96be823fd80efe1adcaa882c168692b53bdb47effc666a1768d04d0d8bf199d36604e82b72fcce53e86d063c347aeecc79a846f8e12cdec679b857f85a75fe59a1338a411950459443b3fec6511dcc78d5bb6dc60accd6013400c0ef71f19d7713b37777a75e96d0d341d416c9cd94" "7e3c442f6ddb31daec66bd96ca31b01d2dfb99d312a651ba5ec1765354de39d7aa4bb096ce7edbd93829d8ee2b7e3ff364f5d87f653a541f033db6c3266a03046f8612ad8d56a1c78912c9774c86a8d7e2eaa7f3bb1033470789ac2c32bd3c2ba1269bb01b176b167688f8fbe1f6094c3e2736bdc1cb1733364011681be98047cdad7d998241e121e6508cfd665c42b30f22bc442f940b5c7d93659f59abcb17aab1f28a02d0b59239f148211c525dd209cb932c54f24fa8a9541f0eab28b4c8df80845058e71e5447959bfc7f7d28e15542523410bc162f566875ed6d9d4fba519000b8c5d90f894f2bc74dc8307e26d4e0a9b418487d7470fbd64e97e660a3038a10a26a80e7cca09a3280ce3c87d07befd6f65127096d6075a18f30906828cee1f8b968dd3247210041078cf6d28f05977e5c172a9ecd83167873881e0ffcc56615ad0d64b0189ed8d559e43cccb1e2f8805df7156cb11f5df9dfbc067fce9fb3ee3230e28edfcf98741b9883f9f0f42913cc2be1036a0590107c69a9fadd4c9fc39df872f0db664ea7172fd72e0ad756be95417487d0c2bb38061c52124dcb2545f15a5bfd39d950b5878a067945733d8b1dc37cb85dd9393c98b0751c83d8e848fd1bd3ad243f6a8af7a8cb8cda7e1dc05324fa3932423fea0428131646534e74398f1604146da26a615045ee49ae2df3c8fcd16da64672845a946de4c26c1417c534a2b62a408a8c30c2e4f73ee44571259b628249c9e3f65e7b8d22002a170e7e53dc7c4cdc0073491db2cd6de20cd" "df07501ff08378ac1cfe3ef479491f3fc475f8aa1fb188706c264e276da3e0399e2bc17cffd6ad0ff94d2d3b9a3b46e8c1472c41fc1c002daa76634f94b3bdf8560cb3241352c6f1be21fee70cd54a1d96e31d71ef99589b93e7ca8d026abcb4a4fbfc8c0f57d59a6d9e760f02fd0a569702da7f59da495c2dd7f92d60fb3220cd7932a032d40ed29deaa5fe971128c6503eb9d1029a23ed6dc4fd5e8c5cf0347841424d60a5a07a9781d08c85222cf7241d199609762488332a6eafbc08cec42c876da9bd3fa287bca12f71b6e33c4453afb970b425a45b9baa9aa69ebb3907e06e6610f100b00c86752b2c106c2e0b71963f1933d315ceef89132c7744149db0c28f62b3d7b43d570d1f5c40bf4b7470b3b8de30b0d756b8326542743f2fa5cf3eff226b6a658ecbe44dc9a0e59f073f999d8c3340ba30ecff6f2fa4f3815f0d4c665b5109ce8984971e5cbec806888c2acdf73d2a330de9e5133787aa4950d08759f4cfcb55ec8efb43d421cf3a9f601a096677eb95f61e352a9adae7c0b971fb455f170c7ed95329b699d6e93f024786507e2e0acbeffb452c26d8c041cb88316d09a08af54ec48451f9bb685a23910e97ac82bb41f19f6b42fa10cfb75f9fa8edd61653c14a27b51544e3fb28009aab76d060135df2d097fd4c2f2e63dba1192c648215fdd1dace4824d71e038e23184ede7f61baefd747aed93b9807d0b3b7b4f7cb9eb171d1ba241b19cf1c74781eaaaca99a458253777522dedcf3d1db6bd4eec4459e59ad635904201b5d91c77bb" "b6e91f00f5a6f29794b35afde3dcd850f08ac5da097549ded05159567e9f7a023e08e49253766c0e151852714987201e90df675368ee638a947b7e6dc20bedf60656971170afe2d453662685dc1ceef8436ca8071680d0346239b41a6825839e9d5af12f9574d51b4672c5fa7f84bac497c8ba5fad2c10fbffe5ee713090b903d7723cd28c1b189a47c6a9fe9a88d0881dd60d1970c6e8a6d812bbd089c10841e5ced1417bef41f400118fa990d157bca93267d407989de017bd48f0231d43b9487526072e2755461274b3f5bf27847dda36c652a2b1fdd3815fd4ab93863426b31ecd1e6a9094dd2ed0190f8138e650dd2174fcc6b6ab1b8b91cc8020f2dcbb14855e7dd0bc1b5a01f55f81c0476daf1684cc4e72a68327120730ae92c45ab4e447c4ee900d61f79681667eec61343e4eebdd65c5b38a1ba5e3478f4d2f59d184ec39aca445a0f6edaa6840f04bfc19acf23db4507609cbdb44514b36aa5ef4ffe46577b711d1028970916eae919f1b4913d5894a24117cd7cc1aa8965840865554ce663af470455c0f756c795fb29eec04b727b12f7f3796f572ca2ec1e8771a88f68999e16b2acb235a7d9146f85f2be5a034babc3bdde750eb7895396d4777c144aee517a07310dcc8c9ce0ead93abb7f1eb4e34ed5036361d682c97eac1ad7c8158035e40a713f0f2e6f6e677d4b11ecc97e101a5b48420435dd218846ae622b416faeba7e0003bbbece71c2aa046715173b408c8ab2888b0b5dc4c34683f83ba9a83795f86122e6d80597d3a952a44f" "5a1edb6f294a0ceebefc3cb54db814cf91fe450ed4c71d0b4091a1fc7474", "goodjob"}, {NULL} }; #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(dmg_password) * gws; outsize = sizeof(dmg_hash) * gws; settingsize = sizeof(dmg_salt); cracked_size = sizeof(*cracked) * gws; inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); cracked = mem_calloc(1, cracked_size); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", PLAINTEXT_LENGTH, (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(dmg_password), 0, db); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr; char *p; int headerver; int res; if (strncmp(ciphertext, "$dmg$", 5) != 0) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 5; /* skip over "$dmg$" marker */ if ((p = strtokm(ctcopy, "*")) == NULL) goto err; headerver = atoi(p); if (headerver == 2) { if ((p = strtokm(NULL, "*")) == NULL) /* salt len */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* ivlen */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (atoi(p) > 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* encrypted_keyblob_size */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 128) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* encrypted keyblob */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* chunk number */ goto err; if ((p = strtokm(NULL, "*")) == NULL) /* data_size */ goto err; if(!isdec(p)) goto err; res = atoi(p); if ((p = strtokm(NULL, "*")) == NULL) /* chunk */ goto err; if (hexlenl(p) != res*2) goto err; if (res > 8192) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* scp */ goto err; if(!isdec(p)) goto err; res = atoi(p); /* FIXME: which values are allowed here? */ if (res == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* zchunk */ goto err; if (strlen(p) != 4096 * 2) goto err; } } else if (headerver == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* salt len */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* len_wrapped_aes_key */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 296) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* wrapped_aes_key */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* len_hmac_sha1_key */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 300) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* hmac_sha1_key */ goto err; if (strlen(p) / 2 != res) goto err; } else goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 5; p = strtokm(ctcopy, "*"); cs.headerver = atoi(p); if (cs.headerver == 2) { p = strtokm(NULL, "*"); cs.saltlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.ivlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.ivlen; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.encrypted_keyblob_size = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.encrypted_keyblob_size; i++) cs.encrypted_keyblob[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.cno = atoi(p); p = strtokm(NULL, "*"); cs.data_size = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.data_size; i++) cs.chunk[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.scp = atoi(p); if (cs.scp == 1) { p = strtokm(NULL, "*"); for (i = 0; i < 4096; i++) cs.zchunk[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } if ((p = strtokm(NULL, "*"))) cs.iterations = atoi(p); else cs.iterations = 1000; } else { p = strtokm(NULL, "*"); cs.saltlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.len_wrapped_aes_key = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.len_wrapped_aes_key; i++) cs.wrapped_aes_key[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.len_hmac_sha1_key = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.len_hmac_sha1_key; i++) cs.wrapped_hmac_sha1_key[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; if ((p = strtokm(NULL, "*"))) cs.iterations = atoi(p); else cs.iterations = 1000; } if (cs.iterations == 0) cs.iterations = 1000; MEM_FREE(keeptr); return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, 20); currentsalt.length = 20; currentsalt.outlen = 32; currentsalt.iterations = cur_salt->iterations; currentsalt.skip_bytes = 0; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static int apple_des3_ede_unwrap_key1(const unsigned char *wrapped_key, const int wrapped_key_len, const unsigned char *decryptKey) { DES_key_schedule ks1, ks2, ks3; unsigned char TEMP1[sizeof(cur_salt->wrapped_hmac_sha1_key)]; unsigned char TEMP2[sizeof(cur_salt->wrapped_hmac_sha1_key)]; unsigned char IV[8] = { 0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05 }; int outlen, i; DES_set_key((DES_cblock*)(decryptKey + 0), &ks1); DES_set_key((DES_cblock*)(decryptKey + 8), &ks2); DES_set_key((DES_cblock*)(decryptKey + 16), &ks3); DES_ede3_cbc_encrypt(wrapped_key, TEMP1, wrapped_key_len, &ks1, &ks2, &ks3, (DES_cblock*)IV, DES_DECRYPT); outlen = check_pkcs_pad(TEMP1, wrapped_key_len, 8); if (outlen < 0) return 0; for (i = 0; i < outlen; i++) TEMP2[i] = TEMP1[outlen - i - 1]; outlen -= 8; DES_ede3_cbc_encrypt(TEMP2 + 8, TEMP1, outlen, &ks1, &ks2, &ks3, (DES_cblock*)TEMP2, DES_DECRYPT); outlen = check_pkcs_pad(TEMP1, outlen, 8); if (outlen < 0) return 0; return 1; } static int hash_plugin_check_hash(unsigned char *derived_key) { unsigned char hmacsha1_key_[20]; unsigned char aes_key_[32]; int ret = 0; if (cur_salt->headerver == 1) { if (apple_des3_ede_unwrap_key1(cur_salt->wrapped_aes_key, cur_salt->len_wrapped_aes_key, derived_key) && apple_des3_ede_unwrap_key1(cur_salt->wrapped_hmac_sha1_key, cur_salt->len_hmac_sha1_key, derived_key)) { return 1; } } else { DES_key_schedule ks1, ks2, ks3; unsigned char TEMP1[sizeof(cur_salt->wrapped_hmac_sha1_key)]; AES_KEY aes_decrypt_key; unsigned char outbuf[8192 + 1]; unsigned char outbuf2[4096 + 1]; unsigned char iv[20]; #ifdef DMG_DEBUG unsigned char *r; #endif const char nulls[8] = { 0 }; DES_set_key((DES_cblock*)(derived_key + 0), &ks1); DES_set_key((DES_cblock*)(derived_key + 8), &ks2); DES_set_key((DES_cblock*)(derived_key + 16), &ks3); memcpy(iv, cur_salt->iv, 8); DES_ede3_cbc_encrypt(cur_salt->encrypted_keyblob, TEMP1, cur_salt->encrypted_keyblob_size, &ks1, &ks2, &ks3, (DES_cblock*)iv, DES_DECRYPT); memcpy(aes_key_, TEMP1, 32); memcpy(hmacsha1_key_, TEMP1, 20); hmac_sha1(hmacsha1_key_, 20, (unsigned char*)&cur_salt->cno, 4, iv, 20); if (cur_salt->encrypted_keyblob_size == 48) AES_set_decrypt_key(aes_key_, 128, &aes_decrypt_key); else AES_set_decrypt_key(aes_key_, 128 * 2, &aes_decrypt_key); AES_cbc_encrypt(cur_salt->chunk, outbuf, cur_salt->data_size, &aes_decrypt_key, iv, AES_DECRYPT); /* 8 consecutive nulls */ if (memmem(outbuf, cur_salt->data_size, (void*)nulls, 8)) { #ifdef DMG_DEBUG if (!bench_running) fprintf(stderr, "NULLS found!\n\n"); #endif ret = 1; } /* These tests seem to be obsoleted by the 8xNULL test */ #ifdef DMG_DEBUG /* </plist> is a pretty generic signature for Apple */ if (memmem(outbuf, cur_salt->data_size, (void*)"</plist>", 8)) { if (!bench_running) fprintf(stderr, "</plist> found!\n\n"); ret = 1; } /* Journalled HFS+ */ if (memmem(outbuf, cur_salt->data_size, (void*)"jrnlhfs+", 8)) { if (!bench_running) fprintf(stderr, "jrnlhfs+ found!\n\n"); ret = 1; } /* Handle compressed DMG files, CMIYC 2012 and self-made samples. Is this test obsoleted by the </plist> one? */ if ((r = memmem(outbuf, cur_salt->data_size, (void*)"koly", 4))) { unsigned int *u32Version = (unsigned int *)(r + 4); if (HTONL(*u32Version) == 4) { if (!bench_running) fprintf(stderr, "koly found!\n\n"); ret = 1; } } /* Handle VileFault sample images */ if (memmem(outbuf, cur_salt->data_size, (void*)"EFI PART", 8)) { if (!bench_running) fprintf(stderr, "EFI PART found!\n\n"); ret = 1; } /* Apple is a good indication but it's short enough to produce false positives */ if (memmem(outbuf, cur_salt->data_size, (void*)"Apple", 5)) { if (!bench_running) fprintf(stderr, "Apple found!\n\n"); ret = 1; } #endif /* DMG_DEBUG */ /* Second buffer test. If present, *this* is the very first block of the DMG */ if (cur_salt->scp == 1) { int cno = 0; hmac_sha1(hmacsha1_key_, 20, (unsigned char*)&cno, 4, iv, 20); if (cur_salt->encrypted_keyblob_size == 48) AES_set_decrypt_key(aes_key_, 128, &aes_decrypt_key); else AES_set_decrypt_key(aes_key_, 128 * 2, &aes_decrypt_key); AES_cbc_encrypt(cur_salt->zchunk, outbuf2, 4096, &aes_decrypt_key, iv, AES_DECRYPT); /* 8 consecutive nulls */ if (memmem(outbuf2, 4096, (void*)nulls, 8)) { #ifdef DMG_DEBUG if (!bench_running) fprintf(stderr, "NULLS found in alternate block!\n\n"); #endif ret = 1; } #ifdef DMG_DEBUG /* This test seem to be obsoleted by the 8xNULL test */ if (memmem(outbuf2, 4096, (void*)"Press any key to reboot", 23)) { if (!bench_running) fprintf(stderr, "MS-DOS UDRW signature found in alternate block!\n\n"); ret = 1; } #endif /* DMG_DEBUG */ } #ifdef DMG_DEBUG /* Write block as hex, strings or raw to a file. */ if (ret && !bench_running) { #if DMG_DEBUG == 4 int fd; if ((fd = open("dmg.debug.main", O_RDWR | O_CREAT | O_TRUNC, 0660)) == -1) perror("open()"); else { #if FCNTL_LOCKS struct flock lock = { 0 }; lock.l_type = F_WRLCK; while (fcntl(fd, F_SETLKW, &lock)) { if (errno != EINTR) pexit("fcntl(F_WRLCK)"); } #elif OS_FLOCK while (flock(fd, LOCK_EX)) { if (errno != EINTR) pexit("flock(LOCK_EX)"); } #endif if ((write(fd, outbuf, cur_salt->data_size) == -1)) perror("write()"); if (cur_salt->scp == 1) if ((write(fd, outbuf2, 4096) == -1)) perror("write()"); if (close(fd)) perror("close"); } #endif #if DMG_DEBUG == 3 dump_stuff(outbuf, cur_salt->data_size); if (cur_salt->scp == 1) { fprintf(stderr, "2nd block:\n"); dump_stuff(outbuf2, 4096); } #endif #if DMG_DEBUG == 2 dump_text(outbuf, cur_salt->data_size); if (cur_salt->scp == 1) { fprintf(stderr, "2nd block:\n"); dump_text(outbuf2, 4096); } #endif } #endif /* DMG_DEBUG */ } return ret; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) if (hash_plugin_check_hash((unsigned char*)outbuffer[index].v) == 1) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_opencl_dmg = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef DMG_DEBUG FMT_NOT_EXACT | #endif #ifdef _OPENMP FMT_OMP | #endif FMT_CASE | FMT_8_BIT, { "iteration count", }, dmg_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
ConvolutionRules.h
// Copyright 2016-present, 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. #ifndef CONVOLUTIONRULES_H #define CONVOLUTIONRULES_H #include <cuda_runtime_api.h> #include <cuda.h> #include "RectangularRegions.h" #include "Metadata.h" #include <algorithm> // only supports 3D convolutions now, and will be modified in the future maybe. // coordinate exchange template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(SparseGrid<dimension> &inputGrid, SparseGrid<dimension> &outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize, const std::vector<Float3> &input_normal, std::vector<Float3> &output_normal) { EASY_FUNCTION(profiler::colors::Green100); //right hand coordinate, int index[6*8] = {0,1,2,3,4,5,6,7, 6,7,4,5,2,3,0,1, 2,3,6,7,0,1,4,5, 4,5,0,1,6,7,2,3, 1,5,3,7,0,4,2,6, 4,0,6,2,5,1,7,3}; Int outputStart = outputGrid.ctr; std::vector<Int> inputObservations = std::vector<Int>(inputGrid.mp.size()); // orientation is determined by the first one? RuleBook candidate_rules = std::vector<std::vector<Int>>(volume<dimension>(size)); for(int i = 0; i < volume<dimension>(size);i++) { candidate_rules[i].reserve(inputGrid.mp.size()); } for (auto const &inIter : inputGrid.mp) { auto outRegion = OutputRegionCalculator<dimension>( inIter.first, size, stride, outputSpatialSize); // printf("new output\r\n\r\n"); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(inIter.first); auto outIter = outputGrid.mp.find(j); if (outIter == outputGrid.mp.end()) { outIter = outputGrid.mp.insert(std::make_pair(j, outputGrid.ctr++)).first; inputObservations[outIter->second - outputStart ] = 0; output_normal.push_back(Float3(0,0,0)); } inputObservations[outIter->second - outputStart ]++; output_normal[outIter->second] += input_normal[inIter.second+inputGrid.ctr]; // find mapping based on // printf("output point: %d %d %d %d %d\r\n",j[0],j[1],j[2], rulesOffset, outIter->second); candidate_rules[rulesOffset].push_back(inIter.second + inputGrid.ctr); candidate_rules[rulesOffset].push_back(outIter->second); } } std::vector<Int> oriented_index = std::vector<Int>(outputGrid.ctr - outputStart ); for(int i = outputStart ; i < outputGrid.ctr; i++) { output_normal[i] /= inputObservations[i - outputStart ]; output_normal[i].normalize(); oriented_index[i - outputStart ] = OrientedFilter(output_normal[i]); } rules.resize(volume<dimension>(size)); // there might be some problems here // target: low level texture information && high level geometry information // minimize the rotation invariance for(int i = 0; i < candidate_rules.size();i++) { for(int k = 0; k < candidate_rules[i].size();k+=2) { int ori_index = index[oriented_index[candidate_rules[i][k+1] - outputStart ] * 8 + i]; #if 0 rules[i].push_back(candidate_rules[i][k]); rules[i].push_back(candidate_rules[i][k+1]); #else rules[ori_index].push_back(candidate_rules[i][k]); rules[ori_index].push_back(candidate_rules[i][k+1]); #endif } } } template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(SparseGrid<dimension> &inputGrid, SparseGrid<dimension> &outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { rules.resize(volume<dimension>(size)); for (auto const &inIter : inputGrid.mp) { auto outRegion = OutputRegionCalculator<dimension>( inIter.first, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(inIter.first); auto outIter = outputGrid.mp.find(j); if (outIter == outputGrid.mp.end()) { outIter = outputGrid.mp.insert(std::make_pair(j, outputGrid.ctr++)).first; } rules[rulesOffset].push_back(inIter.second + inputGrid.ctr); rules[rulesOffset].push_back(outIter->second); } } } // GPU #ifdef GPU_GRID // only supports 3D convolutions now, and will be modified in the future maybe. // coordinate exchange // maybe 3x3 is a better choice, but just a little slower, need to check in the future void dGenerateSpatialNewPoint (Int* d_prev_all_point, // size = num_active_point * dim Int* d_next_all_point, // size = num_active_point * maxi_sizec * dim long* d_size, long* d_stride, long* d_output_spatial_size, Int num_active_point, long maxi_sizec, Int ndim); template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(GPU_SparseGrid<dimension> &gpu_inputGrid, GPU_SparseGrid<dimension> &gpu_outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize, const std::vector<Float3> &input_normal, std::vector<Float3> &output_normal) { EASY_FUNCTION(profiler::colors::Green50); EASY_BLOCK("gen_outpoint"); Int nActiveInput = gpu_inputGrid.pHash->getCompactingSize(); rules.resize(volume<dimension>(size)); Int* in_points_flat = new Int[nActiveInput * dimension]; // size = nActiveInput * dimension gpuErrchk(cudaMemcpy(in_points_flat, gpu_inputGrid.pHash->getAllPoints(), sizeof(Int) * nActiveInput * dimension, cudaMemcpyDeviceToHost)); Point<dimension> p; Points<dimension> out_points; Ints out_index; EASY_BLOCK("transformat"); for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { out_points.push_back(j); } } EASY_END_BLOCK; EASY_END_BLOCK; EASY_BLOCK("insert retrieve"); gpu_outputGrid.pHash->insert_points(out_points); gpu_outputGrid.pHash->retrieve_points(out_points, out_index); EASY_END_BLOCK; EASY_BLOCK("Normal"); Int query_index = 0; //right hand coordinate, int index[6*8] = {0,1,2,3,4,5,6,7, 6,7,4,5,2,3,0,1, 2,3,6,7,0,1,4,5, 4,5,0,1,6,7,2,3, 1,5,3,7,0,4,2,6, 4,0,6,2,5,1,7,3}; std::vector<Int> inputObservations = std::vector<Int>(gpu_outputGrid.pHash->size); output_normal.resize(gpu_outputGrid.ctr + gpu_outputGrid.pHash->size); for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { inputObservations[out_index[query_index]]++; output_normal[gpu_outputGrid.ctr + out_index[query_index]] += input_normal[i + gpu_inputGrid.ctr]; query_index+=1; } } for(int k = 0; k < gpu_outputGrid.pHash->size;k++) { if(inputObservations[k] > 0) { output_normal[gpu_outputGrid.ctr + k] /= inputObservations[k]; } } EASY_END_BLOCK; EASY_BLOCK("query"); query_index = 0; for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(p); Int oriIndex = OrientedFilter(output_normal[gpu_outputGrid.ctr + out_index[query_index++]]); Int newRuleOffset = index[oriIndex * 8 + rulesOffset]; rules[newRuleOffset].push_back(i + gpu_inputGrid.ctr); rules[newRuleOffset].push_back(gpu_outputGrid.ctr + out_index[query_index++]); } } gpu_outputGrid.ctr += gpu_outputGrid.pHash->size; delete[] in_points_flat; EASY_END_BLOCK; } // utils to debug template <Int dimension> bool point_cmp(Point<dimension> a,Point<dimension> b) { for(Int i=0;i<dimension;i++) { if(a[i]<b[i])return true; if(a[i]>b[i])return false; } return false; } template <Int dimension> void point_sort(vector<Point<dimension>> &a) { sort(a.begin(),a.end(),point_cmp<dimension>); } // only support when size == stride case template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(GPU_SparseGrid<dimension> &gpu_inputGrid, GPU_SparseGrid<dimension> &gpu_outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { // Note that this is a special case for downscaling EASY_FUNCTION(profiler::colors::Green100); for(int i = 0; i < dimension; i++) { // printf("convolution kernel: %d %d %d\r\n", i,size[i], stride[i]); assert(size[i] == 2); assert(stride[i] == 2); } rules.resize(volume<dimension>(size)); Int nActiveInput = gpu_inputGrid.pHash->getCompactingSize(); Int* in_points_flat = new Int[nActiveInput * dimension]; // size = nActiveInput * dimension gpuErrchk(cudaMemcpy(in_points_flat, gpu_inputGrid.pHash->getAllPoints(), sizeof(Int) * nActiveInput * dimension, cudaMemcpyDeviceToHost)); // rewrite the rules generation part to get faster implementation Point<dimension> p; Points<dimension> out_points; Ints out_index; // note that this is a mapping from in_points to out_points for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { out_points.push_back(j); } } gpu_outputGrid.pHash->insert_points(out_points); gpu_outputGrid.pHash->retrieve_points(out_points, out_index); Int query_index = 0; for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(p); // printf("%d %d %d %d %d %d %d\r\n", p[0],p[1],p[2],j[0],j[1],j[2],rulesOffset); rules[rulesOffset].push_back(i + gpu_inputGrid.ctr); rules[rulesOffset].push_back(gpu_outputGrid.ctr + out_index[query_index++]); } } gpu_outputGrid.ctr += gpu_outputGrid.pHash->size; delete[] in_points_flat; } void d_Convolution_GenerateOutputRules(uint32_t * d_in_points, uint32_t * d_output_points, uint32_t * d_output_index, RuleBook &rules,Int num, Int dimension, Int filterSize, Int input_offset); at::Tensor FlatPoints(const at::Tensor &input_points); template <Int dimension> at::Tensor ResolutionBasedScatteringCuda(at::Tensor &points_lr, at::Tensor &points_hr, Int stride) { assert(dimension == points_lr.size(1)); int lr_point_num = points_lr.size(0); int hr_point_num = points_hr.size(0); GPU_SparseGrid<dimension> gpu_grid; at::Tensor point_lr_flat = FlatPoints(points_lr); at::Tensor point_hr_flat = FlatPoints(points_hr); at::Tensor point_hr_query = point_hr_flat / stride; at::Tensor hr2lr = torch::empty({hr_point_num}, at::CUDA(at_kINT)); gpu_grid.pHash->insert((uint32_t* )point_lr_flat.data<Int>(), lr_point_num); gpu_grid.pHash->retrieve((uint32_t* )point_hr_query.data<Int>(), (uint32_t* )hr2lr.data<Int>(),hr_point_num); return hr2lr; } template <Int dimension> void Convolution_InputSgToRulesAndOutputSg_FastDownSampleMode(GPU_SparseGrid<dimension> &gpu_inputGrid, GPU_SparseGrid<dimension> &gpu_outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { // Note that this is a special case for downscaling EASY_FUNCTION(profiler::colors::Green100); for(int i = 0; i < dimension; i++) { // printf("convolution kernel: %d %d %d\r\n", i,size[i], stride[i]); assert(size[i] == 2); assert(stride[i] == 2); } clock_t start,end; rules.resize(volume<dimension>(size)); Int nActiveInput = gpu_inputGrid.pHash->getCompactingSize(); at::Tensor d_in_points = at::empty({nActiveInput * dimension}, at::CUDA(at_kINT)); gpuErrchk(cudaMemcpy(d_in_points.data<Int>(), gpu_inputGrid.pHash->getAllPoints(), sizeof(Int) * nActiveInput * dimension, cudaMemcpyDeviceToDevice)); at::Tensor d_out_points = d_in_points / 2; at::Tensor d_results = at::empty({nActiveInput}, at::CUDA(at_kINT)); gpu_outputGrid.pHash->insert((uint32_t* )d_out_points.data<Int>(), nActiveInput); gpu_outputGrid.pHash->retrieve((uint32_t* )d_out_points.data<Int>(), (uint32_t* )d_results.data<Int>(),nActiveInput); d_results += gpu_outputGrid.ctr; d_Convolution_GenerateOutputRules((uint32_t* )d_in_points.data<Int>(),(uint32_t* )d_out_points.data<Int>(), (uint32_t* )d_results.data<Int>(), rules, nActiveInput, dimension, 2,gpu_inputGrid.ctr); gpu_outputGrid.ctr += gpu_outputGrid.pHash->size; #if 0 Int* in_points_flat = new Int[nActiveInput * dimension]; // size = nActiveInput * dimension gpuErrchk(cudaMemcpy(in_points_flat, gpu_inputGrid.pHash->getAllPoints(), sizeof(Int) * nActiveInput * dimension, cudaMemcpyDeviceToHost)); // generate output points // rewrite the rules generation part to get faster implementation Point<dimension> p; Points<dimension> out_points; Ints out_index; // note that this is a mapping from in_points to out_points for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { out_points.push_back(j); } } gpu_outputGrid.pHash->insert_points(out_points); gpu_outputGrid.pHash->retrieve_points(out_points, out_index); Int query_index = 0; for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(p); // printf("%d %d %d %d %d %d %d\r\n", p[0],p[1],p[2],j[0],j[1],j[2],rulesOffset); rules[rulesOffset].push_back(i + gpu_inputGrid.ctr); rules[rulesOffset].push_back(gpu_outputGrid.ctr + out_index[query_index++]); } } delete[] in_points_flat; #endif } #if 0 template <Int dimension> void Convolution_InputSgToRulesAndOutputSg(GPU_SparseGrid<dimension> &gpu_inputGrid, GPU_SparseGrid<dimension> &gpu_outputGrid, RuleBook &rules, long *size, long *stride, long *inputSpatialSize, long *outputSpatialSize) { EASY_FUNCTION(profiler::colors::Green100); EASY_BLOCK("GPU to CPU"); rules.resize(volume<dimension>(size)); Int nActiveInput = gpu_inputGrid.pHash->getCompactingSize(); Int* in_points_flat = new Int[nActiveInput * dimension]; // size = nActiveInput * dimension gpuErrchk(cudaMemcpy(in_points_flat, gpu_inputGrid.pHash->getAllPoints(), sizeof(Int) * nActiveInput * dimension, cudaMemcpyDeviceToHost)); Point<dimension> p; Points<dimension> out_points; EASY_END_BLOCK; // EASY_BLOCK("transformat"); // for (Int i = 0; i < nActiveInput; i++) { // for(Int k = 0; k < dimension; k++) { // p[k] = in_points_flat[i + k * nActiveInput]; // } // auto outRegion = OutputRegionCalculator<dimension>( // p, size, stride, outputSpatialSize); // for (auto j : outRegion) { // out_points.push_back(j); // } // } #ifdef NEW_SPTIAL_POINT EASY_BLOCK("new gen output"); // yet a more efficient way Int *d_prev_all_point=NULL; Int *d_next_all_point=NULL; long *d_size=NULL; long *d_stride=NULL; long *d_outputSpatialSize=NULL; d_prev_all_point=gpu_inputGrid.pHash->getAllPoints(); // small mem allocate gpuErrchk(cudaMalloc((void **)&d_size, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_size, size, sizeof(long) * dimension, cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc((void **)&d_stride, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_stride, stride, sizeof(long) * dimension, cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc((void **)&d_outputSpatialSize, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_outputSpatialSize, outputSpatialSize, sizeof(long) * dimension, cudaMemcpyHostToDevice)); // identify the output size long maxi_sizec=1; // Point<dimension> lb, ub,; for (Int i = 0; i < dimension; i++) { // lb[i] = std::max(0L, (input[i] - size[i] + stride[i]) / stride[i]); // ub[i] = std::min(outputSpatialSize[i] - 1, input[i] / stride[i]); maxi_sizec*= ( size[i] - stride[i]) / stride[i]+1; } gpuErrchk(cudaMalloc((void **)&d_next_all_point, sizeof(Int) * nActiveInput * maxi_sizec * dimension)); gpuErrchk(cudaMemset(d_next_all_point, 0, sizeof(Int) * nActiveInput * maxi_sizec * dimension)); dGenerateSpatialNewPoint( d_prev_all_point, // size = num_active_point * dim d_next_all_point, // size = num_active_point * maxi_sizec * dim d_size, d_stride, d_outputSpatialSize, nActiveInput, maxi_sizec, dimension); gpuErrchk( cudaDeviceSynchronize() ); EASY_END_BLOCK; /* EASY_BLOCK("GPU to CPU"); Int* tmp_outpoint=new Int[nActiveInput * maxi_sizec * dimension]; gpuErrchk(cudaMemcpy(tmp_outpoint, d_next_all_point, sizeof(Int) * nActiveInput * maxi_sizec * dimension, cudaMemcpyDeviceToHost)); gpuErrchk(cudaFree(d_next_all_point)); for (Int i = 0; i < nActiveInput; i++) { for (Int j = 0; j < maxi_sizec; j++) { for(Int k = 0; k < dimension; k++) { p[k] = tmp_outpoint[(i + k * nActiveInput)*maxi_sizec+j]; } out_points.push_back(p); } } delete tmp_outpoint; // can be more efficient here by modify porting issue: */ /* Int *d_prev_all_point=NULL; Int *d_next_all_point=NULL; long *d_size=NULL; long *d_stride=NULL; long *d_outputSpatialSize=NULL; gpuErrchk(cudaMalloc((void **)&d_prev_all_point, sizeof(Int) * nActiveInput * dimension)); gpuErrchk(cudaMemcpy(d_prev_all_point, in_points_flat, sizeof(Int) * nActiveInput * dimension, cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc((void **)&d_size, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_size, size, sizeof(long) * dimension, cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc((void **)&d_stride, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_stride, stride, sizeof(long) * dimension, cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc((void **)&d_outputSpatialSize, sizeof(long) * dimension)); gpuErrchk(cudaMemcpy(d_outputSpatialSize, outputSpatialSize, sizeof(long) * dimension, cudaMemcpyHostToDevice)); // output point mem size(upper bound) would be inactive* maxi_sizec long all_stride=1,maxi_sizec=1; for(Int k = 0; k < dimension; k++) { all_stride*=stride[k]; } // Point<dimension> lb, ub,; for (Int i = 0; i < dimension; i++) { // lb[i] = std::max(0L, (input[i] - size[i] + stride[i]) / stride[i]); // ub[i] = std::min(outputSpatialSize[i] - 1, input[i] / stride[i]); maxi_sizec*= ( size[i] - stride[i]) / stride[i]+1; } #ifdef PRINT_NEW_SPTIAL_POINT printf("maxi_sizec:%d",maxi_sizec); #endif gpuErrchk(cudaMalloc((void **)&d_next_all_point, sizeof(Int) * nActiveInput * maxi_sizec * dimension)); gpuErrchk(cudaMemset(d_next_all_point, 0, sizeof(Int) * nActiveInput * maxi_sizec * dimension)); EASY_END_BLOCK; EASY_BLOCK("new gen output"); dGenerateSpatialNewPoint( d_prev_all_point, // size = num_active_point * dim d_next_all_point, // size = num_active_point * maxi_sizec * dim d_size, d_stride, d_outputSpatialSize, nActiveInput, maxi_sizec, dimension); EASY_END_BLOCK; EASY_BLOCK("two ways portting"); gpuErrchk( cudaDeviceSynchronize() ); // FOR DEBUG Int* debug_outpoint=new Int[nActiveInput * maxi_sizec * dimension]; gpuErrchk(cudaMemcpy(debug_outpoint, d_next_all_point, sizeof(Int) * nActiveInput * maxi_sizec * dimension, cudaMemcpyDeviceToHost)); gpuErrchk(cudaFree(d_prev_all_point)); gpuErrchk(cudaFree(d_next_all_point)); vector<Point<dimension>> debug_outputpoint; // Point<dimension> p; for (Int i = 0; i < nActiveInput; i++) { for (Int j = 0; j < maxi_sizec; j++) { for(Int k = 0; k < dimension; k++) { p[k] = debug_outpoint[(i + k * nActiveInput)*maxi_sizec+j]; } debug_outputpoint.push_back(p); } } #ifdef PRINT_NEW_SPTIAL_POINT printf("\n%d %d\n",debug_outputpoint.size(),out_points.size()); #endif point_sort<dimension>(debug_outputpoint); point_sort<dimension>(out_points); for(Int i=0;i<min(debug_outputpoint.size(),out_points.size());i++) { if(debug_outputpoint[i]!=out_points[i]) { printf("two ways gen not same"); break; } #ifdef PRINT_NEW_SPTIAL_POINT if(i+1==min(debug_outputpoint.size(),out_points.size())) { printf("two ways gen the same"); } #endif } EASY_END_BLOCK; // cmp debug_outpoint and out_points // new transformate here // input gpumem all point() addr, outpoint addr, size, stride,outspsize,ndim, aactive EASY_END_BLOCK; EASY_END_BLOCK; */ #endif EASY_BLOCK("insert and retrieve"); // gpu_outputGrid.pHash->insert_points(out_points); // gpu_outputGrid.pHash->retrieve_points(out_points, out_index); gpu_outputGrid.pHash->insert((uint32_t*)d_next_all_point,nActiveInput * maxi_sizec); uint32_t *d_results = NULL; /* query results*/ // Allocate memory for results gpuErrchk(cudaMalloc((void**)&d_results, sizeof(uint32_t) * nActiveInput * maxi_sizec)); gpu_outputGrid.pHash->retrieve((uint32_t*)d_next_all_point,d_results,nActiveInput * maxi_sizec); Ints out_index; out_index.resize(nActiveInput * maxi_sizec); gpuErrchk(cudaMemcpy(out_index.data(), d_results, sizeof(uint32_t) * nActiveInput * maxi_sizec, cudaMemcpyDeviceToHost)); gpuErrchk(cudaFree(d_results)); gpuErrchk( cudaDeviceSynchronize() ); EASY_END_BLOCK; EASY_BLOCK("query"); // can also be more efficient, but it's more complex because of the struct rulebook vector Int query_index = 0; for (Int i = 0; i < nActiveInput; i++) { for(Int k = 0; k < dimension; k++) { p[k] = in_points_flat[i + k * nActiveInput]; } auto outRegion = OutputRegionCalculator<dimension>( p, size, stride, outputSpatialSize); for (auto j : outRegion) { auto inRegion = InputRegionCalculator<dimension>(j, size, stride); Int rulesOffset = inRegion.offset(p); rules[rulesOffset].push_back(i + gpu_inputGrid.ctr); rules[rulesOffset].push_back(gpu_outputGrid.ctr + out_index[query_index++]); } } gpu_outputGrid.ctr += gpu_outputGrid.pHash->size; delete[] in_points_flat; gpuErrchk(cudaFree(d_next_all_point)); EASY_END_BLOCK; } #endif #endif template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs( #ifdef GPU_GRID GPU_SparseGrids<dimension> &input_SGs, GPU_SparseGrids<dimension> &output_SGs, #else SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, #endif RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize, std::vector<Float3> &output_normal) { EASY_FUNCTION(profiler::colors::Green100); rules.clear(); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); Int output_nActive = 0; Int temp; for (Int i = 0; i < batchSize; i++) { auto &iSG = input_SGs[i]; auto &oSG = output_SGs[i]; oSG.ctr = output_nActive; Convolution_InputSgToRulesAndOutputSg<dimension>( iSG, oSG, rules, filterSize, filterStride, input_spatialSize, output_spatialSize); temp = output_nActive; output_nActive = oSG.ctr; oSG.ctr = temp; } // Debug: Print rulebook #ifdef PRINT_CONVOLUTION printf("Convolution rules:\n"); for (Int i = 0; i < (Int)rules.size(); i++) { for (Int j = 0; j < (Int)rules[i].size(); j+=2) { std::cout << "Offset: " << i << ", Rules: " << rules[i][j] << ", "<< rules[i][j+1] << std::endl; } std::cout << std::endl; } printf("output_nActive = %d\n", output_nActive); #endif return output_nActive; } #define DEBUG_FAST_CONV_RULES 0 template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs( #ifdef GPU_GRID GPU_SparseGrids<dimension> &input_SGs, GPU_SparseGrids<dimension> &output_SGs, #else SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, #endif RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize, const std::vector<Float3> &input_normal, std::vector<Float3> &output_normal, int normal_guide_scale) { output_normal.clear(); rules.clear(); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); // Int input_points = 0; Int output_nActive = 0; Int temp; #if DEBUG_FAST_CONV_RULES RuleBook newRules; newRules.clear(); #endif for (Int i = 0; i < batchSize; i++) { auto &iSG = input_SGs[i]; auto &oSG = output_SGs[i]; oSG.ctr = output_nActive; if(input_normal.empty() || input_spatialSize[0] < normal_guide_scale) { #if DEBUG_FAST_CONV_RULES cudaDeviceSynchronize(); clock_t start,end; double time_gt,time_fast; start = clock(); #endif Convolution_InputSgToRulesAndOutputSg_FastDownSampleMode<dimension>( iSG, oSG, rules, filterSize, filterStride, input_spatialSize, output_spatialSize); #if DEBUG_FAST_CONV_RULES end = clock(); time_gt = (double) (end-start) / CLOCKS_PER_SEC * 1000.0; start = clock(); GPU_SparseGrid<dimension> output_SG; output_SG.ctr = output_nActive; printf("input ctr: %d %d\r\n", iSG.ctr, output_SG.ctr); Convolution_InputSgToRulesAndOutputSg<dimension>( iSG, output_SG, newRules, filterSize, filterStride, input_spatialSize, output_spatialSize); cudaDeviceSynchronize(); end = clock(); time_fast = (double) (end-start) / CLOCKS_PER_SEC * 1000.0; printf("timing: %f %f\r\n", time_gt, time_fast); for(int i = 0; i < rules.size();i++) { printf("%d %d\r\n",newRules[i].size(), rules[i].size()); for(int j = 0; j < rules[i].size();j+=2) { if(newRules[i][j] != rules[i][j] || newRules[i][j+1] != rules[i][j+1]) { printf("%d %d %d %d %d %d\r\n",i,j,newRules[i][j], newRules[i][j+1],rules[i][j],rules[i][j+1]); exit(0); } } } printf("pass verification!\r\n"); #endif } else { // printf("normal guide scale : %d\r\n", input_spatialSize[0]); Convolution_InputSgToRulesAndOutputSg<dimension>( iSG, oSG, rules, filterSize, filterStride, input_spatialSize, output_spatialSize, input_normal, output_normal); } temp = output_nActive; output_nActive = oSG.ctr; oSG.ctr = temp; } // Debug: Print rulebook #ifdef PRINT_CONVOLUTION printf("Convolution rules with normal:\n"); for (Int i = 0; i < (Int)rules.size(); i++) { for (Int j = 0; j < (Int)rules[i].size(); j+=2) { std::cout << "Offset: " << i << ", Rules: " << rules[i][j] << ", "<< rules[i][j+1] << std::endl; } std::cout << std::endl; } printf("output_nActive = %d\n", output_nActive); #endif return output_nActive; } template <Int dimension> Int Convolution_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, SparseGrids<dimension> &output_SGs, RuleBook &rules, long *filterSize, long *filterStride, long *input_spatialSize, long *output_spatialSize) { rules.clear(); rules.resize(volume<dimension>(filterSize)); output_SGs.clear(); Int batchSize = input_SGs.size(); output_SGs.resize(batchSize); std::vector<RuleBook> rbs(batchSize); { Int i; #pragma omp parallel for private(i) for (i = 0; i < batchSize; i++) Convolution_InputSgToRulesAndOutputSg<dimension>( input_SGs[i], output_SGs[i], rbs[i], filterSize, filterStride, input_spatialSize, output_spatialSize); } Int output_nActive = 0; for (Int i = 0; i < batchSize; i++) { // Parallel assignment: // output_nActive <- output_nActive+output_SGs[i].ctr // output_SGs[i].ctr <- output_nActive Int tmp = output_nActive; output_nActive += output_SGs[i].ctr; output_SGs[i].ctr = tmp; } { Int i; #pragma omp parallel for private(i) for (i = 0; i < (Int)rules.size(); i++) { auto &R = rules[i]; for (Int j = 0; j < batchSize; j++) { auto &r = rbs[j][i]; auto offset = output_SGs[j].ctr; for (Int k = 0; k < (Int)r.size();) { R.push_back(r[k++]); R.push_back(r[k++] + offset); } } } } return output_nActive; } // for each active site, list of (inputFeatureNumber,batchIdx, spatialOffset) // triples template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); for (Int batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } template <Int dimension> void SparseToDense_InputSgsToRulesAndOutputSgs_OMP( SparseGrids<dimension> &input_SGs, RuleBook &rules, long *spatialSize) { Int batchSize = input_SGs.size(); rules.clear(); rules.resize(batchSize); Point<dimension> lb, ub; for (Int i = 0; i < dimension; ++i) { lb[i] = 0; ub[i] = spatialSize[i] - 1; } auto region = RectangularRegion<dimension>(lb, ub); Int batchIdx; #pragma omp parallel for private(batchIdx) for (batchIdx = 0; batchIdx < batchSize; batchIdx++) { auto &iSG = input_SGs[batchIdx]; for (auto const &inIter : iSG.mp) { rules[batchIdx].push_back(inIter.second + iSG.ctr); rules[batchIdx].push_back(region.offset(inIter.first)); } } } #endif /* CONVOLUTIONRULES_H */
GB_binop__pow_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__pow_int32 // A.*B function (eWiseMult): GB_AemultB__pow_int32 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__pow_int32 // C+=b function (dense accum): GB_Cdense_accumb__pow_int32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__pow_int32 // C=scalar+B GB_bind1st__pow_int32 // C=scalar+B' GB_bind1st_tran__pow_int32 // C=A+scalar GB_bind2nd__pow_int32 // C=A'+scalar GB_bind2nd_tran__pow_int32 // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = GB_pow_int32 (aij, bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_pow_int32 (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_POW || GxB_NO_INT32 || GxB_NO_POW_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__pow_int32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__pow_int32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__pow_int32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *GB_RESTRICT Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__pow_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__pow_int32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__pow_int32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t bij = Bx [p] ; Cx [p] = GB_pow_int32 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__pow_int32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int32_t aij = Ax [p] ; Cx [p] = GB_pow_int32 (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_pow_int32 (x, aij) ; \ } GrB_Info GB_bind1st_tran__pow_int32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_pow_int32 (aij, y) ; \ } GrB_Info GB_bind2nd_tran__pow_int32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
thread_local_buffer_pool.h
/* * Buffer which provides concurrent access to its underlying container, without the need of synchronization for * every insert. Each thread stores data to its own, smaller buffer, which is later copied to the shared thread_safe_buffer. */ #ifndef MAXFLOW_THREAD_LOCAL_BUFFER_POOL_H #define MAXFLOW_THREAD_LOCAL_BUFFER_POOL_H #include <vector> #include "thread_safe_buffer.h" #ifndef CACHE_LINE_SIZE #define CACHE_LINE_SIZE 64 #endif namespace data_structures { template <typename T> class thread_local_buffer_pool { struct alignas (CACHE_LINE_SIZE) aligned_vector { std::vector<T> data; }; thread_safe_buffer<T> _buffer; std::unique_ptr<aligned_vector[]> _pool; const std::size_t _thread_count; public: thread_local_buffer_pool ( std::size_t thread_count, std::size_t total_max_size ) : _buffer ( total_max_size ), _pool ( std::make_unique<aligned_vector[]> ( thread_count ) ), _thread_count ( thread_count ) { for ( std::size_t i = 0; i < _thread_count; ++i ) _pool[i] . data . reserve ( std::max ( 1ul << 4, total_max_size / _thread_count ) ); } void push_back ( const T & value, std::size_t thread_id ) noexcept { auto & target_buffer = _pool[thread_id] . data; if ( target_buffer . size () == target_buffer . capacity () ) { _buffer . append ( target_buffer . data (), target_buffer . size () ); target_buffer . clear (); } _pool[thread_id] . data . push_back ( value ); } bool empty ( ) const noexcept { if ( !_buffer . empty () ) return false; for ( std::size_t i = 0; i < _thread_count; ++i ) if ( !_pool[i] . data . empty () ) return false; return true; } auto swap_data ( std::unique_ptr<T[]> & other ) noexcept { #pragma omp parallel for schedule(static) for ( std::size_t i = 0; i < _thread_count; ++i ) { auto & target_buffer = _pool[i] . data; if ( target_buffer . size () > 0 ) _buffer . append ( target_buffer . data (), target_buffer . size () ); target_buffer . clear (); } auto prev_size = _buffer . size (); _buffer . swap_data ( other ); return prev_size; } }; } #endif //MAXFLOW_THREAD_LOCAL_BUFFER_POOL_H
GB_subassign_02.c
//------------------------------------------------------------------------------ // GB_subassign_02: C(I,J) = A ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Method 02: C(I,J) = A ; using S // M: NULL // Mask_comp: false // C_replace: false // accum: NULL // A: matrix // S: constructed #define GB_FREE_WORK GB_FREE_TWO_SLICE #include "GB_subassign_methods.h" GrB_Info GB_subassign_02 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix A, const GrB_Matrix S, GB_Context Context ) { //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_GET_C ; GB_GET_A ; GB_GET_S ; GrB_BinaryOp accum = NULL ; //-------------------------------------------------------------------------- // Method 02: C(I,J) = A ; using S //-------------------------------------------------------------------------- // Time: Optimal. All entries in A+S must be examined, so the work is // Omega (nnz(A)+nnz(S)). // Method 02 and Method 04 are somewhat similar. They differ on how C is // modified when the entry is present in S but not A. //-------------------------------------------------------------------------- // Parallel: Z=A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20) //-------------------------------------------------------------------------- GB_SUBASSIGN_TWO_SLICE (A, S) ; //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_TASK_DESCRIPTOR_PHASE1 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get A(:,j) and S(:,j) //------------------------------------------------------------------ int64_t j = (Zh == NULL) ? k : Zh [k] ; GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ; GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ; //------------------------------------------------------------------ // do a 2-way merge of S(:,j) and A(:,j) //------------------------------------------------------------------ // jC = J [j] ; or J is a colon expression // int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = Si [pS] ; int64_t iA = Ai [pA] ; if (iS < iA) { // ----[C . 1] or [X . 1]----------------------------------- // S (i,j) is present but A (i,j) is not // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still a zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } else if (iA < iS) { // ----[. A 1]---------------------------------------------- // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) task_pending++ ; GB_NEXT (A) ; } else { // ----[C A 1] or [X A 1]----------------------------------- // both S (i,j) and A (i,j) present // [C A 1]: action: ( =A ): copy A into C, no accum // [X A 1]: action: ( undelete ): zombie lives GB_C_S_LOOKUP ; GB_noaccum_C_A_1_matrix ; GB_NEXT (S) ; GB_NEXT (A) ; } } // while list S (:,j) has entries. List A (:,j) exhausted. while (pS < pS_end) { // ----[C . 1] or [X . 1]--------------------------------------- // S (i,j) is present but A (i,j) is not // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still a zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } // List A (:,j) has entries. List S (:,j) exhausted. task_pending += (pA_end - pA) ; } GB_PHASE1_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_TASK_DESCRIPTOR_PHASE2 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get A(:,j) and S(:,j) //------------------------------------------------------------------ int64_t j = (Zh == NULL) ? k : Zh [k] ; GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ; GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ; //------------------------------------------------------------------ // do a 2-way merge of S(:,j) and A(:,j) //------------------------------------------------------------------ // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = Si [pS] ; int64_t iA = Ai [pA] ; if (iS < iA) { GB_NEXT (S) ; } else if (iA < iS) { // ----[. A 1]---------------------------------------------- // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; GB_NEXT (A) ; } else { GB_NEXT (S) ; GB_NEXT (A) ; } } // while list A (:,j) has entries. List S (:,j) exhausted. while (pA < pA_end) { // ----[. A 1]-------------------------------------------------- // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) int64_t iA = Ai [pA] ; int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; GB_NEXT (A) ; } } GB_PHASE2_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
vorticities.c
/* This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license. Github repository: https://github.com/OpenNWP/GAME */ /* Here, vorticities are calculated. The word "vorticity" hereby refers to both vertical and tangential components. */ #include <stdio.h> #include "../game_types.h" #include "geos95.h" #include "../thermodynamics/thermodynamics.h" #include "spatial_operators.h" int calc_rel_vort_on_triangles(Vector_field, double [], Grid *, Dualgrid *); int calc_pot_vort(Vector_field velocity_field, Scalar_field density_field, Diagnostics *diagnostics, Grid *grid, Dualgrid *dualgrid) { // It is called "potential vorticity", but it is not Ertel's potential vorticity. It is the absolute vorticity divided by the density. calc_rel_vort(velocity_field, diagnostics, grid, dualgrid); // pot_vort is a misuse of name here add_f_to_rel_vort(diagnostics -> rel_vort, diagnostics -> pot_vort, dualgrid); int layer_index, h_index, edge_vector_index_h, upper_from_index, upper_to_index; double density_value; // determining the density value by which we need to divide #pragma omp parallel for private (layer_index, h_index, edge_vector_index_h, upper_from_index, upper_to_index, density_value) for (int i = 0; i < NO_OF_LAYERS*2*NO_OF_VECTORS_H + NO_OF_VECTORS_H; ++i) { layer_index = i/(2*NO_OF_VECTORS_H); h_index = i - layer_index*2*NO_OF_VECTORS_H; // interpolation of the density to the center of the rhombus if (h_index >= NO_OF_VECTORS_H) { edge_vector_index_h = h_index - NO_OF_VECTORS_H; density_value = 0; for (int j = 0; j < 4; ++j) { density_value += grid -> density_to_rhombi_weights[4*edge_vector_index_h + j] *density_field[layer_index*NO_OF_SCALARS_H + grid -> density_to_rhombi_indices[4*edge_vector_index_h + j]]; } } // interpolation of the density to the half level edges else { // linear extrapolation to the TOA if (layer_index == 0) { density_value = 0.5*(density_field[grid -> from_index[h_index]] + density_field[grid -> to_index[h_index]]) // the gradient + (0.5*(density_field[grid -> from_index[h_index]] + density_field[grid -> to_index[h_index]]) - 0.5*(density_field[grid -> from_index[h_index] + NO_OF_SCALARS_H] + density_field[grid -> to_index[h_index] + NO_OF_SCALARS_H])) /(grid -> z_vector[NO_OF_SCALARS + h_index] - grid -> z_vector[NO_OF_SCALARS + NO_OF_VECTORS_PER_LAYER + h_index]) // delta z *(grid -> z_vector[0] - grid -> z_vector[NO_OF_SCALARS + h_index]); } // linear extrapolation to the surface else if (layer_index == NO_OF_LAYERS) { density_value = 0.5*(density_field[(layer_index - 1)*NO_OF_SCALARS_H + grid -> from_index[h_index]] + density_field[(layer_index - 1)*NO_OF_SCALARS_H + grid -> to_index[h_index]]) // the gradient + (0.5*(density_field[(layer_index - 2)*NO_OF_SCALARS_H + grid -> from_index[h_index]] + density_field[(layer_index - 2)*NO_OF_SCALARS_H + grid -> to_index[h_index]]) - 0.5*(density_field[(layer_index - 1)*NO_OF_SCALARS_H + grid -> from_index[h_index]] + density_field[(layer_index - 1)*NO_OF_SCALARS_H + grid -> to_index[h_index]])) /(grid -> z_vector[NO_OF_SCALARS + (layer_index - 2)*NO_OF_VECTORS_PER_LAYER + h_index] - grid -> z_vector[NO_OF_SCALARS + (layer_index - 1)*NO_OF_VECTORS_PER_LAYER + h_index]) // delta z *(0.5*(grid -> z_vector[layer_index*NO_OF_VECTORS_PER_LAYER + grid -> from_index[h_index]] + grid -> z_vector[layer_index*NO_OF_VECTORS_PER_LAYER + grid -> to_index[h_index]]) - grid -> z_vector[NO_OF_SCALARS + (layer_index - 1)*NO_OF_VECTORS_PER_LAYER + h_index]); } else { upper_from_index = (layer_index - 1)*NO_OF_SCALARS_H + grid -> from_index[h_index]; upper_to_index = (layer_index - 1)*NO_OF_SCALARS_H + grid -> to_index[h_index]; density_value = 0.25*(density_field[upper_from_index] + density_field[upper_to_index] + density_field[upper_from_index + NO_OF_SCALARS_H] + density_field[upper_to_index + NO_OF_SCALARS_H]); } } // division by the density to obtain the "potential vorticity" diagnostics -> pot_vort[i] = diagnostics -> pot_vort[i]/density_value; } return 0; } int add_f_to_rel_vort(Curl_field rel_vort, Curl_field out_field, Dualgrid *dualgrid) { /* adding the Coriolis parameter to the relative vorticity */ int layer_index, h_index; #pragma omp parallel for private(layer_index, h_index) for (int i = 0; i < NO_OF_LAYERS*2*NO_OF_VECTORS_H + NO_OF_VECTORS_H; ++i) { layer_index = i/(2*NO_OF_VECTORS_H); h_index = i - layer_index*2*NO_OF_VECTORS_H; out_field[i] = rel_vort[i] + dualgrid -> f_vec[h_index]; } return 0; } int calc_rel_vort(Vector_field velocity_field, Diagnostics *diagnostics, Grid *grid, Dualgrid *dualgrid) { /* This function averages the vorticities on triangles to rhombi and calculates horizontal (tangential) vorticities. */ // calling the function which computes the relative vorticity on triangles calc_rel_vort_on_triangles(velocity_field, diagnostics -> rel_vort_on_triangles, grid, dualgrid); int layer_index, h_index, index_0, index_1, index_2, index_3, base_index; double covar_0, covar_2; #pragma omp parallel for private(layer_index, h_index, index_0, index_1, index_2, index_3, covar_0, covar_2, base_index) for (int i = NO_OF_VECTORS_H; i < NO_OF_LAYERS*2*NO_OF_VECTORS_H + NO_OF_VECTORS_H; ++i) { layer_index = i/(2*NO_OF_VECTORS_H); h_index = i - layer_index*2*NO_OF_VECTORS_H; // rhombus vorticities (stand vertically) if (h_index >= NO_OF_VECTORS_H) { base_index = NO_OF_VECTORS_H + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER; diagnostics -> rel_vort[i] = ( dualgrid -> area[base_index + dualgrid -> from_index[h_index - NO_OF_VECTORS_H]] *diagnostics -> rel_vort_on_triangles[layer_index*NO_OF_DUAL_SCALARS_H + dualgrid -> from_index[h_index - NO_OF_VECTORS_H]] + dualgrid -> area[base_index + dualgrid -> to_index[h_index - NO_OF_VECTORS_H]] *diagnostics -> rel_vort_on_triangles[layer_index*NO_OF_DUAL_SCALARS_H + dualgrid -> to_index[h_index - NO_OF_VECTORS_H]])/( dualgrid -> area[base_index + dualgrid -> from_index[h_index - NO_OF_VECTORS_H]] + dualgrid -> area[base_index + dualgrid -> to_index[h_index - NO_OF_VECTORS_H]]); } // tangential (horizontal) vorticities else { base_index = layer_index*NO_OF_VECTORS_PER_LAYER; // At the lower boundary, w vanishes. Furthermore, the covariant velocity below the surface is also zero. if (layer_index == NO_OF_LAYERS) { index_2 = base_index - NO_OF_VECTORS_H + h_index; horizontal_covariant(velocity_field, layer_index - 1, h_index, grid, &covar_2); diagnostics -> rel_vort[i] = 1/dualgrid -> area[h_index + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER]*grid -> normal_distance[index_2]*covar_2; } else { index_0 = base_index + NO_OF_SCALARS_H + h_index; index_1 = base_index + grid -> from_index[h_index]; index_2 = base_index - NO_OF_VECTORS_H + h_index; index_3 = base_index + grid -> to_index[h_index]; horizontal_covariant(velocity_field, layer_index, h_index, grid, &covar_0); horizontal_covariant(velocity_field, layer_index - 1, h_index, grid, &covar_2); diagnostics -> rel_vort[i] = 1/dualgrid -> area[h_index + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER]*( - grid -> normal_distance[index_0]*covar_0 + grid -> normal_distance[index_1]*velocity_field[index_1] + grid -> normal_distance[index_2]*covar_2 - grid -> normal_distance[index_3]*velocity_field[index_3]); } } } // At the upper boundary, the tangential vorticity is assumed to have no vertical shear. #pragma omp parallel for for (int i = 0; i < NO_OF_VECTORS_H; ++i) { diagnostics -> rel_vort[i] = diagnostics -> rel_vort[i + 2*NO_OF_VECTORS_H]; } return 0; } int calc_rel_vort_on_triangles(Vector_field velocity_field, double result[], Grid *grid, Dualgrid * dualgrid) { /* This function calculates the vertical relative vorticity on triangles. */ int layer_index, h_index, vector_index, index_for_vertical_gradient; double velocity_value, length_rescale_factor, vertical_gradient, delta_z; // loop over all triangles #pragma omp parallel for private(layer_index, h_index, velocity_value, length_rescale_factor, vector_index, index_for_vertical_gradient, vertical_gradient, delta_z) for (int i = 0; i < NO_OF_DUAL_V_VECTORS; ++i) { layer_index = i/NO_OF_DUAL_SCALARS_H; h_index = i - layer_index*NO_OF_DUAL_SCALARS_H; // clearing what has previously been here result[i] = 0; // loop over the three edges of the triangle at hand for (int j = 0; j < 3; ++j) { vector_index = NO_OF_SCALARS_H + layer_index*NO_OF_VECTORS_PER_LAYER + dualgrid -> vorticity_indices_triangles[3*h_index + j]; velocity_value = velocity_field[vector_index]; // this corrects for terrain following coordinates length_rescale_factor = 1; if (layer_index >= NO_OF_LAYERS - grid -> no_of_oro_layers) { length_rescale_factor = (RADIUS + dualgrid -> z_vector[NO_OF_VECTORS_H + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER + h_index])/(RADIUS + grid -> z_vector[vector_index]); delta_z = dualgrid -> z_vector[NO_OF_VECTORS_H + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER + h_index] - grid -> z_vector[vector_index]; if (delta_z > 0) { index_for_vertical_gradient = vector_index - NO_OF_VECTORS_PER_LAYER; } else { if (layer_index == NO_OF_LAYERS - 1) { index_for_vertical_gradient = vector_index - NO_OF_VECTORS_PER_LAYER; } else { index_for_vertical_gradient = vector_index + NO_OF_VECTORS_PER_LAYER; } } vertical_gradient = (velocity_field[vector_index] - velocity_field[index_for_vertical_gradient])/(grid -> z_vector[vector_index] - grid -> z_vector[index_for_vertical_gradient]); // Here, the vertical interpolation is made. velocity_value += delta_z*vertical_gradient; } result[i] += length_rescale_factor*grid -> normal_distance[vector_index]*dualgrid -> vorticity_signs_triangles[3*h_index + j]*velocity_value; } // dividing by the area (Stokes' Theorem) result[i] = result[i]/dualgrid -> area[NO_OF_VECTORS_H + layer_index*NO_OF_DUAL_VECTORS_PER_LAYER + h_index]; } return 0; }
fixed_version.c
#include<stdio.h> int main(){ int sum = 1; int i =1; // increase sum by one each iteratiob using openmp #pragma omp parallel for firstprivate(i) reduction( + : sum ) for (i = i; i < 10; i++) { sum +=1; } }
sparse_create_mex.c
/* Copyright (c) 2012 by Marcin Krotkiewski, University of Oslo See ../License.txt for License Agreement. */ #include <libutils/config.h> #include "sparse_opts.h" #include <libutils/mtypes.h> #include <libutils/utils.h> #include <libutils/sorted_list.h> #include <libutils/memutils.h> #include <libutils/tictoc.h> #include <libutils/message_id.h> #include <libutils/parallel.h> #include <libmatlab/mesh.h> #define DYNAMIC_ALLOC_SIZE 1024 typedef struct { dimType dofi, dofj; } pair_t; typedef struct { dimType dofi, dofj; Double value; } triplet_t; INLINE void enumerate_elem_dofs_old(dimType n_node_dof, dimType n_elem_nodes, dimType iel, dimType *elems, dimType *dof_map, dimType *element_dofs) { dimType i, j; dimType dofi; size_t li; Uint ptr=0; for(i=0; i<n_elem_nodes; i++){ for(j=0; j<n_node_dof; j++){ li = (size_t)iel*n_elem_nodes+i; /* no int overflow: elems is assumed to be verified before */ dofi = elems[li] - ONE_BASED_INDEX; /* no int overflow: dofi must fit into dimType */ dofi = (size_t)n_node_dof*dofi+j; if(dof_map) dofi = dof_map[dofi] - ONE_BASED_INDEX; element_dofs[ptr++] = dofi; } } } INLINE void enumerate_elem_dofs(dimType n_node_dof, dimType n_elem_nodes, dimType *elems, dimType *dof_map, dimType *element_dofs) { dimType i, j; dimType dofi, nodei; Uint ptr=0; for(i=0; i<n_elem_nodes; i++){ nodei = elems[i] - ONE_BASED_INDEX; for(j=0; j<n_node_dof; j++){ /* no int overflow: dofi must fit into dimType */ dofi = n_node_dof*nodei+j; if(dof_map) dofi = dof_map[dofi] - ONE_BASED_INDEX; element_dofs[ptr++] = dofi; } } } void assemble_sparse_matrix(mwIndex *Ap, mwSize *Ai, Double *Ax, dimType row_start, dimType row_end, dimType n_row_entries, dimType *lists_static, Double *dlists_static, dimType *n_list_elems_static, dimType **lists_dynamic, Double **dlists_dynamic, dimType *n_list_elems_dynamic, dimType *list_size_dynamic, mwIndex nnz_shift) { /* This implementation first copies static list entries */ /* to the correct row, and then treats the row as a sorted list */ /* to add the dynamic entries, if any. */ dimType i; size_t li; dimType ptr; mwSize *rowptr = NULL; Double *rowptr_Ax = NULL; dimType *dynptr = NULL; Double *ddynptr = NULL; mwSize n_entries; mwSize Ap_elem; for(i=row_start; i<row_end; i++){ /* update the thread-local Ap vector */ Ap_elem = Ap[i] + nnz_shift; Ap[i] = Ap_elem; li = (size_t)i*n_row_entries; rowptr = Ai + Ap_elem; if(Ax) rowptr_Ax = Ax + Ap_elem; /* copy static entries first */ /* by hand - data type conversion */ n_entries = n_list_elems_static[i]; for(ptr=0; ptr<n_entries; ptr++){ rowptr[ptr] = lists_static[li+ptr]; } /* double is double... */ if(dlists_static) memcpy(rowptr_Ax, dlists_static+li, sizeof(Double)*n_entries); /* add dynamic entries as to a sorted list */ if(n_list_elems_dynamic[i]){ /* do we have Ax values as well? */ if(dlists_dynamic){ /* Assemble Ax and Ai values */ dynptr = lists_dynamic[i]; ddynptr = dlists_dynamic[i]; for(ptr=0; ptr<n_list_elems_dynamic[i]; ptr++){ sorted_list_add_static_accum_mwSize_Double(rowptr, &n_entries, dynptr[ptr], rowptr_Ax, ddynptr[ptr]); } mfree(lists_dynamic[i], sizeof(dimType)*(list_size_dynamic[i])); mfree(dlists_dynamic[i], sizeof(Double)*(list_size_dynamic[i])); } else { /* Symbolic matrix: only assemble Ai */ dynptr = lists_dynamic[i]; for(ptr=0; ptr<n_list_elems_dynamic[i]; ptr++){ sorted_list_add_static_mwSize(rowptr, &n_entries, dynptr[ptr]); } mfree(lists_dynamic[i], sizeof(dimType)*(list_size_dynamic[i])); } } } } /* Creates a symbolic sparse matrix (no Ax array) */ void sparse_matrix_create(dimType matrix_dim, dimType n_node_dof, dimType n_elem_dof, dimType n_elems, dimType n_elem_nodes, dimType *elems, mwIndex **Ap_out, mwSize **Ai_out, dimType symm, dimType n_row_entries, dimType *dof_map) { /* data accessible to all threads */ dimType **lists_dynamic = 0; dimType *n_list_elems_dynamic = 0; dimType *list_size_dynamic = 0; dimType *lists_static = 0; dimType *n_list_elems_static = 0; mwIndex nnz = 0; #ifdef USE_OPENMP pair_t **comm_entries = 0; dimType *comm_size = 0; dimType *n_comm_entries = 0; dimType *row_cpu_dist = 0; #endif /* USE_OPENMP */ /* allocate static row arrays first */ /* if we run out of space, allocate dynamic lists */ mmalloc(lists_dynamic, sizeof(dimType*)*matrix_dim); mmalloc(n_list_elems_dynamic, sizeof(dimType)*matrix_dim); mmalloc(list_size_dynamic, sizeof(dimType)*matrix_dim); /* allocate storage for dynamic row arrays */ mmalloc(lists_static, sizeof(dimType)*n_row_entries*matrix_dim); mmalloc(n_list_elems_static, sizeof(dimType)*matrix_dim); /* allocate output row pointer */ mmalloc_global((*Ap_out), sizeof(mwIndex)*(matrix_dim+1)); DMESSAGE("static memory usage (MB): %lli\n", DEBUG_MEMORY, (long long)get_total_memory_usage()/1024/1024); #ifdef USE_OPENMP #pragma omp parallel #endif /* USE_OPENMP */ { /* thread local variables */ Uint i, j; dimType iel; dimType dofi, dofj; dimType pos; size_t li; mwIndex nnz_shift = 0; dimType *element_dofs = alloca(n_elem_dof*sizeof(dimType)); Uint nthr, thrid; dimType row_start, row_end; dimType el_start, el_end; dimType *elems_local = NULL; dimType nonlocal = 0, dynamic = 0, chkstatic = 0; dimType block_size, n_elems_local; parallel_get_info(&thrid, &nthr); /* affinity_bind(thrid, thrid); */ DMESSAGE("nthr %"PRI_UINT", thrid %"PRI_UINT, DEBUG_DETAILED, nthr, thrid); /* data distribution - matrix rows */ block_size = matrix_dim/nthr+1; row_start = thrid*block_size; row_end = (thrid+1)*block_size; row_end = MIN(row_end, matrix_dim); /* data distribution - elements */ block_size = n_elems/nthr+1; el_start = thrid*block_size; el_end = (thrid+1)*block_size; el_end = MIN(el_end, n_elems); n_elems_local = el_end - el_start; /* zero-initialize arrays */ #ifdef USE_OPENMP #pragma omp single /* communication arrays, only used in parallel mode */ { mcalloc(comm_entries, sizeof(pair_t *)*nthr*nthr); mcalloc(comm_size, sizeof(dimType)*nthr*nthr); mcalloc(n_comm_entries, sizeof(dimType)*nthr*nthr); mmalloc(row_cpu_dist, sizeof(dimType)*nthr); } #pragma omp barrier row_cpu_dist[thrid] = row_end; #endif /* USE_OPENMP */ for(i=row_start; i<row_end; i++){ lists_dynamic[i] = NULL; n_list_elems_dynamic[i] = 0; list_size_dynamic[i] = 0; n_list_elems_static[i] = 0; } #ifdef USE_OPENMP #pragma omp barrier #pragma omp flush #endif /* USE_OPENMP */ /* adjust the local element pointer */ elems_local = elems + el_start*n_elem_nodes; /* element loop */ for(iel=0; iel<n_elems_local; iel++){ enumerate_elem_dofs(n_node_dof, n_elem_nodes, elems_local, dof_map, element_dofs); elems_local += n_elem_nodes; for(i=0; i<n_elem_dof; i++){ /* Note the dof traversal order for symmetric matrices */ for(j=i*symm; j<n_elem_dof; j++){ dofi = element_dofs[i]; dofj = element_dofs[j]; if(symm && dofi>dofj){ pos = dofj; dofj = dofi; dofi = pos; } /* handle local dofs using static lists */ if(row_start <= dofi && dofi < row_end){ /* local matrix part */ /* choose between the static and dynamic data structure */ if(n_list_elems_static){ chkstatic++; li = (size_t)dofi*n_row_entries; if(n_list_elems_static[dofi] < n_row_entries){ /* Add to static list since there is space */ /* Duplicate entry is not added to the list */ sorted_list_add_static_dimType(lists_static + li, n_list_elems_static + dofi, dofj); continue; } else { /* locate to see if we have it in the static list already */ pos = sorted_list_locate_dimType(lists_static + li, n_row_entries, dofj); if(pos<n_row_entries && lists_static[li + pos]==dofj) continue; } } dynamic++; /* dynamic data structure */ /* check if a given row has a dynamic list */ if(!list_size_dynamic[dofi]){ sorted_list_create(lists_dynamic + dofi, list_size_dynamic + dofi); } sorted_list_add(lists_dynamic + dofi, n_list_elems_dynamic + dofi, list_size_dynamic + dofi, dofj); } else { #ifdef USE_OPENMP /* non-local matrix part - only used in parallel mode */ nonlocal++; /* locate the cpu that owns this triplet */ pos = sorted_list_locate_dimType(row_cpu_dist, nthr, dofi); if(row_cpu_dist[pos]==dofi) pos++; /* add the triplet to the non-local list */ if(comm_size[pos*nthr+thrid]==n_comm_entries[pos*nthr+thrid]){ comm_size[pos*nthr+thrid] += DYNAMIC_ALLOC_SIZE; mrealloc(comm_entries[pos*nthr+thrid], sizeof(pair_t)*comm_size[pos*nthr+thrid], sizeof(pair_t)*DYNAMIC_ALLOC_SIZE); } comm_entries[pos*nthr+thrid][n_comm_entries[pos*nthr+thrid]].dofi = dofi; comm_entries[pos*nthr+thrid][n_comm_entries[pos*nthr+thrid]].dofj = dofj; n_comm_entries[pos*nthr+thrid]++; #endif /* USE_OPENMP */ } } } } #ifdef USE_OPENMP #pragma omp barrier #pragma omp flush /* handle communication - accumulate local triplets that have been found by other threads */ for(j=0; j<nthr; j++){ /* local data - no communication */ if(j==thrid) continue; for(i=0; i<n_comm_entries[thrid*nthr+j]; i++){ dofi = comm_entries[thrid*nthr+j][i].dofi; dofj = comm_entries[thrid*nthr+j][i].dofj; if(n_list_elems_static){ chkstatic++; li = (size_t)dofi*n_row_entries; if(n_list_elems_static[dofi] < n_row_entries){ /* Add to static list since there is space */ /* Duplicate entry is not added to the list */ sorted_list_add_static_dimType(lists_static + li, n_list_elems_static + dofi, dofj); continue; } else { /* locate to see if we have it in the static list already */ pos = sorted_list_locate_dimType(lists_static + li, n_row_entries, dofj); if(pos<n_row_entries && lists_static[li + pos]==dofj) continue; } } dynamic++; /* dynamic data structure */ /* check if a given row has a dynamic list */ if(!list_size_dynamic[dofi]){ sorted_list_create(lists_dynamic + dofi, list_size_dynamic + dofi); } sorted_list_add(lists_dynamic + dofi, n_list_elems_dynamic + dofi, list_size_dynamic + dofi, dofj); } mfree(comm_entries[thrid*nthr+j], sizeof(pair_t)*comm_size[thrid*nthr+j]); } #endif /* USE_OPENMP */ VERBOSE("thread %"PRI_UINT", list access: nonlocal %"PRI_DIMTYPE" dynamic %"PRI_DIMTYPE" static %"PRI_DIMTYPE, DEBUG_DETAILED, thrid, nonlocal, dynamic, chkstatic); /* Count a cumulative sum of the number of non-zeros in every matrix row. */ /* NOTE: Ap is here thread-local and needs to be further updated. */ /* Last iteration has to be unrolled to make sure we do not overwrite */ /* the first element of Ap of the next thread, which should be 0. */ (*Ap_out)[row_start] = 0; for(i=row_start; i<row_end-1; i++) { (*Ap_out)[i+1] = (*Ap_out)[i] + n_list_elems_static[i] + n_list_elems_dynamic[i]; } /* Execute in order: */ /* Determine the number of non-zeros in the 'earlier' part of the matrix (nnz_shift). */ /* This is later used to update the thread-local Ap row pointer vector */ /* into the final, assembled Ap vector. */ for(i=0; i<nthr; i++){ if(thrid==i){ #ifdef USE_OPENMP #pragma omp flush(nnz) #endif /* USE_OPENMP */ /* NOTE: nnz is a shared variable that is updated by all threads in order */ nnz_shift = nnz; nnz += (*Ap_out)[row_end-1] + n_list_elems_static[row_end-1] + n_list_elems_dynamic[row_end-1]; } #ifdef USE_OPENMP #pragma omp barrier #endif /* USE_OPENMP */ } #ifdef USE_OPENMP #pragma omp single #endif /* USE_OPENMP */ { (*Ap_out)[matrix_dim] = nnz; /* allocate row array */ mmalloc_global(*Ai_out, sizeof(mwSize)*nnz); DMESSAGE("maximum memory usage (MB): %lli\n", DEBUG_MEMORY, (long long)get_total_memory_usage()/1024/1024); } #ifdef USE_OPENMP #pragma omp barrier #endif /* USE_OPENMP */ /* create matrix rows */ assemble_sparse_matrix(*Ap_out, *Ai_out, NULL, row_start, row_end, n_row_entries, lists_static, NULL, n_list_elems_static, lists_dynamic, NULL, n_list_elems_dynamic, list_size_dynamic, nnz_shift); #ifdef USE_OPENMP #pragma omp single { mfree(comm_entries, sizeof(pair_t*)*nthr*nthr); mfree(comm_size, sizeof(dimType)*nthr*nthr); mfree(n_comm_entries, sizeof(dimType)*nthr*nthr); mfree(row_cpu_dist, sizeof(dimType)*nthr); } #endif /* USE_OPENMP */ } mfree(lists_static, sizeof(dimType)*n_row_entries*matrix_dim); mfree(n_list_elems_static, sizeof(dimType)*matrix_dim); mfree(lists_dynamic, sizeof(dimType*)*matrix_dim); mfree(n_list_elems_dynamic, sizeof(dimType)*(matrix_dim)); mfree(list_size_dynamic, sizeof(dimType)*matrix_dim); } /* Assembles the sparse matrix from element matrices and element list. */ void sparse_matrix_create_accum(dimType matrix_dim, dimType n_node_dof, dimType n_elem_dof, dimType n_elems, dimType n_elem_nodes, dimType *elems, Double *Aelems, dimType elem_matrices, mwIndex **Ap_out, mwSize **Ai_out, Double **Ax_out, dimType symm, dimType n_row_entries, dimType *dof_map) { dimType *lists_static = 0; Double *dlists_static = 0; dimType *n_list_elems_static = 0; dimType **lists_dynamic = 0; Double **dlists_dynamic = 0; dimType *n_list_elems_dynamic = 0; dimType *list_size_dynamic = 0; mwIndex nnz = 0; #ifdef USE_OPENMP triplet_t **comm_entries = 0; dimType *comm_size = 0; dimType *n_comm_entries = 0; dimType *row_cpu_dist = 0; #endif /* USE_OPENMP */ /* allocate static row arrays first */ /* if we run out of space, allocate dynamic lists */ mmalloc(lists_static, sizeof(dimType)*n_row_entries*matrix_dim); mmalloc(dlists_static, sizeof(Double)*n_row_entries*matrix_dim); mcalloc(n_list_elems_static, sizeof(dimType)*matrix_dim); /* allocate storage for dynamic row arrays */ mmalloc(lists_dynamic, sizeof(dimType*)*matrix_dim); mmalloc(dlists_dynamic, sizeof(Double*)*matrix_dim); mcalloc(list_size_dynamic, sizeof(dimType)*matrix_dim); mcalloc(n_list_elems_dynamic, sizeof(dimType)*matrix_dim); /* allocate output row pointer */ mmalloc_global((*Ap_out), sizeof(mwIndex)*(matrix_dim+1)); DMESSAGE("static memory usage (MB): %lli\n", DEBUG_MEMORY, (long long)get_total_memory_usage()/1024/1024); #ifdef USE_OPENMP #pragma omp parallel #endif { /* thread local variables */ Uint i, j; dimType iel; dimType dofi, dofj; dimType pos; size_t li; mwIndex nnz_shift = 0; dimType *element_dofs = alloca(n_elem_dof*sizeof(dimType)); Uint nthr, thrid; dimType row_start, row_end; dimType el_start, el_end; dimType *elems_local = NULL; dimType nonlocal = 0, dynamic = 0, chkstatic = 0; dimType block_size, n_elems_local; Double Avalue, *Aelems_ptr = NULL; parallel_get_info(&thrid, &nthr); /* affinity_bind(thrid, thrid); */ DMESSAGE("nthr %"PRI_UINT", thrid %"PRI_UINT, DEBUG_DETAILED, nthr, thrid); /* data distribution - matrix rows */ block_size = matrix_dim/nthr+1; row_start = thrid*block_size; row_end = (thrid+1)*block_size; row_end = MIN(row_end, matrix_dim); /* data distribution - elements */ block_size = n_elems/nthr+1; el_start = thrid*block_size; el_end = (thrid+1)*block_size; el_end = MIN(el_end, n_elems); n_elems_local = el_end - el_start; /* zero-initialize arrays */ #ifdef USE_OPENMP #pragma omp single /* communication arrays, only used in parallel mode */ { mcalloc(comm_entries, sizeof(triplet_t*)*nthr*nthr); mcalloc(comm_size, sizeof(dimType)*nthr*nthr); mcalloc(n_comm_entries, sizeof(dimType)*nthr*nthr); mmalloc(row_cpu_dist, sizeof(dimType)*nthr); } #pragma omp barrier row_cpu_dist[thrid] = row_end; #endif /* USE_OPENMP */ for(i=row_start; i<row_end; i++){ lists_dynamic[i] = NULL; dlists_dynamic[i] = NULL; n_list_elems_dynamic[i] = 0; list_size_dynamic[i] = 0; n_list_elems_static[i] = 0; } #ifdef USE_OPENMP #pragma omp barrier #pragma omp flush #endif /* USE_OPENMP */ /* adjust the local element pointer */ elems_local = elems + el_start*n_elem_nodes; if(symm){ Aelems_ptr = Aelems + (size_t)el_start*n_elem_dof*(n_elem_dof+1)/2; } else { Aelems_ptr = Aelems + (size_t)el_start*n_elem_dof*n_elem_dof; } /* element loop */ for(iel=0; iel<n_elems_local; iel++){ /* using the same element matrix for all elements */ if(!elem_matrices) Aelems_ptr = Aelems; /* enumerate elems dofs */ enumerate_elem_dofs(n_node_dof, n_elem_nodes, elems_local, dof_map, element_dofs); elems_local += n_elem_nodes; for(i=0; i<n_elem_dof; i++){ /* Note the dof traversal order for symmetric matrices */ for(j=i*symm; j<n_elem_dof; j++){ dofi = element_dofs[i]; dofj = element_dofs[j]; if(symm && dofi>dofj){ pos = dofj; dofj = dofi; dofi = pos; } Avalue = *Aelems_ptr; Aelems_ptr++; /* handle local dofs using static lists */ if(row_start <= dofi && dofi < row_end){ /* local matrix part */ /* choose between the static and dynamic data structure */ if(n_list_elems_static){ chkstatic++; li = (size_t)dofi*n_row_entries; if(n_list_elems_static[dofi] < n_row_entries){ /* Add to static list since there is space */ /* Duplicate entry is not added to the list */ sorted_list_add_static_accum_dimType_Double(lists_static + li, n_list_elems_static + dofi, dofj, dlists_static + li, Avalue); continue; } else { /* locate to see if we have it in the static list already */ pos = sorted_list_locate_dimType(lists_static + li, n_row_entries, dofj); if(pos<n_row_entries && lists_static[li + pos]==dofj) { dlists_static[li+pos] += Avalue; continue; } } } dynamic++; /* dynamic data structure */ /* check if a given row has a dynamic list */ if(!list_size_dynamic[dofi]){ sorted_list_create_pair(lists_dynamic + dofi, dlists_dynamic + dofi, list_size_dynamic + dofi); } sorted_list_add_accum(lists_dynamic + dofi, n_list_elems_dynamic + dofi, list_size_dynamic + dofi, dofj, dlists_dynamic + dofi, Avalue); } else { #ifdef USE_OPENMP /* non-local matrix part - only used in parallel mode */ nonlocal++; /* locate the cpu that owns this triplet */ pos = sorted_list_locate_dimType(row_cpu_dist, nthr, dofi); if(row_cpu_dist[pos]==dofi) pos++; /* add the triplet to the non-local list */ if(comm_size[pos*nthr+thrid]==n_comm_entries[pos*nthr+thrid]){ comm_size[pos*nthr+thrid] += DYNAMIC_ALLOC_SIZE; mrealloc(comm_entries[pos*nthr+thrid], sizeof(triplet_t)*comm_size[pos*nthr+thrid], sizeof(triplet_t)*DYNAMIC_ALLOC_SIZE); } comm_entries[pos*nthr+thrid][n_comm_entries[pos*nthr+thrid]].dofi = dofi; comm_entries[pos*nthr+thrid][n_comm_entries[pos*nthr+thrid]].dofj = dofj; comm_entries[pos*nthr+thrid][n_comm_entries[pos*nthr+thrid]].value = Avalue; n_comm_entries[pos*nthr+thrid]++; #endif /* USE_OPENMP */ } } } } #ifdef USE_OPENMP #pragma omp barrier #pragma omp flush /* handle communication - accumulate local triplets that have been found by other threads */ for(j=0; j<nthr; j++){ /* local data - no communication */ if(j==thrid) continue; for(i=0; i<n_comm_entries[thrid*nthr+j]; i++){ dofi = comm_entries[thrid*nthr+j][i].dofi; dofj = comm_entries[thrid*nthr+j][i].dofj; Avalue = comm_entries[thrid*nthr+j][i].value; if(n_list_elems_static){ chkstatic++; li = (size_t)dofi*n_row_entries; if(n_list_elems_static[dofi] < n_row_entries){ /* Add to static list since there is space */ /* Duplicate entry is not added to the list */ sorted_list_add_static_accum_dimType_Double(lists_static + li, n_list_elems_static + dofi, dofj, dlists_static + li, Avalue); continue; } else { /* locate to see if we have it in the static list already */ pos = sorted_list_locate_dimType(lists_static + li, n_row_entries, dofj); if(pos<n_row_entries && lists_static[li + pos]==dofj) { dlists_static[li+pos] += Avalue; continue; } } } dynamic++; /* dynamic data structure */ /* check if a given row has a dynamic list */ if(!list_size_dynamic[dofi]){ sorted_list_create_pair(lists_dynamic + dofi, dlists_dynamic + dofi, list_size_dynamic + dofi); } sorted_list_add_accum(lists_dynamic + dofi, n_list_elems_dynamic + dofi, list_size_dynamic + dofi, dofj, dlists_dynamic + dofi, Avalue); } mfree(comm_entries[thrid*nthr+j], sizeof(triplet_t)*comm_size[thrid*nthr+j]); } #endif /* USE_OPENMP */ VERBOSE("thread %"PRI_UINT", list access: nonlocal %"PRI_DIMTYPE" dynamic %"PRI_DIMTYPE" static %"PRI_DIMTYPE, DEBUG_DETAILED, thrid, nonlocal, dynamic, chkstatic); /* Count a cumulative sum of the number of non-zeros in every matrix row. */ /* NOTE: Ap is here thread-local and needs to be further updated. */ /* Last iteration has to be unrolled to make sure we do not overwrite */ /* the first element of Ap of the next thread, which should be 0. */ (*Ap_out)[row_start] = 0; for(i=row_start; i<row_end-1; i++) { (*Ap_out)[i+1] = (*Ap_out)[i] + n_list_elems_static[i] + n_list_elems_dynamic[i]; } /* Execute in order: */ /* Determine the number of non-zeros in the 'earlier' part of the matrix (nnz_shift). */ /* This is later used to update the thread-local Ap row pointer vector */ /* into the final, assembled Ap vector. */ for(i=0; i<nthr; i++){ if(thrid==i){ #ifdef USE_OPENMP #pragma omp flush(nnz) #endif /* USE_OPENMP */ /* NOTE: nnz is a shared variable that is updated by all threads in order */ nnz_shift = nnz; nnz += (*Ap_out)[row_end-1] + n_list_elems_static[row_end-1] + n_list_elems_dynamic[row_end-1]; } #ifdef USE_OPENMP #pragma omp barrier #endif /* USE_OPENMP */ } #ifdef USE_OPENMP #pragma omp single #endif /* USE_OPENMP */ { (*Ap_out)[matrix_dim] = nnz; /* allocate row array */ mmalloc_global(*Ai_out, sizeof(mwSize)*nnz); mmalloc_global(*Ax_out, sizeof(Double)*nnz); DMESSAGE("maximum memory usage (MB): %lli\n", DEBUG_MEMORY, (long long)get_total_memory_usage()/1024/1024); } /* create matrix rows */ #ifdef USE_OPENMP #pragma omp barrier #endif assemble_sparse_matrix(*Ap_out, *Ai_out, *Ax_out, row_start, row_end, n_row_entries, lists_static, dlists_static, n_list_elems_static, lists_dynamic, dlists_dynamic, n_list_elems_dynamic, list_size_dynamic, nnz_shift); #ifdef USE_OPENMP #pragma omp single { mfree(comm_entries, sizeof(triplet_t*)*nthr*nthr); mfree(comm_size, sizeof(dimType)*nthr*nthr); mfree(n_comm_entries, sizeof(dimType)*nthr*nthr); mfree(row_cpu_dist, sizeof(dimType)*nthr); } #endif /* USE_OPENMP */ } mfree(lists_dynamic, sizeof(dimType*)*matrix_dim); mfree(dlists_dynamic, sizeof(Double*)*matrix_dim); mfree(list_size_dynamic, sizeof(dimType)*matrix_dim); mfree(n_list_elems_dynamic, sizeof(dimType)*(matrix_dim)); mfree(lists_static, sizeof(dimType)*n_row_entries*matrix_dim); mfree(dlists_static, sizeof(Double)*n_row_entries*matrix_dim); mfree(n_list_elems_static, sizeof(dimType)*matrix_dim); } /* Creates an index map from element dofs to the Ax array in the CRS sparse storage. */ void sparse_map_create(dimType n_node_dof, dimType n_elem_dof, dimType n_elems, dimType n_elem_nodes, dimType *elems, dimType *dof_map, dimType symm, mwIndex *Ap, mwSize *Ai, mwIndex **Map_out, size_t *map_size){ dimType i, j, iel; dimType *element_dofs = alloca(n_elem_dof*sizeof(dimType)); size_t sparse_iter = 0; size_t map_length; dimType dofi, dofj, pos; mwIndex *map; mwIndex *rowptr = 0; mwIndex nrowent = 0; mwIndex rowstart = 0; if(symm){ map_length = (mwIndex)n_elems*n_elem_dof*(n_elem_dof+1)/2; } else { map_length = (mwIndex)n_elems*n_elem_dof*n_elem_dof; } mmalloc_global(map, sizeof(mwIndex)*map_length); for(iel=0; iel<n_elems; iel++){ enumerate_elem_dofs(n_node_dof, n_elem_nodes, elems, dof_map, element_dofs); for(i=0; i<n_elem_dof; i++){ for(j=i*symm; j<n_elem_dof; j++){ dofi = element_dofs[i]; dofj = element_dofs[j]; if(symm && dofi>dofj){ pos = dofj; dofj = dofi; dofi = pos; } rowptr = Ai + Ap[dofi]; rowstart = Ap[dofi]; nrowent = Ap[dofi+1] - Ap[dofi]; map[sparse_iter++] = ONE_BASED_INDEX + rowstart + sorted_list_locate_mwIndex(rowptr, nrowent, (mwIndex)dofj); if(map[sparse_iter-1]==0) MESSAGE("ups"); } } } *Map_out = map; *map_size = map_length; } #ifdef MATLAB_MEX_FILE #include <libmatlab/mexparams.h> void mexFunction(int nargout, mxArray *pargout [ ], int nargin, const mxArray *pargin[]) { size_t m, n; char buff[256]; dimType n_elem_nodes; dimType n_elems; dimType matrix_dim = 0; dimType *dof_map = NULL; dimType *elems = NULL; mwIndex matrix_nz = 0; Double *Aelems = NULL; t_opts opts; int arg = 0; dimType distinct_elem_matrices = 1; /* unique element matrix for all elements */ dimType symbolic = 1; Uint argout = 0; /* MATLAB sparse storage arrays */ mwIndex *Ap = NULL; mwSize *Ai = NULL; Double *Ax = NULL; if (nargin < 1 || nargin > 4) MEXHELP; tic(); /* ELEMS */ m = 0; n = 0; elems = mex_get_matrix(dimType, pargin[arg++], &m, &n, "ELEMS", "number of element nodes", "number of elements", 0); SNPRINTF(buff, 255, "No dimensions of 'ELEMS' can be larger than %"PRI_DIMTYPE, MaxDimType); managed_type_cast(dimType, n_elem_nodes, m, buff); managed_type_cast(dimType, n_elems, n, buff); /* options */ arg = 2; if(nargin>=arg+1){ opts = mex2opts(pargin[arg]); } else { opts = mex2opts(NULL); } parallel_set_num_threads(opts.nthreads); /* These are empirically obtained 'good' values. */ /* For unstructured meshes these are larger than */ /* the average number of entries per row in the resulting matrix */ /* to account for variation in the actual mesh connectivity. */ if(opts.n_row_entries == -1){ switch(n_elem_nodes){ case 3: opts.n_row_entries = 12; break; case 6: opts.n_row_entries = 20; break; case 7: opts.n_row_entries = 32; break; case 4: opts.n_row_entries = 20; break; /* assume 3d tet, not 2d quad */ case 9: opts.n_row_entries = 14; break; case 10: opts.n_row_entries = 48; break; case 15: opts.n_row_entries = 32; break; /* needs to be larger for parallel execution */ case 8: opts.n_row_entries = 14; break; case 27: opts.n_row_entries = 48; break; default: opts.n_row_entries = 16; break; } /* why is this slower? */ /* if(opts.symmetric) opts.n_row_entries /=2; */ opts.n_row_entries *= opts.n_node_dof; } /* element matrix for node dofs */ arg = 1; if(nargin>=arg+1){ m = 0; n = 0; Aelems = mex_get_matrix(Double, pargin[arg++], &m, &n, "Aelems", "number of element matrix entries", "number of elements", 1); /* decipher Aelems size */ if(Aelems){ symbolic = 0; if(m==1 && n==1){ /* OK. symbolic matrix */ symbolic = 1; } else if(n==n_elems || m==n_elems){ if(opts.symmetric){ if(m*n != (Ulong)n_elems*(n_elem_nodes*opts.n_node_dof)*(n_elem_nodes*opts.n_node_dof+1)/2){ USERERROR("For symmetric matrices Aelems must be the size of (nnod*ndof)*(nnod*ndof+1)/2 X (1 or nel)", MUTILS_INVALID_PARAMETER); } } else { if(m*n != (Ulong)n_elems*(n_elem_nodes*opts.n_node_dof)*(n_elem_nodes*opts.n_node_dof)){ USERERROR("For general matrices Aelems must be the size of (nnod*ndof)*(nnod*ndof) X (1 or nel)", MUTILS_INVALID_PARAMETER); } } /* OK. element matrices for every element separately */ distinct_elem_matrices = 1; } else if(m==1 || n==1){ if(opts.symmetric){ /* symmetric sparse matrix and common element matrix */ if(m*n != (n_elem_nodes*opts.n_node_dof)*(n_elem_nodes*opts.n_node_dof+1)/2){ USERERROR("For symmetric matrices Aelems must be the size of (nnod*ndof)*(nnod*ndof+1)/2 X (1 or nel)", MUTILS_INVALID_PARAMETER); } } else { /* general sparse matrix and common element matrix */ if(m*n != (n_elem_nodes*opts.n_node_dof)*(n_elem_nodes*opts.n_node_dof)){ USERERROR("For general matrices Aelems must be the size of (nnod*ndof)*(nnod*ndof) X (1 or nel)", MUTILS_INVALID_PARAMETER); } } /* OK. The same element matrix for all elements */ distinct_elem_matrices = 0; } else { USERERROR("Can not understand size of Aelem. Type 'help sparse_create' for more information on Aelem.", MUTILS_INVALID_PARAMETER); } } else { symbolic = 1; } } /* Analyze ELEMS and find out the matrix dimensions */ { size_t i; dimType n_ref_nodes; char buff[256]; n_ref_nodes = validate_elems(elems, n_elems, 0, n_elem_nodes); i = (size_t)n_ref_nodes*opts.n_node_dof; SNPRINTF(buff, 255, "Matrix dimension (%zu) is too large. Maximum matrix dimension is %"PRI_DIMTYPE, i, MaxDimType); managed_type_cast(dimType, matrix_dim, i, buff); } /* Check if we have a permutation/map. */ /* Validate the map */ arg = 3; if(nargin>=arg+1){ dimType i; char buff[256]; m = 1; n = matrix_dim; dof_map = mex_get_matrix(dimType, pargin[arg++], &m, &n, "dof_map", "1", "matrix dimension", 1); if(dof_map){ /* dof_map can map nodes/dofs onto each other and reduce matrix_dim */ m = 0; for(i=0; i<matrix_dim; i++) { if(dof_map[i] < ONE_BASED_INDEX) USERERROR("Invalid dof_map. Values can not be smaller than %d.", MUTILS_INVALID_PARAMETER, ONE_BASED_INDEX); m = MAX(m, dof_map[i]); } SNPRINTF(buff, 255, "Matrix dimension (%"PRI_DIMTYPE") is too large. Maximum matrix dimension is %"PRI_DIMTYPE, i, MaxDimType); managed_type_cast(dimType, matrix_dim, m, buff); } } /* check the matrix dimension */ validate_matrix_dim(matrix_dim); /* Validate index operations and memory size bounds */ /* to make sure that the array sizes fit size_t */ { size_t size; uint64_t temp; char buff[256]; SNPRINTF(buff, 255, "Size of opts.n_row_entries*matrix_dim too large to fit into memory."); safemult_u(sizeof(dimType), opts.n_row_entries, temp, buff); safemult_u(temp, matrix_dim, temp, buff); managed_type_cast(size_t, size, temp, buff); safemult_u(sizeof(Double), opts.n_row_entries, temp, buff); safemult_u(temp, matrix_dim, temp, buff); managed_type_cast(size_t, size, temp, buff); } ntoc("MATLAB input (time)"); /* assemble the matrix, or just create the sparsity structure */ tic(); if(!symbolic){ sparse_matrix_create_accum(matrix_dim, opts.n_node_dof, opts.n_node_dof*n_elem_nodes, n_elems, n_elem_nodes, elems, Aelems, distinct_elem_matrices, &Ap, &Ai, &Ax, opts.symmetric, opts.n_row_entries, dof_map); } else { sparse_matrix_create(matrix_dim, opts.n_node_dof, opts.n_node_dof*n_elem_nodes, n_elems, n_elem_nodes, elems, &Ap, &Ai, opts.symmetric, opts.n_row_entries, dof_map); } matrix_nz = Ap[matrix_dim]; ntoc("sparse_matrix_create (time)"); /* return sparse matrix */ tic(); { mxArray *A = 0; mwIndex i; size_t Axsize; if(!Ax){ A = mxCreateSparseLogicalMatrix(0, 0, 0); mmalloc_global(Ax, matrix_nz*sizeof(mxLogical)); /* VS does not support unsigned loop iterators as of now. */ #ifndef _MSC_VER #ifdef USE_OPENMP #pragma omp parallel for schedule(static) #endif #endif for(i=0; i<matrix_nz; i++) { ((mxLogical*)Ax)[i] = 1; } Axsize = sizeof(mxLogical); } else { A = mxCreateSparse(0, 0, 0, mxREAL); Axsize = sizeof(Double); } mpersistent(Ax, matrix_nz*Axsize); mpersistent(Ap, (matrix_dim+1)*sizeof(indexType)); mpersistent(Ai, matrix_nz*sizeof(mwSize)); mxSetM(A, matrix_dim); mxSetN(A, matrix_dim); mxSetNzmax(A, matrix_nz); mxSetJc(A, Ap); mxSetIr(A, Ai); mxSetPr(A, Ax); pargout[argout] = A; } /* create map */ if(opts.gen_map && nargout>1){ mwIndex *map = NULL; size_t map_size = 0; uint64_t temp; dimType n_elem_dof = n_elem_nodes*opts.n_node_dof; char buff[256]; mxClassID class_out; SNPRINTF(buff, 255, "Size of MAP too large to fit into memory."); safemult_u(sizeof(mwIndex), n_elems, temp, buff); safemult_u(temp, n_elem_dof, temp, buff); safemult_u(temp, n_elem_dof, temp, buff); managed_type_cast(size_t, map_size, temp, buff); sparse_map_create(opts.n_node_dof, opts.n_node_dof*n_elem_nodes, n_elems, n_elem_nodes, elems, dof_map, opts.symmetric, Ap, Ai, &map, &map_size); get_matlab_class(mwIndex, class_out); pargout[1] = mxCreateNumericMatrix(0, 0, class_out, mxREAL); mxSetN(pargout[1], 1); mxSetM(pargout[1], map_size); mxSetData(pargout[1], map); mpersistent(map, sizeof(mwIndex)*map_size); } ntoc("MATLAB output (time)"); DEBUG_STATISTICS; } #endif
PReLU.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/PReLU.c" #else void THNN_(PReLU_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THTensor *weight, THIndex_t nOutputPlane) { THTensor_(resizeAs)(output, input); if (nOutputPlane == 0) { // handle shared parameter case real w = *THTensor_(data)(weight); TH_TENSOR_APPLY2(real, output, real, input, *output_data = (*input_data > 0) ? *input_data : w*(*input_data); ); } else { input = THTensor_(newContiguous)(input); long bs = 1, ks = 1; { long input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } real *output_data = THTensor_(data)(output); real *input_data = THTensor_(data)(input); real *weight_data = THTensor_(data)(weight); THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { real* n_input_data = input_data + i*nOutputPlane*ks; real* n_output_data = output_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { for (k = 0; k < ks; ++k) n_output_data[k] = (n_input_data[k] > 0) ? n_input_data[k] : weight_data[j] * n_input_data[k]; n_input_data += ks; n_output_data += ks; } } THTensor_(free)(input); } } void THNN_(PReLU_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THIndex_t nOutputPlane) { THNN_CHECK_NELEMENT(input, gradOutput); THTensor_(resizeAs)(gradInput, input); if (nOutputPlane == 0) { real w = THTensor_(data)(weight)[0]; TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, input, if ((*input_data) > 0) *gradInput_data = *gradOutput_data; else *gradInput_data = w * (*gradOutput_data); ); } else { input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); const real *weight_data = THTensor_(data)(weight); real *gradInput_data = THTensor_(data)(gradInput); long bs = 1, ks = 1; { long input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; real *n_gradInput_data = gradInput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real w = weight_data[j]; for (k = 0; k < ks; ++k) { if (n_input_data[k] > 0) n_gradInput_data[k] = n_gradOutput_data[k]; else n_gradInput_data[k] = n_gradOutput_data[k] * w; } n_input_data += ks; n_gradInput_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } } void THNN_(PReLU_accGradParameters)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *gradWeight, THTensor *gradWeightBuf, THTensor *gradWeightBuf2, THIndex_t nOutputPlane, accreal scale_) { real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_); THNN_CHECK_NELEMENT(input, gradOutput); if (nOutputPlane == 0) { real *gradWeight_data = THTensor_(data)(gradWeight); real sum = 0; TH_TENSOR_APPLY2(real, input, real, gradOutput, if ((*input_data) <= 0) sum += (*input_data) * (*gradOutput_data); ); gradWeight_data[0] += scale * sum; } else { THArgCheck(THTensor_(isContiguous)(gradWeight), 6, "gradWeight needs to be contiguous"); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); long bs = 1, ks = 1; { long input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); const real *weight_data = THTensor_(data)(weight); real *gradWeight_data = THTensor_(data)(gradWeight); THIndex_t i, j, k; for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real sum = 0; for (k = 0; k < ks; ++k) if (n_input_data[k] <= 0) sum += n_gradOutput_data[k] * n_input_data[k]; gradWeight_data[j] += scale * sum; n_input_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } } #endif
trsm_cmpt.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include "mkl.h" #include "sys/time.h" #include "math.h" #define min(X,Y) (((X) < (Y)) ? (X) : (Y)) #define TRSM_BATCH cblas_dtrsm_batch #define TRSM_COMPUTE_BATCH cblas_dtrsm_compute_batch #define fabst fabs #define FPTYPE double #define VECTOR_LENGTH 8 #define REPEAT 1000 #define MEM_ALIGNMENT 64 #define GRP_COUNT 1 int main(int argc, char *argv[]) { int i, j, ii, jj, nthr, grp; #pragma omp parallel { nthr = omp_get_num_threads(); } unsigned long op_count = 0; double startt, stopt, mint, mints; mint = 1e5; mints = 1e5; int group_count = GRP_COUNT; int pack_length = VECTOR_LENGTH; int m_init, grp_init; if (argc > 1) m_init = atoi(argv[1]); else m_init = 5; if (argc > 2) grp_init = atoi(argv[2]); else grp_init = 512; MKL_INT m[GRP_COUNT] = {m_init}; MKL_INT lda[GRP_COUNT] = {m_init}; MKL_INT ldb[GRP_COUNT] = {m_init}; FPTYPE alpha[GRP_COUNT] = {1.0}; MKL_INT size_per_grp[GRP_COUNT] = {grp_init}; CBLAS_SIDE SIDE[GRP_COUNT] = {CblasRight}; CBLAS_UPLO UPLO[GRP_COUNT] = {CblasUpper}; CBLAS_TRANSPOSE TRANSA[GRP_COUNT] = {CblasNoTrans}; CBLAS_DIAG DIAG[GRP_COUNT] = {CblasNonUnit}; int num_pointers = 0; for (i = 0; i < GRP_COUNT; i++) num_pointers += size_per_grp[i]; int a_total = 0; int b_total = 0; for (i = 0; i < GRP_COUNT; i++) a_total += m[i] * m[i] * size_per_grp[i]; for (i = 0; i < GRP_COUNT; i++) b_total += m[i] * m[i] * size_per_grp[i]; FPTYPE *a, *b, *c; a = (FPTYPE *)_mm_malloc( a_total * sizeof(FPTYPE), MEM_ALIGNMENT ); b = (FPTYPE *)_mm_malloc( b_total * sizeof(FPTYPE), MEM_ALIGNMENT ); c = (FPTYPE *)_mm_malloc( b_total * sizeof(FPTYPE), MEM_ALIGNMENT ); for (i = 0; i < a_total; i++) a[i] = (FPTYPE) rand() / (FPTYPE) RAND_MAX + .5; for (i = 0; i < b_total; i++) b[i] = (FPTYPE) rand() / (FPTYPE) RAND_MAX + .5; for (i = 0; i < b_total; i++) c[i] = b[i]; FPTYPE *a_array[num_pointers], *b_array[num_pointers]; int a_idx = 0; int b_idx = 0; int p_num = 0; for (i = 0; i < GRP_COUNT; i++) { for (j = 0; j < size_per_grp[i]; j++) { a_array[p_num] = &a[ a_idx ]; b_array[p_num] = &b[ b_idx ]; p_num++; a_idx += m[i] * m[i]; b_idx += m[i] * m[i]; op_count += m[i] * m[i] * m[i]; } } for (i = 0; i < GRP_COUNT; i++) { int idx_matrix = 0; for (ii = 0; ii < i; ii++) idx_matrix += size_per_grp[ii]; for (j = 0; j < size_per_grp[i]; j++) { for (ii = 0; ii < m[i]; ii++) { a_array[idx_matrix][ii*lda[i] + ii] = 10.0; } idx_matrix++; } } // setup packed arrays int grp_idx = 0; int A_p_idx = 0; int B_p_idx = 0; int i_grp, i_format, format_tail; FPTYPE *a_packed, *b_packed; a_packed = (FPTYPE *)_mm_malloc( a_total * sizeof(FPTYPE), MEM_ALIGNMENT ); b_packed = (FPTYPE *)_mm_malloc( b_total * sizeof(FPTYPE), MEM_ALIGNMENT ); // setup compact_t structs compact_t A_p, B_p, C_p; A_p.layout = CblasColMajor; A_p.rows = m; A_p.cols = m; A_p.stride = lda; A_p.group_count = GRP_COUNT; A_p.size_per_group = size_per_grp; A_p.format = VECTOR_LENGTH; A_p.mat = a_packed; B_p.layout = CblasColMajor; B_p.rows = m; B_p.cols = m; B_p.stride = ldb; B_p.group_count = GRP_COUNT; B_p.size_per_group = size_per_grp; B_p.format = VECTOR_LENGTH; B_p.mat = b_packed; for (i_grp=0; i_grp<GRP_COUNT; i_grp++) { for (i_format=0; i_format<(size_per_grp[i_grp]/VECTOR_LENGTH)*VECTOR_LENGTH; i_format+=VECTOR_LENGTH) { for (j=0; j<A_p.cols[i_grp]; j++) { for (i=0; i<A_p.rows[i_grp]; i++) { for (ii=0; ii<VECTOR_LENGTH; ii++) { a_packed[ii + A_p_idx] = a_array[ii + grp_idx + i_format][A_p.rows[i_grp]*j + i]; } A_p_idx+=VECTOR_LENGTH; } } for (j=0; j<B_p.cols[i_grp]; j++) { for (i=0; i<B_p.rows[i_grp]; i++) { for (ii=0; ii<VECTOR_LENGTH; ii++) { b_packed[ii + B_p_idx] = b_array[ii + grp_idx + i_format][B_p.rows[i_grp]*j + i]; } B_p_idx+=VECTOR_LENGTH; } } } // tail handling format_tail = size_per_grp[i_grp] - i_format; i_format = (size_per_grp[i_grp]/VECTOR_LENGTH)*VECTOR_LENGTH; if (format_tail > 0) { for (j=0; j<A_p.cols[i_grp]; j++) { for (i=0; i<A_p.rows[i_grp]; i++) { for (ii=0; ii<format_tail; ii++) { a_packed[ii + A_p_idx] = a_array[ii + grp_idx + i_format][A_p.rows[i_grp]*j + i]; } A_p_idx+=format_tail; } } for (j=0; j<B_p.cols[i_grp]; j++) { for (i=0; i<B_p.rows[i_grp]; i++) { for (ii=0; ii<format_tail; ii++) { b_packed[ii + B_p_idx] = b_array[ii + grp_idx + i_format][B_p.rows[i_grp]*j + i]; } B_p_idx+=format_tail; } } } grp_idx += size_per_grp[i_grp]; } printf("\n THREADS --- m = n --- TRSM_BATCH --- TRSM_BATCH_COMPUTE\n"); for (i = 0; i < REPEAT; i++) { startt = omp_get_wtime(); TRSM_BATCH( CblasColMajor, SIDE, UPLO, TRANSA, DIAG, m, m, alpha, (const FPTYPE**)a_array, lda, b_array, ldb, GRP_COUNT, size_per_grp ); stopt = omp_get_wtime(); mint = min(mint, (stopt - startt)); } for (i = 0; i < REPEAT; i++) { startt = omp_get_wtime(); TRSM_COMPUTE_BATCH( SIDE, UPLO, TRANSA, DIAG, alpha, &A_p, &B_p ); stopt = omp_get_wtime(); mints = min(mints, (stopt - startt)); } printf(" %d --- %d --- %5.2f --- %5.2f\n", nthr, m_init, (double)op_count/(mint*1e9), (double)op_count/(mints*1e9)); _mm_free(a_packed); _mm_free(b_packed); _mm_free(a); _mm_free(b); _mm_free(c); return 0; }
CImg.h
/* # # File : CImg.h # ( C++ header file ) # # Description : The C++ Template Image Processing Toolkit. # This file is the main component of the CImg Library project. # ( http://cimg.sourceforge.net ) # # Project manager : David Tschumperle. # ( http://tschumperle.users.greyc.fr/ ) # # A complete list of contributors is available in file 'README.txt' # distributed within the CImg package. # # Licenses : This file is 'dual-licensed', you have to choose one # of the two licenses below to apply. # # CeCILL-C # The CeCILL-C license is close to the GNU LGPL. # ( http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html ) # # or CeCILL v2.0 # The CeCILL license is compatible with the GNU GPL. # ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html ) # # This software is governed either by the CeCILL or the CeCILL-C license # under French law and abiding by the rules of distribution of free software. # You can use, modify and or redistribute the software under the terms of # the CeCILL or CeCILL-C licenses as circulated by CEA, CNRS and INRIA # at the following URL: "http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL and CeCILL-C licenses and that you accept its terms. # */ // Set version number of the library. #ifndef cimg_version #define cimg_version 152 /*----------------------------------------------------------- # # Test and possibly auto-set CImg configuration variables # and include required headers. # # If you find that the default configuration variables are # not adapted to your system, you can override their values # before including the header file "CImg.h" # (use the #define directive). # ------------------------------------------------------------*/ // Include standard C++ headers. // This is the minimal set of required headers to make CImg-based codes compile. #include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include <cmath> #include <ctime> #include <exception> // Detect/configure OS variables. // // Define 'cimg_OS' to: '0' for an unknown OS (will try to minize library dependencies). // '1' for a Unix-like OS (Linux, Solaris, BSD, MacOSX, Irix, ...). // '2' for Microsoft Windows. // (auto-detection is performed if 'cimg_OS' is not set by the user). #ifndef cimg_OS #if defined(unix) || defined(__unix) || defined(__unix__) \ || defined(linux) || defined(__linux) || defined(__linux__) \ || defined(sun) || defined(__sun) \ || defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) \ || defined(__FreeBSD__) || defined __DragonFly__ \ || defined(sgi) || defined(__sgi) \ || defined(__MACOSX__) || defined(__APPLE__) \ || defined(__CYGWIN__) #define cimg_OS 1 #elif defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \ || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) #define cimg_OS 2 #else #define cimg_OS 0 #endif #elif !(cimg_OS==0 || cimg_OS==1 || cimg_OS==2) #error CImg Library: Invalid configuration variable 'cimg_OS'. #error (correct values are '0 = unknown OS', '1 = Unix-like OS', '2 = Microsoft Windows'). #endif // Disable silly warnings on some Microsoft VC++ compilers. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4311) #pragma warning(disable:4312) #pragma warning(disable:4800) #pragma warning(disable:4804) #pragma warning(disable:4996) #define _CRT_SECURE_NO_DEPRECATE 1 #define _CRT_NONSTDC_NO_DEPRECATE 1 #endif // Include OS-specific headers. #if cimg_OS==1 #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #elif cimg_OS==2 #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> #ifndef _WIN32_IE #define _WIN32_IE 0x0400 #endif #include <shlobj.h> #include <process.h> #include <io.h> #define cimg_snprintf _snprintf #define cimg_vsnprintf _vsnprintf #endif #ifndef cimg_snprintf #include <stdio.h> #define cimg_snprintf snprintf #define cimg_vsnprintf vsnprintf #endif // Configure filename separator. // // Filename separator is set by default to '/', except for Windows where it is '\'. #ifndef cimg_file_separator #if cimg_OS==2 #define cimg_file_separator '\\' #else #define cimg_file_separator '/' #endif #endif // Configure verbosity of output messages. // // Define 'cimg_verbosity' to: '0' to hide library messages (quiet mode). // '1' to output library messages on the console. // '2' to output library messages on a basic dialog window (default behavior). // '3' to do as '1' + add extra warnings (may slow down the code!). // '4' to do as '2' + add extra warnings (may slow down the code!). // // Define 'cimg_strict_warnings' to replace warning messages by exception throwns. // // Define 'cimg_use_vt100' to allow output of color messages on VT100-compatible terminals. #ifndef cimg_verbosity #define cimg_verbosity 2 #elif !(cimg_verbosity==0 || cimg_verbosity==1 || cimg_verbosity==2 || cimg_verbosity==3 || cimg_verbosity==4) #error CImg Library: Configuration variable 'cimg_verbosity' is badly defined. #error (should be { 0=quiet | 1=console | 2=dialog | 3=console+warnings | 4=dialog+warnings }). #endif // Configure display framework. // // Define 'cimg_display' to: '0' to disable display capabilities. // '1' to use the X-Window framework (X11). // '2' to use the Microsoft GDI32 framework. #ifndef cimg_display #if cimg_OS==0 #define cimg_display 0 #elif cimg_OS==1 #if defined(__MACOSX__) || defined(__APPLE__) #define cimg_display 1 #else #define cimg_display 1 #endif #elif cimg_OS==2 #define cimg_display 2 #endif #elif !(cimg_display==0 || cimg_display==1 || cimg_display==2) #error CImg Library: Configuration variable 'cimg_display' is badly defined. #error (should be { 0=none | 1=X-Window (X11) | 2=Microsoft GDI32 }). #endif // Include display-specific headers. #if cimg_display==1 #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <pthread.h> #ifdef cimg_use_xshm #include <sys/ipc.h> #include <sys/shm.h> #include <X11/extensions/XShm.h> #endif #ifdef cimg_use_xrandr #include <X11/extensions/Xrandr.h> #endif #endif #ifndef cimg_appname #define cimg_appname "CImg" #endif // Configure OpenMP support. // (http://www.openmp.org) // // Define 'cimg_use_openmp' to enable OpenMP support. // // OpenMP directives may be used in a (very) few CImg functions to get // advantages of multi-core CPUs. #ifdef cimg_use_openmp #include "omp.h" #define _cimg_static #else #define _cimg_static static #endif // Configure OpenCV support. // (http://opencv.willowgarage.com/wiki/) // // Define 'cimg_use_opencv' to enable OpenCV support. // // OpenCV library may be used to access images from cameras // (see method 'CImg<T>::load_camera()'). #ifdef cimg_use_opencv #ifdef True #undef True #define _cimg_redefine_True #endif #ifdef False #undef False #define _cimg_redefine_False #endif #include <cstddef> #include "cv.h" #include "highgui.h" #endif // Configure LibPNG support. // (http://www.libpng.org) // // Define 'cimg_use_png' to enable LibPNG support. // // PNG library may be used to get a native support of '.png' files. // (see methods 'CImg<T>::{load,save}_png()'. #ifdef cimg_use_png extern "C" { #include "png.h" } #endif // Configure LibJPEG support. // (http://en.wikipedia.org/wiki/Libjpeg) // // Define 'cimg_use_jpeg' to enable LibJPEG support. // // JPEG library may be used to get a native support of '.jpg' files. // (see methods 'CImg<T>::{load,save}_jpeg()'). #ifdef cimg_use_jpeg extern "C" { #include "jpeglib.h" #include "setjmp.h" } #endif // Configure LibTIFF support. // (http://www.libtiff.org) // // Define 'cimg_use_tiff' to enable LibTIFF support. // // TIFF library may be used to get a native support of '.tif' files. // (see methods 'CImg[List]<T>::{load,save}_tiff()'). #ifdef cimg_use_tiff extern "C" { #include "tiffio.h" } #endif // Configure LibMINC2 support. // (http://en.wikibooks.org/wiki/MINC/Reference/MINC2.0_File_Format_Reference) // // Define 'cimg_use_minc2' to enable LibMINC2 support. // // MINC2 library may be used to get a native support of '.mnc' files. // (see methods 'CImg<T>::{load,save}_minc2()'). #ifdef cimg_use_minc2 #include "minc_io_simple_volume.h" #include "minc_1_simple.h" #include "minc_1_simple_rw.h" #endif // Configure FFMPEG support. // (http://www.ffmpeg.org) // // Define 'cimg_use_ffmpeg' to enable FFMPEG lib support. // // Avcodec and Avformat libraries from FFMPEG may be used // to get a native support of various video file formats. // (see methods 'CImg[List]<T>::load_ffmpeg()'). #ifdef cimg_use_ffmpeg #if (defined(_STDINT_H) || defined(_STDINT_H_)) && !defined(UINT64_C) #warning "__STDC_CONSTANT_MACROS has to be defined before including <stdint.h>, this file will probably not compile." #endif #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS // ...or stdint.h wont' define UINT64_C, needed by libavutil #endif extern "C" { #include "avformat.h" #include "avcodec.h" #include "swscale.h" } #endif // Configure Zlib support. // (http://www.zlib.net) // // Define 'cimg_use_zlib' to enable Zlib support. // // Zlib library may be used to allow compressed data in '.cimgz' files // (see methods 'CImg[List]<T>::{load,save}_cimg()'). #ifdef cimg_use_zlib extern "C" { #include "zlib.h" } #endif // Configure Magick++ support. // (http://www.imagemagick.org/Magick++) // // Define 'cimg_use_magick' to enable Magick++ support. // // Magick++ library may be used to get a native support of various image file formats. // (see methods 'CImg<T>::{load,save}()'). #ifdef cimg_use_magick #include "Magick++.h" #endif // Configure FFTW3 support. // (http://www.fftw.org) // // Define 'cimg_use_fftw3' to enable libFFTW3 support. // // FFTW3 library may be used to efficiently compute the Fast Fourier Transform // of image data, without restriction on the image size. // (see method 'CImg[List]<T>::FFT()'). #ifdef cimg_use_fftw3 extern "C" { #include "fftw3.h" } #endif // Configure LibBoard support. // (http://libboard.sourceforge.net/) // // Define 'cimg_use_board' to enable Board support. // // Board library may be used to draw 3d objects in vector-graphics canvas // that can be saved as '.ps' or '.svg' files afterwards. // (see method 'CImg<T>::draw_object3d()'). #ifdef cimg_use_board #ifdef None #undef None #define _cimg_redefine_None #endif #include "Board.h" #endif // Configure OpenEXR support. // (http://www.openexr.com/) // // Define 'cimg_use_openexr' to enable OpenEXR support. // // OpenEXR library may be used to get a native support of '.exr' files. // (see methods 'CImg<T>::{load,save}_exr()'). #ifdef cimg_use_openexr #include "ImfRgbaFile.h" #include "ImfInputFile.h" #include "ImfChannelList.h" #include "ImfMatrixAttribute.h" #include "ImfArray.h" #endif // Lapack configuration. // (http://www.netlib.org/lapack) // // Define 'cimg_use_lapack' to enable LAPACK support. // // Lapack library may be used in several CImg methods to speed up // matrix computations (eigenvalues, inverse, ...). #ifdef cimg_use_lapack extern "C" { extern void sgetrf_(int*, int*, float*, int*, int*, int*); extern void sgetri_(int*, float*, int*, int*, float*, int*, int*); extern void sgetrs_(char*, int*, int*, float*, int*, int*, float*, int*, int*); extern void sgesvd_(char*, char*, int*, int*, float*, int*, float*, float*, int*, float*, int*, float*, int*, int*); extern void ssyev_(char*, char*, int*, float*, int*, float*, float*, int*, int*); extern void dgetrf_(int*, int*, double*, int*, int*, int*); extern void dgetri_(int*, double*, int*, int*, double*, int*, int*); extern void dgetrs_(char*, int*, int*, double*, int*, int*, double*, int*, int*); extern void dgesvd_(char*, char*, int*, int*, double*, int*, double*, double*, int*, double*, int*, double*, int*, int*); extern void dsyev_(char*, char*, int*, double*, int*, double*, double*, int*, int*); extern void dgels_(char*, int*,int*,int*,double*,int*,double*,int*,double*,int*,int*); extern void sgels_(char*, int*,int*,int*,float*,int*,float*,int*,float*,int*,int*); } #endif // Check if min/max/PI macros are defined. // // CImg does not compile if macros 'min', 'max' or 'PI' are defined, // because it redefines functions min(), max() and const variable PI in the cimg:: namespace. // so it '#undef' these macros if necessary, and restore them to reasonable // values at the end of this file. #ifdef min #undef min #define _cimg_redefine_min #endif #ifdef max #undef max #define _cimg_redefine_max #endif #ifdef PI #undef PI #define _cimg_redefine_PI #endif // Define 'cimg_library' namespace suffix. // // You may want to add a suffix to the 'cimg_library' namespace, for instance if you need to work // with several versions of the library at the same time. #ifdef cimg_namespace_suffix #define __cimg_library_suffixed(s) cimg_library_##s #define _cimg_library_suffixed(s) __cimg_library_suffixed(s) #define cimg_library_suffixed _cimg_library_suffixed(cimg_namespace_suffix) #else #define cimg_library_suffixed cimg_library #endif /*------------------------------------------------------------------------------ # # Define user-friendly macros. # # These CImg macros are prefixed by 'cimg_' and can be used safely in your own # code. They are useful to parse command line options, or to write image loops. # ------------------------------------------------------------------------------*/ // Macros to define program usage, and retrieve command line arguments. #define cimg_usage(usage) cimg_library_suffixed::cimg::option((char*)0,argc,argv,(char*)0,usage,false) #define cimg_help(str) cimg_library_suffixed::cimg::option((char*)0,argc,argv,str,(char*)0) #define cimg_option(name,defaut,usage) cimg_library_suffixed::cimg::option(name,argc,argv,defaut,usage) #define cimg_argument(pos) cimg_library_suffixed::cimg::argument(pos,argc,argv) #define cimg_argument1(pos,s0) cimg_library_suffixed::cimg::argument(pos,argc,argv,1,s0) #define cimg_argument2(pos,s0,s1) cimg_library_suffixed::cimg::argument(pos,argc,argv,2,s0,s1) #define cimg_argument3(pos,s0,s1,s2) cimg_library_suffixed::cimg::argument(pos,argc,argv,3,s0,s1,s2) #define cimg_argument4(pos,s0,s1,s2,s3) cimg_library_suffixed::cimg::argument(pos,argc,argv,4,s0,s1,s2,s3) #define cimg_argument5(pos,s0,s1,s2,s3,s4) cimg_library_suffixed::cimg::argument(pos,argc,argv,5,s0,s1,s2,s3,s4) #define cimg_argument6(pos,s0,s1,s2,s3,s4,s5) cimg_library_suffixed::cimg::argument(pos,argc,argv,6,s0,s1,s2,s3,s4,s5) #define cimg_argument7(pos,s0,s1,s2,s3,s4,s5,s6) cimg_library_suffixed::cimg::argument(pos,argc,argv,7,s0,s1,s2,s3,s4,s5,s6) #define cimg_argument8(pos,s0,s1,s2,s3,s4,s5,s6,s7) cimg_library_suffixed::cimg::argument(pos,argc,argv,8,s0,s1,s2,s3,s4,s5,s6,s7) #define cimg_argument9(pos,s0,s1,s2,s3,s4,s5,s6,s7,s8) cimg_library_suffixed::cimg::argument(pos,argc,argv,9,s0,s1,s2,s3,s4,s5,s6,s7,s8) // Macros to define and manipulate local neighborhoods. #define CImg_2x2(I,T) T I[4]; \ T& I##cc = I[0]; T& I##nc = I[1]; \ T& I##cn = I[2]; T& I##nn = I[3]; \ I##cc = I##nc = \ I##cn = I##nn = 0 #define CImg_3x3(I,T) T I[9]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; \ T& I##pc = I[3]; T& I##cc = I[4]; T& I##nc = I[5]; \ T& I##pn = I[6]; T& I##cn = I[7]; T& I##nn = I[8]; \ I##pp = I##cp = I##np = \ I##pc = I##cc = I##nc = \ I##pn = I##cn = I##nn = 0 #define CImg_4x4(I,T) T I[16]; \ T& I##pp = I[0]; T& I##cp = I[1]; T& I##np = I[2]; T& I##ap = I[3]; \ T& I##pc = I[4]; T& I##cc = I[5]; T& I##nc = I[6]; T& I##ac = I[7]; \ T& I##pn = I[8]; T& I##cn = I[9]; T& I##nn = I[10]; T& I##an = I[11]; \ T& I##pa = I[12]; T& I##ca = I[13]; T& I##na = I[14]; T& I##aa = I[15]; \ I##pp = I##cp = I##np = I##ap = \ I##pc = I##cc = I##nc = I##ac = \ I##pn = I##cn = I##nn = I##an = \ I##pa = I##ca = I##na = I##aa = 0 #define CImg_5x5(I,T) T I[25]; \ T& I##bb = I[0]; T& I##pb = I[1]; T& I##cb = I[2]; T& I##nb = I[3]; T& I##ab = I[4]; \ T& I##bp = I[5]; T& I##pp = I[6]; T& I##cp = I[7]; T& I##np = I[8]; T& I##ap = I[9]; \ T& I##bc = I[10]; T& I##pc = I[11]; T& I##cc = I[12]; T& I##nc = I[13]; T& I##ac = I[14]; \ T& I##bn = I[15]; T& I##pn = I[16]; T& I##cn = I[17]; T& I##nn = I[18]; T& I##an = I[19]; \ T& I##ba = I[20]; T& I##pa = I[21]; T& I##ca = I[22]; T& I##na = I[23]; T& I##aa = I[24]; \ I##bb = I##pb = I##cb = I##nb = I##ab = \ I##bp = I##pp = I##cp = I##np = I##ap = \ I##bc = I##pc = I##cc = I##nc = I##ac = \ I##bn = I##pn = I##cn = I##nn = I##an = \ I##ba = I##pa = I##ca = I##na = I##aa = 0 #define CImg_2x2x2(I,T) T I[8]; \ T& I##ccc = I[0]; T& I##ncc = I[1]; \ T& I##cnc = I[2]; T& I##nnc = I[3]; \ T& I##ccn = I[4]; T& I##ncn = I[5]; \ T& I##cnn = I[6]; T& I##nnn = I[7]; \ I##ccc = I##ncc = \ I##cnc = I##nnc = \ I##ccn = I##ncn = \ I##cnn = I##nnn = 0 #define CImg_3x3x3(I,T) T I[27]; \ T& I##ppp = I[0]; T& I##cpp = I[1]; T& I##npp = I[2]; \ T& I##pcp = I[3]; T& I##ccp = I[4]; T& I##ncp = I[5]; \ T& I##pnp = I[6]; T& I##cnp = I[7]; T& I##nnp = I[8]; \ T& I##ppc = I[9]; T& I##cpc = I[10]; T& I##npc = I[11]; \ T& I##pcc = I[12]; T& I##ccc = I[13]; T& I##ncc = I[14]; \ T& I##pnc = I[15]; T& I##cnc = I[16]; T& I##nnc = I[17]; \ T& I##ppn = I[18]; T& I##cpn = I[19]; T& I##npn = I[20]; \ T& I##pcn = I[21]; T& I##ccn = I[22]; T& I##ncn = I[23]; \ T& I##pnn = I[24]; T& I##cnn = I[25]; T& I##nnn = I[26]; \ I##ppp = I##cpp = I##npp = \ I##pcp = I##ccp = I##ncp = \ I##pnp = I##cnp = I##nnp = \ I##ppc = I##cpc = I##npc = \ I##pcc = I##ccc = I##ncc = \ I##pnc = I##cnc = I##nnc = \ I##ppn = I##cpn = I##npn = \ I##pcn = I##ccn = I##ncn = \ I##pnn = I##cnn = I##nnn = 0 #define cimg_get2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), I[3] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), I[3] = (T)(img)(_p1##x,y,z,c), \ I[4] = (T)(img)(x,y,z,c), I[5] = (T)(img)(_n1##x,y,z,c), I[6] = (T)(img)(_p1##x,_n1##y,z,c), I[7] = (T)(img)(x,_n1##y,z,c), \ I[8] = (T)(img)(_n1##x,_n1##y,z,c) #define cimg_get4x4(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,z,c), I[1] = (T)(img)(x,_p1##y,z,c), I[2] = (T)(img)(_n1##x,_p1##y,z,c), I[3] = (T)(img)(_n2##x,_p1##y,z,c), \ I[4] = (T)(img)(_p1##x,y,z,c), I[5] = (T)(img)(x,y,z,c), I[6] = (T)(img)(_n1##x,y,z,c), I[7] = (T)(img)(_n2##x,y,z,c), \ I[8] = (T)(img)(_p1##x,_n1##y,z,c), I[9] = (T)(img)(x,_n1##y,z,c), I[10] = (T)(img)(_n1##x,_n1##y,z,c), I[11] = (T)(img)(_n2##x,_n1##y,z,c), \ I[12] = (T)(img)(_p1##x,_n2##y,z,c), I[13] = (T)(img)(x,_n2##y,z,c), I[14] = (T)(img)(_n1##x,_n2##y,z,c), I[15] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get5x5(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), I[3] = (T)(img)(_n1##x,_p2##y,z,c), \ I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_p2##x,_p1##y,z,c), I[6] = (T)(img)(_p1##x,_p1##y,z,c), I[7] = (T)(img)(x,_p1##y,z,c), \ I[8] = (T)(img)(_n1##x,_p1##y,z,c), I[9] = (T)(img)(_n2##x,_p1##y,z,c), I[10] = (T)(img)(_p2##x,y,z,c), I[11] = (T)(img)(_p1##x,y,z,c), \ I[12] = (T)(img)(x,y,z,c), I[13] = (T)(img)(_n1##x,y,z,c), I[14] = (T)(img)(_n2##x,y,z,c), I[15] = (T)(img)(_p2##x,_n1##y,z,c), \ I[16] = (T)(img)(_p1##x,_n1##y,z,c), I[17] = (T)(img)(x,_n1##y,z,c), I[18] = (T)(img)(_n1##x,_n1##y,z,c), I[19] = (T)(img)(_n2##x,_n1##y,z,c), \ I[20] = (T)(img)(_p2##x,_n2##y,z,c), I[21] = (T)(img)(_p1##x,_n2##y,z,c), I[22] = (T)(img)(x,_n2##y,z,c), I[23] = (T)(img)(_n1##x,_n2##y,z,c), \ I[24] = (T)(img)(_n2##x,_n2##y,z,c) #define cimg_get6x6(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p2##x,_p2##y,z,c), I[1] = (T)(img)(_p1##x,_p2##y,z,c), I[2] = (T)(img)(x,_p2##y,z,c), I[3] = (T)(img)(_n1##x,_p2##y,z,c), \ I[4] = (T)(img)(_n2##x,_p2##y,z,c), I[5] = (T)(img)(_n3##x,_p2##y,z,c), I[6] = (T)(img)(_p2##x,_p1##y,z,c), I[7] = (T)(img)(_p1##x,_p1##y,z,c), \ I[8] = (T)(img)(x,_p1##y,z,c), I[9] = (T)(img)(_n1##x,_p1##y,z,c), I[10] = (T)(img)(_n2##x,_p1##y,z,c), I[11] = (T)(img)(_n3##x,_p1##y,z,c), \ I[12] = (T)(img)(_p2##x,y,z,c), I[13] = (T)(img)(_p1##x,y,z,c), I[14] = (T)(img)(x,y,z,c), I[15] = (T)(img)(_n1##x,y,z,c), \ I[16] = (T)(img)(_n2##x,y,z,c), I[17] = (T)(img)(_n3##x,y,z,c), I[18] = (T)(img)(_p2##x,_n1##y,z,c), I[19] = (T)(img)(_p1##x,_n1##y,z,c), \ I[20] = (T)(img)(x,_n1##y,z,c), I[21] = (T)(img)(_n1##x,_n1##y,z,c), I[22] = (T)(img)(_n2##x,_n1##y,z,c), I[23] = (T)(img)(_n3##x,_n1##y,z,c), \ I[24] = (T)(img)(_p2##x,_n2##y,z,c), I[25] = (T)(img)(_p1##x,_n2##y,z,c), I[26] = (T)(img)(x,_n2##y,z,c), I[27] = (T)(img)(_n1##x,_n2##y,z,c), \ I[28] = (T)(img)(_n2##x,_n2##y,z,c), I[29] = (T)(img)(_n3##x,_n2##y,z,c), I[30] = (T)(img)(_p2##x,_n3##y,z,c), I[31] = (T)(img)(_p1##x,_n3##y,z,c), \ I[32] = (T)(img)(x,_n3##y,z,c), I[33] = (T)(img)(_n1##x,_n3##y,z,c), I[34] = (T)(img)(_n2##x,_n3##y,z,c), I[35] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get7x7(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), I[3] = (T)(img)(x,_p3##y,z,c), \ I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_p3##x,_p2##y,z,c), \ I[8] = (T)(img)(_p2##x,_p2##y,z,c), I[9] = (T)(img)(_p1##x,_p2##y,z,c), I[10] = (T)(img)(x,_p2##y,z,c), I[11] = (T)(img)(_n1##x,_p2##y,z,c), \ I[12] = (T)(img)(_n2##x,_p2##y,z,c), I[13] = (T)(img)(_n3##x,_p2##y,z,c), I[14] = (T)(img)(_p3##x,_p1##y,z,c), I[15] = (T)(img)(_p2##x,_p1##y,z,c), \ I[16] = (T)(img)(_p1##x,_p1##y,z,c), I[17] = (T)(img)(x,_p1##y,z,c), I[18] = (T)(img)(_n1##x,_p1##y,z,c), I[19] = (T)(img)(_n2##x,_p1##y,z,c), \ I[20] = (T)(img)(_n3##x,_p1##y,z,c), I[21] = (T)(img)(_p3##x,y,z,c), I[22] = (T)(img)(_p2##x,y,z,c), I[23] = (T)(img)(_p1##x,y,z,c), \ I[24] = (T)(img)(x,y,z,c), I[25] = (T)(img)(_n1##x,y,z,c), I[26] = (T)(img)(_n2##x,y,z,c), I[27] = (T)(img)(_n3##x,y,z,c), \ I[28] = (T)(img)(_p3##x,_n1##y,z,c), I[29] = (T)(img)(_p2##x,_n1##y,z,c), I[30] = (T)(img)(_p1##x,_n1##y,z,c), I[31] = (T)(img)(x,_n1##y,z,c), \ I[32] = (T)(img)(_n1##x,_n1##y,z,c), I[33] = (T)(img)(_n2##x,_n1##y,z,c), I[34] = (T)(img)(_n3##x,_n1##y,z,c), I[35] = (T)(img)(_p3##x,_n2##y,z,c), \ I[36] = (T)(img)(_p2##x,_n2##y,z,c), I[37] = (T)(img)(_p1##x,_n2##y,z,c), I[38] = (T)(img)(x,_n2##y,z,c), I[39] = (T)(img)(_n1##x,_n2##y,z,c), \ I[40] = (T)(img)(_n2##x,_n2##y,z,c), I[41] = (T)(img)(_n3##x,_n2##y,z,c), I[42] = (T)(img)(_p3##x,_n3##y,z,c), I[43] = (T)(img)(_p2##x,_n3##y,z,c), \ I[44] = (T)(img)(_p1##x,_n3##y,z,c), I[45] = (T)(img)(x,_n3##y,z,c), I[46] = (T)(img)(_n1##x,_n3##y,z,c), I[47] = (T)(img)(_n2##x,_n3##y,z,c), \ I[48] = (T)(img)(_n3##x,_n3##y,z,c) #define cimg_get8x8(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p3##x,_p3##y,z,c), I[1] = (T)(img)(_p2##x,_p3##y,z,c), I[2] = (T)(img)(_p1##x,_p3##y,z,c), I[3] = (T)(img)(x,_p3##y,z,c), \ I[4] = (T)(img)(_n1##x,_p3##y,z,c), I[5] = (T)(img)(_n2##x,_p3##y,z,c), I[6] = (T)(img)(_n3##x,_p3##y,z,c), I[7] = (T)(img)(_n4##x,_p3##y,z,c), \ I[8] = (T)(img)(_p3##x,_p2##y,z,c), I[9] = (T)(img)(_p2##x,_p2##y,z,c), I[10] = (T)(img)(_p1##x,_p2##y,z,c), I[11] = (T)(img)(x,_p2##y,z,c), \ I[12] = (T)(img)(_n1##x,_p2##y,z,c), I[13] = (T)(img)(_n2##x,_p2##y,z,c), I[14] = (T)(img)(_n3##x,_p2##y,z,c), I[15] = (T)(img)(_n4##x,_p2##y,z,c), \ I[16] = (T)(img)(_p3##x,_p1##y,z,c), I[17] = (T)(img)(_p2##x,_p1##y,z,c), I[18] = (T)(img)(_p1##x,_p1##y,z,c), I[19] = (T)(img)(x,_p1##y,z,c), \ I[20] = (T)(img)(_n1##x,_p1##y,z,c), I[21] = (T)(img)(_n2##x,_p1##y,z,c), I[22] = (T)(img)(_n3##x,_p1##y,z,c), I[23] = (T)(img)(_n4##x,_p1##y,z,c), \ I[24] = (T)(img)(_p3##x,y,z,c), I[25] = (T)(img)(_p2##x,y,z,c), I[26] = (T)(img)(_p1##x,y,z,c), I[27] = (T)(img)(x,y,z,c), \ I[28] = (T)(img)(_n1##x,y,z,c), I[29] = (T)(img)(_n2##x,y,z,c), I[30] = (T)(img)(_n3##x,y,z,c), I[31] = (T)(img)(_n4##x,y,z,c), \ I[32] = (T)(img)(_p3##x,_n1##y,z,c), I[33] = (T)(img)(_p2##x,_n1##y,z,c), I[34] = (T)(img)(_p1##x,_n1##y,z,c), I[35] = (T)(img)(x,_n1##y,z,c), \ I[36] = (T)(img)(_n1##x,_n1##y,z,c), I[37] = (T)(img)(_n2##x,_n1##y,z,c), I[38] = (T)(img)(_n3##x,_n1##y,z,c), I[39] = (T)(img)(_n4##x,_n1##y,z,c), \ I[40] = (T)(img)(_p3##x,_n2##y,z,c), I[41] = (T)(img)(_p2##x,_n2##y,z,c), I[42] = (T)(img)(_p1##x,_n2##y,z,c), I[43] = (T)(img)(x,_n2##y,z,c), \ I[44] = (T)(img)(_n1##x,_n2##y,z,c), I[45] = (T)(img)(_n2##x,_n2##y,z,c), I[46] = (T)(img)(_n3##x,_n2##y,z,c), I[47] = (T)(img)(_n4##x,_n2##y,z,c), \ I[48] = (T)(img)(_p3##x,_n3##y,z,c), I[49] = (T)(img)(_p2##x,_n3##y,z,c), I[50] = (T)(img)(_p1##x,_n3##y,z,c), I[51] = (T)(img)(x,_n3##y,z,c), \ I[52] = (T)(img)(_n1##x,_n3##y,z,c), I[53] = (T)(img)(_n2##x,_n3##y,z,c), I[54] = (T)(img)(_n3##x,_n3##y,z,c), I[55] = (T)(img)(_n4##x,_n3##y,z,c), \ I[56] = (T)(img)(_p3##x,_n4##y,z,c), I[57] = (T)(img)(_p2##x,_n4##y,z,c), I[58] = (T)(img)(_p1##x,_n4##y,z,c), I[59] = (T)(img)(x,_n4##y,z,c), \ I[60] = (T)(img)(_n1##x,_n4##y,z,c), I[61] = (T)(img)(_n2##x,_n4##y,z,c), I[62] = (T)(img)(_n3##x,_n4##y,z,c), I[63] = (T)(img)(_n4##x,_n4##y,z,c); #define cimg_get9x9(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p4##x,_p4##y,z,c), I[1] = (T)(img)(_p3##x,_p4##y,z,c), I[2] = (T)(img)(_p2##x,_p4##y,z,c), I[3] = (T)(img)(_p1##x,_p4##y,z,c), \ I[4] = (T)(img)(x,_p4##y,z,c), I[5] = (T)(img)(_n1##x,_p4##y,z,c), I[6] = (T)(img)(_n2##x,_p4##y,z,c), I[7] = (T)(img)(_n3##x,_p4##y,z,c), \ I[8] = (T)(img)(_n4##x,_p4##y,z,c), I[9] = (T)(img)(_p4##x,_p3##y,z,c), I[10] = (T)(img)(_p3##x,_p3##y,z,c), I[11] = (T)(img)(_p2##x,_p3##y,z,c), \ I[12] = (T)(img)(_p1##x,_p3##y,z,c), I[13] = (T)(img)(x,_p3##y,z,c), I[14] = (T)(img)(_n1##x,_p3##y,z,c), I[15] = (T)(img)(_n2##x,_p3##y,z,c), \ I[16] = (T)(img)(_n3##x,_p3##y,z,c), I[17] = (T)(img)(_n4##x,_p3##y,z,c), I[18] = (T)(img)(_p4##x,_p2##y,z,c), I[19] = (T)(img)(_p3##x,_p2##y,z,c), \ I[20] = (T)(img)(_p2##x,_p2##y,z,c), I[21] = (T)(img)(_p1##x,_p2##y,z,c), I[22] = (T)(img)(x,_p2##y,z,c), I[23] = (T)(img)(_n1##x,_p2##y,z,c), \ I[24] = (T)(img)(_n2##x,_p2##y,z,c), I[25] = (T)(img)(_n3##x,_p2##y,z,c), I[26] = (T)(img)(_n4##x,_p2##y,z,c), I[27] = (T)(img)(_p4##x,_p1##y,z,c), \ I[28] = (T)(img)(_p3##x,_p1##y,z,c), I[29] = (T)(img)(_p2##x,_p1##y,z,c), I[30] = (T)(img)(_p1##x,_p1##y,z,c), I[31] = (T)(img)(x,_p1##y,z,c), \ I[32] = (T)(img)(_n1##x,_p1##y,z,c), I[33] = (T)(img)(_n2##x,_p1##y,z,c), I[34] = (T)(img)(_n3##x,_p1##y,z,c), I[35] = (T)(img)(_n4##x,_p1##y,z,c), \ I[36] = (T)(img)(_p4##x,y,z,c), I[37] = (T)(img)(_p3##x,y,z,c), I[38] = (T)(img)(_p2##x,y,z,c), I[39] = (T)(img)(_p1##x,y,z,c), \ I[40] = (T)(img)(x,y,z,c), I[41] = (T)(img)(_n1##x,y,z,c), I[42] = (T)(img)(_n2##x,y,z,c), I[43] = (T)(img)(_n3##x,y,z,c), \ I[44] = (T)(img)(_n4##x,y,z,c), I[45] = (T)(img)(_p4##x,_n1##y,z,c), I[46] = (T)(img)(_p3##x,_n1##y,z,c), I[47] = (T)(img)(_p2##x,_n1##y,z,c), \ I[48] = (T)(img)(_p1##x,_n1##y,z,c), I[49] = (T)(img)(x,_n1##y,z,c), I[50] = (T)(img)(_n1##x,_n1##y,z,c), I[51] = (T)(img)(_n2##x,_n1##y,z,c), \ I[52] = (T)(img)(_n3##x,_n1##y,z,c), I[53] = (T)(img)(_n4##x,_n1##y,z,c), I[54] = (T)(img)(_p4##x,_n2##y,z,c), I[55] = (T)(img)(_p3##x,_n2##y,z,c), \ I[56] = (T)(img)(_p2##x,_n2##y,z,c), I[57] = (T)(img)(_p1##x,_n2##y,z,c), I[58] = (T)(img)(x,_n2##y,z,c), I[59] = (T)(img)(_n1##x,_n2##y,z,c), \ I[60] = (T)(img)(_n2##x,_n2##y,z,c), I[61] = (T)(img)(_n3##x,_n2##y,z,c), I[62] = (T)(img)(_n4##x,_n2##y,z,c), I[63] = (T)(img)(_p4##x,_n3##y,z,c), \ I[64] = (T)(img)(_p3##x,_n3##y,z,c), I[65] = (T)(img)(_p2##x,_n3##y,z,c), I[66] = (T)(img)(_p1##x,_n3##y,z,c), I[67] = (T)(img)(x,_n3##y,z,c), \ I[68] = (T)(img)(_n1##x,_n3##y,z,c), I[69] = (T)(img)(_n2##x,_n3##y,z,c), I[70] = (T)(img)(_n3##x,_n3##y,z,c), I[71] = (T)(img)(_n4##x,_n3##y,z,c), \ I[72] = (T)(img)(_p4##x,_n4##y,z,c), I[73] = (T)(img)(_p3##x,_n4##y,z,c), I[74] = (T)(img)(_p2##x,_n4##y,z,c), I[75] = (T)(img)(_p1##x,_n4##y,z,c), \ I[76] = (T)(img)(x,_n4##y,z,c), I[77] = (T)(img)(_n1##x,_n4##y,z,c), I[78] = (T)(img)(_n2##x,_n4##y,z,c), I[79] = (T)(img)(_n3##x,_n4##y,z,c), \ I[80] = (T)(img)(_n4##x,_n4##y,z,c) #define cimg_get2x2x2(img,x,y,z,c,I,T) \ I[0] = (T)(img)(x,y,z,c), I[1] = (T)(img)(_n1##x,y,z,c), I[2] = (T)(img)(x,_n1##y,z,c), I[3] = (T)(img)(_n1##x,_n1##y,z,c), \ I[4] = (T)(img)(x,y,_n1##z,c), I[5] = (T)(img)(_n1##x,y,_n1##z,c), I[6] = (T)(img)(x,_n1##y,_n1##z,c), I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c) #define cimg_get3x3x3(img,x,y,z,c,I,T) \ I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c), I[1] = (T)(img)(x,_p1##y,_p1##z,c), I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c), \ I[3] = (T)(img)(_p1##x,y,_p1##z,c), I[4] = (T)(img)(x,y,_p1##z,c), I[5] = (T)(img)(_n1##x,y,_p1##z,c), \ I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c), I[7] = (T)(img)(x,_n1##y,_p1##z,c), I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c), \ I[9] = (T)(img)(_p1##x,_p1##y,z,c), I[10] = (T)(img)(x,_p1##y,z,c), I[11] = (T)(img)(_n1##x,_p1##y,z,c), \ I[12] = (T)(img)(_p1##x,y,z,c), I[13] = (T)(img)(x,y,z,c), I[14] = (T)(img)(_n1##x,y,z,c), \ I[15] = (T)(img)(_p1##x,_n1##y,z,c), I[16] = (T)(img)(x,_n1##y,z,c), I[17] = (T)(img)(_n1##x,_n1##y,z,c), \ I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c), I[19] = (T)(img)(x,_p1##y,_n1##z,c), I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c), \ I[21] = (T)(img)(_p1##x,y,_n1##z,c), I[22] = (T)(img)(x,y,_n1##z,c), I[23] = (T)(img)(_n1##x,y,_n1##z,c), \ I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c), I[25] = (T)(img)(x,_n1##y,_n1##z,c), I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c) // Macros to perform various image loops. // // These macros are simpler to use than loops with C++ iterators. #define cimg_for(img,ptrs,T_ptrs) for (T_ptrs *ptrs = (img)._data, *_max##ptrs = (img)._data + (img).size(); ptrs<_max##ptrs; ++ptrs) #define cimg_rof(img,ptrs,T_ptrs) for (T_ptrs *ptrs = (img)._data + (img).size(); (ptrs--)>(img)._data; ) #define cimg_foroff(img,off) for (unsigned long off = 0, _max##off = (img).size(); off<_max##off; ++off) #define cimg_for1(bound,i) for (int i = 0; i<(int)(bound); ++i) #define cimg_forX(img,x) cimg_for1((img)._width,x) #define cimg_forY(img,y) cimg_for1((img)._height,y) #define cimg_forZ(img,z) cimg_for1((img)._depth,z) #define cimg_forC(img,c) cimg_for1((img)._spectrum,c) #define cimg_forXY(img,x,y) cimg_forY(img,y) cimg_forX(img,x) #define cimg_forXZ(img,x,z) cimg_forZ(img,z) cimg_forX(img,x) #define cimg_forYZ(img,y,z) cimg_forZ(img,z) cimg_forY(img,y) #define cimg_forXC(img,x,c) cimg_forC(img,c) cimg_forX(img,x) #define cimg_forYC(img,y,c) cimg_forC(img,c) cimg_forY(img,y) #define cimg_forZC(img,z,c) cimg_forC(img,c) cimg_forZ(img,z) #define cimg_forXYZ(img,x,y,z) cimg_forZ(img,z) cimg_forXY(img,x,y) #define cimg_forXYC(img,x,y,c) cimg_forC(img,c) cimg_forXY(img,x,y) #define cimg_forXZC(img,x,z,c) cimg_forC(img,c) cimg_forXZ(img,x,z) #define cimg_forYZC(img,y,z,c) cimg_forC(img,c) cimg_forYZ(img,y,z) #define cimg_forXYZC(img,x,y,z,c) cimg_forC(img,c) cimg_forXYZ(img,x,y,z) #define cimg_for_in1(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), _max##i = (int)(i1)<(int)(bound)?(int)(i1):(int)(bound)-1; i<=_max##i; ++i) #define cimg_for_inX(img,x0,x1,x) cimg_for_in1((img)._width,x0,x1,x) #define cimg_for_inY(img,y0,y1,y) cimg_for_in1((img)._height,y0,y1,y) #define cimg_for_inZ(img,z0,z1,z) cimg_for_in1((img)._depth,z0,z1,z) #define cimg_for_inC(img,c0,c1,c) cimg_for_in1((img)._spectrum,c0,c1,c) #define cimg_for_inXY(img,x0,y0,x1,y1,x,y) cimg_for_inY(img,y0,y1,y) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXZ(img,x0,z0,x1,z1,x,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inX(img,x0,x1,x) #define cimg_for_inXC(img,x0,c0,x1,c1,x,c) cimg_for_inC(img,c0,c1,c) cimg_for_inX(img,x0,x1,x) #define cimg_for_inYZ(img,y0,z0,y1,z1,y,z) cimg_for_inZ(img,x0,z1,z) cimg_for_inY(img,y0,y1,y) #define cimg_for_inYC(img,y0,c0,y1,c1,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inY(img,y0,y1,y) #define cimg_for_inZC(img,z0,c0,z1,c1,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inZ(img,z0,z1,z) #define cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_inZ(img,z0,z1,z) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXY(img,x0,y0,x1,y1,x,y) #define cimg_for_inXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXZ(img,x0,z0,x1,z1,x,z) #define cimg_for_inYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inYZ(img,y0,z0,y1,z1,y,z) #define cimg_for_inXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_inC(img,c0,c1,c) cimg_for_inXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_insideX(img,x,n) cimg_for_inX(img,n,(img)._width-1-(n),x) #define cimg_for_insideY(img,y,n) cimg_for_inY(img,n,(img)._height-1-(n),y) #define cimg_for_insideZ(img,z,n) cimg_for_inZ(img,n,(img)._depth-1-(n),z) #define cimg_for_insideC(img,c,n) cimg_for_inC(img,n,(img)._spectrum-1-(n),c) #define cimg_for_insideXY(img,x,y,n) cimg_for_inXY(img,n,n,(img)._width-1-(n),(img)._height-1-(n),x,y) #define cimg_for_insideXYZ(img,x,y,z,n) cimg_for_inXYZ(img,n,n,n,(img)._width-1-(n),(img)._height-1-(n),(img)._depth-1-(n),x,y,z) #define cimg_for_insideXYZC(img,x,y,z,c,n) cimg_for_inXYZ(img,n,n,n,(img)._width-1-(n),(img)._height-1-(n),(img)._depth-1-(n),x,y,z) #define cimg_for_out1(boundi,i0,i1,i) \ for (int i = (int)(i0)>0?0:(int)(i1)+1; i<(int)(boundi); ++i, i = i==(int)(i0)?(int)(i1)+1:i) #define cimg_for_out2(boundi,boundj,i0,j0,i1,j1,i,j) \ for (int j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j?0:(int)(i0)>0?0:(int)(i1)+1; i<(int)(boundi); \ ++i, i = _n1j?i:(i==(int)(i0)?(int)(i1)+1:i)) #define cimg_for_out3(boundi,boundj,boundk,i0,j0,k0,i1,j1,k1,i,j,k) \ for (int k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k?0:(int)(i0)>0?0:(int)(i1)+1; i<(int)(boundi); \ ++i, i = _n1j || _n1k?i:(i==(int)(i0)?(int)(i1)+1:i)) #define cimg_for_out4(boundi,boundj,boundk,boundl,i0,j0,k0,l0,i1,j1,k1,l1,i,j,k,l) \ for (int l = 0; l<(int)(boundl); ++l) \ for (int _n1l = (int)(l<(int)(l0) || l>(int)(l1)), k = 0; k<(int)(boundk); ++k) \ for (int _n1k = (int)(k<(int)(k0) || k>(int)(k1)), j = 0; j<(int)(boundj); ++j) \ for (int _n1j = (int)(j<(int)(j0) || j>(int)(j1)), i = _n1j || _n1k || _n1l?0:(int)(i0)>0?0:(int)(i1)+1; i<(int)(boundi); \ ++i, i = _n1j || _n1k || _n1l?i:(i==(int)(i0)?(int)(i1)+1:i)) #define cimg_for_outX(img,x0,x1,x) cimg_for_out1((img)._width,x0,x1,x) #define cimg_for_outY(img,y0,y1,y) cimg_for_out1((img)._height,y0,y1,y) #define cimg_for_outZ(img,z0,z1,z) cimg_for_out1((img)._depth,z0,z1,z) #define cimg_for_outC(img,c0,c1,c) cimg_for_out1((img)._spectrum,c0,c1,c) #define cimg_for_outXY(img,x0,y0,x1,y1,x,y) cimg_for_out2((img)._width,(img)._height,x0,y0,x1,y1,x,y) #define cimg_for_outXZ(img,x0,z0,x1,z1,x,z) cimg_for_out2((img)._width,(img)._depth,x0,z0,x1,z1,x,z) #define cimg_for_outXC(img,x0,c0,x1,c1,x,c) cimg_for_out2((img)._width,(img)._spectrum,x0,c0,x1,c1,x,c) #define cimg_for_outYZ(img,y0,z0,y1,z1,y,z) cimg_for_out2((img)._height,(img)._depth,y0,z0,y1,z1,y,z) #define cimg_for_outYC(img,y0,c0,y1,c1,y,c) cimg_for_out2((img)._height,(img)._spectrum,y0,c0,y1,c1,y,c) #define cimg_for_outZC(img,z0,c0,z1,c1,z,c) cimg_for_out2((img)._depth,(img)._spectrum,z0,c0,z1,c1,z,c) #define cimg_for_outXYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_out3((img)._width,(img)._height,(img)._depth,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for_outXYC(img,x0,y0,c0,x1,y1,c1,x,y,c) cimg_for_out3((img)._width,(img)._height,(img)._spectrum,x0,y0,c0,x1,y1,c1,x,y,c) #define cimg_for_outXZC(img,x0,z0,c0,x1,z1,c1,x,z,c) cimg_for_out3((img)._width,(img)._depth,(img)._spectrum,x0,z0,c0,x1,z1,c1,x,z,c) #define cimg_for_outYZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_out3((img)._height,(img)._depth,(img)._spectrum,y0,z0,c0,y1,z1,c1,y,z,c) #define cimg_for_outXYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) \ cimg_for_out4((img)._width,(img)._height,(img)._depth,(img)._spectrum,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) #define cimg_for_borderX(img,x,n) cimg_for_outX(img,n,(img)._width-1-(n),x) #define cimg_for_borderY(img,y,n) cimg_for_outY(img,n,(img)._height-1-(n),y) #define cimg_for_borderZ(img,z,n) cimg_for_outZ(img,n,(img)._depth-1-(n),z) #define cimg_for_borderC(img,c,n) cimg_for_outC(img,n,(img)._spectrum-1-(n),c) #define cimg_for_borderXY(img,x,y,n) cimg_for_outXY(img,n,n,(img)._width-1-(n),(img)._height-1-(n),x,y) #define cimg_for_borderXYZ(img,x,y,z,n) cimg_for_outXYZ(img,n,n,n,(img)._width-1-(n),(img)._height-1-(n),(img)._depth-1-(n),x,y,z) #define cimg_for_borderXYZC(img,x,y,z,c,n) \ cimg_for_outXYZC(img,n,n,n,n,(img)._width-1-(n),(img)._height-1-(n),(img)._depth-1-(n),(img)._spectrum-1-(n),x,y,z,c) #define cimg_for_spiralXY(img,x,y) \ for (int x = 0, y = 0, _n1##x = 1, _n1##y = (img).width()*(img).height(); _n1##y; \ --_n1##y, _n1##x+=(_n1##x>>2)-((!(_n1##x&3)?--y:((_n1##x&3)==1?(img)._width-1-++x:((_n1##x&3)==2?(img)._height-1-++y:--x))))?0:1) #define cimg_for_lineXY(x,y,x0,y0,x1,y1) \ for (int x = (int)(x0), y = (int)(y0), _sx = 1, _sy = 1, _steep = 0, \ _dx=(x1)>(x0)?(int)(x1)-(int)(x0):(_sx=-1,(int)(x0)-(int)(x1)), \ _dy=(y1)>(y0)?(int)(y1)-(int)(y0):(_sy=-1,(int)(y0)-(int)(y1)), \ _counter = _dx, \ _err = _dx>_dy?(_dy>>1):((_steep=1),(_counter=_dy),(_dx>>1)); \ _counter>=0; \ --_counter, x+=_steep? \ (y+=_sy,(_err-=_dx)<0?_err+=_dy,_sx:0): \ (y+=(_err-=_dy)<0?_err+=_dx,_sy:0,_sx)) #define cimg_for2(bound,i) \ for (int i = 0, _n1##i = 1>=(bound)?(int)(bound)-1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ ++i, ++_n1##i) #define cimg_for2X(img,x) cimg_for2((img)._width,x) #define cimg_for2Y(img,y) cimg_for2((img)._height,y) #define cimg_for2Z(img,z) cimg_for2((img)._depth,z) #define cimg_for2C(img,c) cimg_for2((img)._spectrum,c) #define cimg_for2XY(img,x,y) cimg_for2Y(img,y) cimg_for2X(img,x) #define cimg_for2XZ(img,x,z) cimg_for2Z(img,z) cimg_for2X(img,x) #define cimg_for2XC(img,x,c) cimg_for2C(img,c) cimg_for2X(img,x) #define cimg_for2YZ(img,y,z) cimg_for2Z(img,z) cimg_for2Y(img,y) #define cimg_for2YC(img,y,c) cimg_for2C(img,c) cimg_for2Y(img,y) #define cimg_for2ZC(img,z,c) cimg_for2C(img,c) cimg_for2Z(img,z) #define cimg_for2XYZ(img,x,y,z) cimg_for2Z(img,z) cimg_for2XY(img,x,y) #define cimg_for2XZC(img,x,z,c) cimg_for2C(img,c) cimg_for2XZ(img,x,z) #define cimg_for2YZC(img,y,z,c) cimg_for2C(img,c) cimg_for2YZ(img,y,z) #define cimg_for2XYZC(img,x,y,z,c) cimg_for2C(img,c) cimg_for2XYZ(img,x,y,z) #define cimg_for_in2(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ ++i, ++_n1##i) #define cimg_for_in2X(img,x0,x1,x) cimg_for_in2((img)._width,x0,x1,x) #define cimg_for_in2Y(img,y0,y1,y) cimg_for_in2((img)._height,y0,y1,y) #define cimg_for_in2Z(img,z0,z1,z) cimg_for_in2((img)._depth,z0,z1,z) #define cimg_for_in2C(img,c0,c1,c) cimg_for_in2((img)._spectrum,c0,c1,c) #define cimg_for_in2XY(img,x0,y0,x1,y1,x,y) cimg_for_in2Y(img,y0,y1,y) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XZ(img,x0,z0,x1,z1,x,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2XC(img,x0,c0,x1,c1,x,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2X(img,x0,x1,x) #define cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2YC(img,y0,c0,y1,c1,y,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Y(img,y0,y1,y) #define cimg_for_in2ZC(img,z0,c0,z1,c1,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2Z(img,z0,z1,z) #define cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in2Z(img,z0,z1,z) cimg_for_in2XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in2XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in2YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in2XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in2C(img,c0,c1,c) cimg_for_in2XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i) #define cimg_for3X(img,x) cimg_for3((img)._width,x) #define cimg_for3Y(img,y) cimg_for3((img)._height,y) #define cimg_for3Z(img,z) cimg_for3((img)._depth,z) #define cimg_for3C(img,c) cimg_for3((img)._spectrum,c) #define cimg_for3XY(img,x,y) cimg_for3Y(img,y) cimg_for3X(img,x) #define cimg_for3XZ(img,x,z) cimg_for3Z(img,z) cimg_for3X(img,x) #define cimg_for3XC(img,x,c) cimg_for3C(img,c) cimg_for3X(img,x) #define cimg_for3YZ(img,y,z) cimg_for3Z(img,z) cimg_for3Y(img,y) #define cimg_for3YC(img,y,c) cimg_for3C(img,c) cimg_for3Y(img,y) #define cimg_for3ZC(img,z,c) cimg_for3C(img,c) cimg_for3Z(img,z) #define cimg_for3XYZ(img,x,y,z) cimg_for3Z(img,z) cimg_for3XY(img,x,y) #define cimg_for3XZC(img,x,z,c) cimg_for3C(img,c) cimg_for3XZ(img,x,z) #define cimg_for3YZC(img,y,z,c) cimg_for3C(img,c) cimg_for3YZ(img,y,z) #define cimg_for3XYZC(img,x,y,z,c) cimg_for3C(img,c) cimg_for3XYZ(img,x,y,z) #define cimg_for_in3(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1; \ i<=(int)(i1) && (_n1##i<(int)(bound) || i==--_n1##i); \ _p1##i = i++, ++_n1##i) #define cimg_for_in3X(img,x0,x1,x) cimg_for_in3((img)._width,x0,x1,x) #define cimg_for_in3Y(img,y0,y1,y) cimg_for_in3((img)._height,y0,y1,y) #define cimg_for_in3Z(img,z0,z1,z) cimg_for_in3((img)._depth,z0,z1,z) #define cimg_for_in3C(img,c0,c1,c) cimg_for_in3((img)._spectrum,c0,c1,c) #define cimg_for_in3XY(img,x0,y0,x1,y1,x,y) cimg_for_in3Y(img,y0,y1,y) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XZ(img,x0,z0,x1,z1,x,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3XC(img,x0,c0,x1,c1,x,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3X(img,x0,x1,x) #define cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3YC(img,y0,c0,y1,c1,y,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Y(img,y0,y1,y) #define cimg_for_in3ZC(img,z0,c0,z1,c1,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3Z(img,z0,z1,z) #define cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in3Z(img,z0,z1,z) cimg_for_in3XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in3XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in3YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in3XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in3C(img,c0,c1,c) cimg_for_in3XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for4(bound,i) \ for (int i = 0, _p1##i = 0, _n1##i = 1>=(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(bound)?(int)(bound)-1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for4X(img,x) cimg_for4((img)._width,x) #define cimg_for4Y(img,y) cimg_for4((img)._height,y) #define cimg_for4Z(img,z) cimg_for4((img)._depth,z) #define cimg_for4C(img,c) cimg_for4((img)._spectrum,c) #define cimg_for4XY(img,x,y) cimg_for4Y(img,y) cimg_for4X(img,x) #define cimg_for4XZ(img,x,z) cimg_for4Z(img,z) cimg_for4X(img,x) #define cimg_for4XC(img,x,c) cimg_for4C(img,c) cimg_for4X(img,x) #define cimg_for4YZ(img,y,z) cimg_for4Z(img,z) cimg_for4Y(img,y) #define cimg_for4YC(img,y,c) cimg_for4C(img,c) cimg_for4Y(img,y) #define cimg_for4ZC(img,z,c) cimg_for4C(img,c) cimg_for4Z(img,z) #define cimg_for4XYZ(img,x,y,z) cimg_for4Z(img,z) cimg_for4XY(img,x,y) #define cimg_for4XZC(img,x,z,c) cimg_for4C(img,c) cimg_for4XZ(img,x,z) #define cimg_for4YZC(img,y,z,c) cimg_for4C(img,c) cimg_for4YZ(img,y,z) #define cimg_for4XYZC(img,x,y,z,c) cimg_for4C(img,c) cimg_for4XYZ(img,x,y,z) #define cimg_for_in4(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in4X(img,x0,x1,x) cimg_for_in4((img)._width,x0,x1,x) #define cimg_for_in4Y(img,y0,y1,y) cimg_for_in4((img)._height,y0,y1,y) #define cimg_for_in4Z(img,z0,z1,z) cimg_for_in4((img)._depth,z0,z1,z) #define cimg_for_in4C(img,c0,c1,c) cimg_for_in4((img)._spectrum,c0,c1,c) #define cimg_for_in4XY(img,x0,y0,x1,y1,x,y) cimg_for_in4Y(img,y0,y1,y) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XZ(img,x0,z0,x1,z1,x,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4XC(img,x0,c0,x1,c1,x,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4X(img,x0,x1,x) #define cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4YC(img,y0,c0,y1,c1,y,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Y(img,y0,y1,y) #define cimg_for_in4ZC(img,z0,c0,z1,c1,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4Z(img,z0,z1,z) #define cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in4Z(img,z0,z1,z) cimg_for_in4XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in4XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in4YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in4XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in4C(img,c0,c1,c) cimg_for_in4XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for5(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(bound)?(int)(bound)-1:2; \ _n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for5X(img,x) cimg_for5((img)._width,x) #define cimg_for5Y(img,y) cimg_for5((img)._height,y) #define cimg_for5Z(img,z) cimg_for5((img)._depth,z) #define cimg_for5C(img,c) cimg_for5((img)._spectrum,c) #define cimg_for5XY(img,x,y) cimg_for5Y(img,y) cimg_for5X(img,x) #define cimg_for5XZ(img,x,z) cimg_for5Z(img,z) cimg_for5X(img,x) #define cimg_for5XC(img,x,c) cimg_for5C(img,c) cimg_for5X(img,x) #define cimg_for5YZ(img,y,z) cimg_for5Z(img,z) cimg_for5Y(img,y) #define cimg_for5YC(img,y,c) cimg_for5C(img,c) cimg_for5Y(img,y) #define cimg_for5ZC(img,z,c) cimg_for5C(img,c) cimg_for5Z(img,z) #define cimg_for5XYZ(img,x,y,z) cimg_for5Z(img,z) cimg_for5XY(img,x,y) #define cimg_for5XZC(img,x,z,c) cimg_for5C(img,c) cimg_for5XZ(img,x,z) #define cimg_for5YZC(img,y,z,c) cimg_for5C(img,c) cimg_for5YZ(img,y,z) #define cimg_for5XYZC(img,x,y,z,c) cimg_for5C(img,c) cimg_for5XYZ(img,x,y,z) #define cimg_for_in5(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i-2<0?0:i-2, \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2; \ i<=(int)(i1) && (_n2##i<(int)(bound) || _n1##i==--_n2##i || i==(_n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i) #define cimg_for_in5X(img,x0,x1,x) cimg_for_in5((img)._width,x0,x1,x) #define cimg_for_in5Y(img,y0,y1,y) cimg_for_in5((img)._height,y0,y1,y) #define cimg_for_in5Z(img,z0,z1,z) cimg_for_in5((img)._depth,z0,z1,z) #define cimg_for_in5C(img,c0,c1,c) cimg_for_in5((img)._spectrum,c0,c1,c) #define cimg_for_in5XY(img,x0,y0,x1,y1,x,y) cimg_for_in5Y(img,y0,y1,y) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XZ(img,x0,z0,x1,z1,x,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5XC(img,x0,c0,x1,c1,x,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5X(img,x0,x1,x) #define cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5YC(img,y0,c0,y1,c1,y,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Y(img,y0,y1,y) #define cimg_for_in5ZC(img,z0,c0,z1,c1,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5Z(img,z0,z1,z) #define cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in5Z(img,z0,z1,z) cimg_for_in5XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in5XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in5YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in5XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in5C(img,c0,c1,c) cimg_for_in5XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for6(bound,i) \ for (int i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(bound)?(int)(bound)-1:2, \ _n3##i = 3>=(bound)?(int)(bound)-1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for6X(img,x) cimg_for6((img)._width,x) #define cimg_for6Y(img,y) cimg_for6((img)._height,y) #define cimg_for6Z(img,z) cimg_for6((img)._depth,z) #define cimg_for6C(img,c) cimg_for6((img)._spectrum,c) #define cimg_for6XY(img,x,y) cimg_for6Y(img,y) cimg_for6X(img,x) #define cimg_for6XZ(img,x,z) cimg_for6Z(img,z) cimg_for6X(img,x) #define cimg_for6XC(img,x,c) cimg_for6C(img,c) cimg_for6X(img,x) #define cimg_for6YZ(img,y,z) cimg_for6Z(img,z) cimg_for6Y(img,y) #define cimg_for6YC(img,y,c) cimg_for6C(img,c) cimg_for6Y(img,y) #define cimg_for6ZC(img,z,c) cimg_for6C(img,c) cimg_for6Z(img,z) #define cimg_for6XYZ(img,x,y,z) cimg_for6Z(img,z) cimg_for6XY(img,x,y) #define cimg_for6XZC(img,x,z,c) cimg_for6C(img,c) cimg_for6XZ(img,x,z) #define cimg_for6YZC(img,y,z,c) cimg_for6C(img,c) cimg_for6YZ(img,y,z) #define cimg_for6XYZC(img,x,y,z,c) cimg_for6C(img,c) cimg_for6XYZ(img,x,y,z) #define cimg_for_in6(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p2##i = i-2<0?0:i-2, \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2, \ _n3##i = i+3>=(int)(bound)?(int)(bound)-1:i+3; \ i<=(int)(i1) && (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in6X(img,x0,x1,x) cimg_for_in6((img)._width,x0,x1,x) #define cimg_for_in6Y(img,y0,y1,y) cimg_for_in6((img)._height,y0,y1,y) #define cimg_for_in6Z(img,z0,z1,z) cimg_for_in6((img)._depth,z0,z1,z) #define cimg_for_in6C(img,c0,c1,c) cimg_for_in6((img)._spectrum,c0,c1,c) #define cimg_for_in6XY(img,x0,y0,x1,y1,x,y) cimg_for_in6Y(img,y0,y1,y) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XZ(img,x0,z0,x1,z1,x,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6XC(img,x0,c0,x1,c1,x,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6X(img,x0,x1,x) #define cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6YC(img,y0,c0,y1,c1,y,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Y(img,y0,y1,y) #define cimg_for_in6ZC(img,z0,c0,z1,c1,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6Z(img,z0,z1,z) #define cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in6Z(img,z0,z1,z) cimg_for_in6XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in6XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in6YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in6XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in6C(img,c0,c1,c) cimg_for_in6XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for7(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(bound)?(int)(bound)-1:2, \ _n3##i = 3>=(bound)?(int)(bound)-1:3; \ _n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for7X(img,x) cimg_for7((img)._width,x) #define cimg_for7Y(img,y) cimg_for7((img)._height,y) #define cimg_for7Z(img,z) cimg_for7((img)._depth,z) #define cimg_for7C(img,c) cimg_for7((img)._spectrum,c) #define cimg_for7XY(img,x,y) cimg_for7Y(img,y) cimg_for7X(img,x) #define cimg_for7XZ(img,x,z) cimg_for7Z(img,z) cimg_for7X(img,x) #define cimg_for7XC(img,x,c) cimg_for7C(img,c) cimg_for7X(img,x) #define cimg_for7YZ(img,y,z) cimg_for7Z(img,z) cimg_for7Y(img,y) #define cimg_for7YC(img,y,c) cimg_for7C(img,c) cimg_for7Y(img,y) #define cimg_for7ZC(img,z,c) cimg_for7C(img,c) cimg_for7Z(img,z) #define cimg_for7XYZ(img,x,y,z) cimg_for7Z(img,z) cimg_for7XY(img,x,y) #define cimg_for7XZC(img,x,z,c) cimg_for7C(img,c) cimg_for7XZ(img,x,z) #define cimg_for7YZC(img,y,z,c) cimg_for7C(img,c) cimg_for7YZ(img,y,z) #define cimg_for7XYZC(img,x,y,z,c) cimg_for7C(img,c) cimg_for7XYZ(img,x,y,z) #define cimg_for_in7(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i-3<0?0:i-3, \ _p2##i = i-2<0?0:i-2, \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2, \ _n3##i = i+3>=(int)(bound)?(int)(bound)-1:i+3; \ i<=(int)(i1) && (_n3##i<(int)(bound) || _n2##i==--_n3##i || _n1##i==--_n2##i || i==(_n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i) #define cimg_for_in7X(img,x0,x1,x) cimg_for_in7((img)._width,x0,x1,x) #define cimg_for_in7Y(img,y0,y1,y) cimg_for_in7((img)._height,y0,y1,y) #define cimg_for_in7Z(img,z0,z1,z) cimg_for_in7((img)._depth,z0,z1,z) #define cimg_for_in7C(img,c0,c1,c) cimg_for_in7((img)._spectrum,c0,c1,c) #define cimg_for_in7XY(img,x0,y0,x1,y1,x,y) cimg_for_in7Y(img,y0,y1,y) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XZ(img,x0,z0,x1,z1,x,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7XC(img,x0,c0,x1,c1,x,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7X(img,x0,x1,x) #define cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7YC(img,y0,c0,y1,c1,y,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Y(img,y0,y1,y) #define cimg_for_in7ZC(img,z0,c0,z1,c1,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7Z(img,z0,z1,z) #define cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in7Z(img,z0,z1,z) cimg_for_in7XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in7XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in7YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in7XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in7C(img,c0,c1,c) cimg_for_in7XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for8(bound,i) \ for (int i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(bound)?(int)(bound)-1:2, \ _n3##i = 3>=(bound)?(int)(bound)-1:3, \ _n4##i = 4>=(bound)?(int)(bound)-1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for8X(img,x) cimg_for8((img)._width,x) #define cimg_for8Y(img,y) cimg_for8((img)._height,y) #define cimg_for8Z(img,z) cimg_for8((img)._depth,z) #define cimg_for8C(img,c) cimg_for8((img)._spectrum,c) #define cimg_for8XY(img,x,y) cimg_for8Y(img,y) cimg_for8X(img,x) #define cimg_for8XZ(img,x,z) cimg_for8Z(img,z) cimg_for8X(img,x) #define cimg_for8XC(img,x,c) cimg_for8C(img,c) cimg_for8X(img,x) #define cimg_for8YZ(img,y,z) cimg_for8Z(img,z) cimg_for8Y(img,y) #define cimg_for8YC(img,y,c) cimg_for8C(img,c) cimg_for8Y(img,y) #define cimg_for8ZC(img,z,c) cimg_for8C(img,c) cimg_for8Z(img,z) #define cimg_for8XYZ(img,x,y,z) cimg_for8Z(img,z) cimg_for8XY(img,x,y) #define cimg_for8XZC(img,x,z,c) cimg_for8C(img,c) cimg_for8XZ(img,x,z) #define cimg_for8YZC(img,y,z,c) cimg_for8C(img,c) cimg_for8YZ(img,y,z) #define cimg_for8XYZC(img,x,y,z,c) cimg_for8C(img,c) cimg_for8XYZ(img,x,y,z) #define cimg_for_in8(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p3##i = i-3<0?0:i-3, \ _p2##i = i-2<0?0:i-2, \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2, \ _n3##i = i+3>=(int)(bound)?(int)(bound)-1:i+3, \ _n4##i = i+4>=(int)(bound)?(int)(bound)-1:i+4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in8X(img,x0,x1,x) cimg_for_in8((img)._width,x0,x1,x) #define cimg_for_in8Y(img,y0,y1,y) cimg_for_in8((img)._height,y0,y1,y) #define cimg_for_in8Z(img,z0,z1,z) cimg_for_in8((img)._depth,z0,z1,z) #define cimg_for_in8C(img,c0,c1,c) cimg_for_in8((img)._spectrum,c0,c1,c) #define cimg_for_in8XY(img,x0,y0,x1,y1,x,y) cimg_for_in8Y(img,y0,y1,y) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XZ(img,x0,z0,x1,z1,x,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8XC(img,x0,c0,x1,c1,x,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8X(img,x0,x1,x) #define cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8YC(img,y0,c0,y1,c1,y,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Y(img,y0,y1,y) #define cimg_for_in8ZC(img,z0,c0,z1,c1,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8Z(img,z0,z1,z) #define cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in8Z(img,z0,z1,z) cimg_for_in8XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in8XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in8YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in8XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in8C(img,c0,c1,c) cimg_for_in8XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for9(bound,i) \ for (int i = 0, _p4##i = 0, _p3##i = 0, _p2##i = 0, _p1##i = 0, \ _n1##i = 1>=(int)(bound)?(int)(bound)-1:1, \ _n2##i = 2>=(int)(bound)?(int)(bound)-1:2, \ _n3##i = 3>=(int)(bound)?(int)(bound)-1:3, \ _n4##i = 4>=(int)(bound)?(int)(bound)-1:4; \ _n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for9X(img,x) cimg_for9((img)._width,x) #define cimg_for9Y(img,y) cimg_for9((img)._height,y) #define cimg_for9Z(img,z) cimg_for9((img)._depth,z) #define cimg_for9C(img,c) cimg_for9((img)._spectrum,c) #define cimg_for9XY(img,x,y) cimg_for9Y(img,y) cimg_for9X(img,x) #define cimg_for9XZ(img,x,z) cimg_for9Z(img,z) cimg_for9X(img,x) #define cimg_for9XC(img,x,c) cimg_for9C(img,c) cimg_for9X(img,x) #define cimg_for9YZ(img,y,z) cimg_for9Z(img,z) cimg_for9Y(img,y) #define cimg_for9YC(img,y,c) cimg_for9C(img,c) cimg_for9Y(img,y) #define cimg_for9ZC(img,z,c) cimg_for9C(img,c) cimg_for9Z(img,z) #define cimg_for9XYZ(img,x,y,z) cimg_for9Z(img,z) cimg_for9XY(img,x,y) #define cimg_for9XZC(img,x,z,c) cimg_for9C(img,c) cimg_for9XZ(img,x,z) #define cimg_for9YZC(img,y,z,c) cimg_for9C(img,c) cimg_for9YZ(img,y,z) #define cimg_for9XYZC(img,x,y,z,c) cimg_for9C(img,c) cimg_for9XYZ(img,x,y,z) #define cimg_for_in9(bound,i0,i1,i) \ for (int i = (int)(i0)<0?0:(int)(i0), \ _p4##i = i-4<0?0:i-4, \ _p3##i = i-3<0?0:i-3, \ _p2##i = i-2<0?0:i-2, \ _p1##i = i-1<0?0:i-1, \ _n1##i = i+1>=(int)(bound)?(int)(bound)-1:i+1, \ _n2##i = i+2>=(int)(bound)?(int)(bound)-1:i+2, \ _n3##i = i+3>=(int)(bound)?(int)(bound)-1:i+3, \ _n4##i = i+4>=(int)(bound)?(int)(bound)-1:i+4; \ i<=(int)(i1) && (_n4##i<(int)(bound) || _n3##i==--_n4##i || _n2##i==--_n3##i || _n1##i==--_n2##i || \ i==(_n4##i = _n3##i = _n2##i = --_n1##i)); \ _p4##i = _p3##i, _p3##i = _p2##i, _p2##i = _p1##i, _p1##i = i++, ++_n1##i, ++_n2##i, ++_n3##i, ++_n4##i) #define cimg_for_in9X(img,x0,x1,x) cimg_for_in9((img)._width,x0,x1,x) #define cimg_for_in9Y(img,y0,y1,y) cimg_for_in9((img)._height,y0,y1,y) #define cimg_for_in9Z(img,z0,z1,z) cimg_for_in9((img)._depth,z0,z1,z) #define cimg_for_in9C(img,c0,c1,c) cimg_for_in9((img)._spectrum,c0,c1,c) #define cimg_for_in9XY(img,x0,y0,x1,y1,x,y) cimg_for_in9Y(img,y0,y1,y) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XZ(img,x0,z0,x1,z1,x,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9XC(img,x0,c0,x1,c1,x,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9X(img,x0,x1,x) #define cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9YC(img,y0,c0,y1,c1,y,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Y(img,y0,y1,y) #define cimg_for_in9ZC(img,z0,c0,z1,c1,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9Z(img,z0,z1,z) #define cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) cimg_for_in9Z(img,z0,z1,z) cimg_for_in9XY(img,x0,y0,x1,y1,x,y) #define cimg_for_in9XZC(img,x0,z0,c0,x1,y1,c1,x,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9XZ(img,x0,y0,x1,y1,x,z) #define cimg_for_in9YZC(img,y0,z0,c0,y1,z1,c1,y,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9YZ(img,y0,z0,y1,z1,y,z) #define cimg_for_in9XYZC(img,x0,y0,z0,c0,x1,y1,z1,c1,x,y,z,c) cimg_for_in9C(img,c0,c1,c) cimg_for_in9XYZ(img,x0,y0,z0,x1,y1,z1,x,y,z) #define cimg_for2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for_in2x2(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ x+1>=(int)(img)._width?(img).width()-1:x+1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], \ I[2] = I[3], \ ++x, ++_n1##x) #define cimg_for3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x-1<0?0:x-1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = (T)(img)(_p1##x,y,z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[4] = (T)(img)(x,y,z,c)), \ (I[7] = (T)(img)(x,_n1##y,z,c)), \ x+1>=(int)(img)._width?(img).width()-1:x+1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) #define cimg_for4x4(img,x,y,z,c,I,T) \ cimg_for4((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width()-1:1, \ _n2##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = I[5] = (T)(img)(0,y,z,c)), \ (I[8] = I[9] = (T)(img)(0,_n1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width()-1:2); \ (_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in4x4(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in4((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(int)(img)._width?(img).width()-1:x+1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[4] = (T)(img)(_p1##x,y,z,c)), \ (I[8] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[1] = (T)(img)(x,_p1##y,z,c)), \ (I[5] = (T)(img)(x,y,z,c)), \ (I[9] = (T)(img)(x,_n1##y,z,c)), \ (I[13] = (T)(img)(x,_n2##y,z,c)), \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[6] = (T)(img)(_n1##x,y,z,c)), \ (I[10] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_n2##y,z,c)), \ x+2>=(int)(img)._width?(img).width()-1:x+2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[3] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[7] = (T)(img)(_n2##x,y,z,c)), \ (I[11] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], \ I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], \ _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for5x5(img,x,y,z,c,I,T) \ cimg_for5((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width()-1:1, \ _n2##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = I[6] = I[7] = (T)(img)(0,_p1##y,z,c)), \ (I[10] = I[11] = I[12] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = I[17] = (T)(img)(0,_n1##y,z,c)), \ (I[20] = I[21] = I[22] = (T)(img)(0,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ 2>=(img)._width?(img).width()-1:2); \ (_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for_in5x5(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in5((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p2##x = x-2<0?0:x-2, \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(int)(img)._width?(img).width()-1:x+1, \ _n2##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[5] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[10] = (T)(img)(_p2##x,y,z,c)), \ (I[15] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[11] = (T)(img)(_p1##x,y,z,c)), \ (I[16] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[7] = (T)(img)(x,_p1##y,z,c)), \ (I[12] = (T)(img)(x,y,z,c)), \ (I[17] = (T)(img)(x,_n1##y,z,c)), \ (I[22] = (T)(img)(x,_n2##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[8] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_n1##x,y,z,c)), \ (I[18] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_n2##y,z,c)), \ x+2>=(int)(img)._width?(img).width()-1:x+2); \ x<=(int)(x1) && ((_n2##x<(img).width() && ( \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n2##x,y,z,c)), \ (I[19] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_n2##y,z,c)),1)) || \ _n1##x==--_n2##x || x==(_n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], \ I[5] = I[6], I[6] = I[7], I[7] = I[8], I[8] = I[9], \ I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], \ I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], \ I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x) #define cimg_for6x6(img,x,y,z,c,I,T) \ cimg_for6((img)._height,y) for (int x = 0, \ _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width()-1:1, \ _n2##x = 2>=(img)._width?(img).width()-1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = I[7] = I[8] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = I[14] = (T)(img)(0,y,z,c)), \ (I[18] = I[19] = I[20] = (T)(img)(0,_n1##y,z,c)), \ (I[24] = I[25] = I[26] = (T)(img)(0,_n2##y,z,c)), \ (I[30] = I[31] = I[32] = (T)(img)(0,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width()-1:3); \ (_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in6x6(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in6((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)x0, \ _p2##x = x-2<0?0:x-2, \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(int)(img)._width?(img).width()-1:x+1, \ _n2##x = x+2>=(int)(img)._width?(img).width()-1:x+2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[6] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p2##x,y,z,c)), \ (I[18] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[24] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[30] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[7] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[13] = (T)(img)(_p1##x,y,z,c)), \ (I[19] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[25] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[31] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[2] = (T)(img)(x,_p2##y,z,c)), \ (I[8] = (T)(img)(x,_p1##y,z,c)), \ (I[14] = (T)(img)(x,y,z,c)), \ (I[20] = (T)(img)(x,_n1##y,z,c)), \ (I[26] = (T)(img)(x,_n2##y,z,c)), \ (I[32] = (T)(img)(x,_n3##y,z,c)), \ (I[3] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[9] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[15] = (T)(img)(_n1##x,y,z,c)), \ (I[21] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[27] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[33] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[10] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[16] = (T)(img)(_n2##x,y,z,c)), \ (I[22] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[28] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[34] = (T)(img)(_n2##x,_n3##y,z,c)), \ x+3>=(int)(img)._width?(img).width()-1:x+3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[5] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[11] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[17] = (T)(img)(_n3##x,y,z,c)), \ (I[23] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[29] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[35] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3## x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], \ I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], \ I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for7x7(img,x,y,z,c,I,T) \ cimg_for7((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=(img)._width?(img).width()-1:1, \ _n2##x = 2>=(img)._width?(img).width()-1:2, \ _n3##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = I[8] = I[9] = I[10] = (T)(img)(0,_p2##y,z,c)), \ (I[14] = I[15] = I[16] = I[17] = (T)(img)(0,_p1##y,z,c)), \ (I[21] = I[22] = I[23] = I[24] = (T)(img)(0,y,z,c)), \ (I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_n1##y,z,c)), \ (I[35] = I[36] = I[37] = I[38] = (T)(img)(0,_n2##y,z,c)), \ (I[42] = I[43] = I[44] = I[45] = (T)(img)(0,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ 3>=(img)._width?(img).width()-1:3); \ (_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for_in7x7(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in7((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x-3<0?0:x-3, \ _p2##x = x-2<0?0:x-2, \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(int)(img)._width?(img).width()-1:x+1, \ _n2##x = x+2>=(int)(img)._width?(img).width()-1:x+2, \ _n3##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[7] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[14] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[21] = (T)(img)(_p3##x,y,z,c)), \ (I[28] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[35] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[42] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[15] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[22] = (T)(img)(_p2##x,y,z,c)), \ (I[29] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[36] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[43] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[23] = (T)(img)(_p1##x,y,z,c)), \ (I[30] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[37] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[44] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[10] = (T)(img)(x,_p2##y,z,c)), \ (I[17] = (T)(img)(x,_p1##y,z,c)), \ (I[24] = (T)(img)(x,y,z,c)), \ (I[31] = (T)(img)(x,_n1##y,z,c)), \ (I[38] = (T)(img)(x,_n2##y,z,c)), \ (I[45] = (T)(img)(x,_n3##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[11] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_n1##x,y,z,c)), \ (I[32] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[39] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[46] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[19] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_n2##x,y,z,c)), \ (I[33] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[47] = (T)(img)(_n2##x,_n3##y,z,c)), \ x+3>=(int)(img)._width?(img).width()-1:x+3); \ x<=(int)(x1) && ((_n3##x<(img).width() && ( \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[27] = (T)(img)(_n3##x,y,z,c)), \ (I[34] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_n3##x,_n3##y,z,c)),1)) || \ _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], \ I[7] = I[8], I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], \ I[14] = I[15], I[15] = I[16], I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], \ I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], I[26] = I[27], \ I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], \ I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], \ I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], I[47] = I[48], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x) #define cimg_for8x8(img,x,y,z,c,I,T) \ cimg_for8((img)._height,y) for (int x = 0, \ _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width()-1:1, \ _n2##x = 2>=((img)._width)?(img).width()-1:2, \ _n3##x = 3>=((img)._width)?(img).width()-1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = I[9] = I[10] = I[11] = (T)(img)(0,_p2##y,z,c)), \ (I[16] = I[17] = I[18] = I[19] = (T)(img)(0,_p1##y,z,c)), \ (I[24] = I[25] = I[26] = I[27] = (T)(img)(0,y,z,c)), \ (I[32] = I[33] = I[34] = I[35] = (T)(img)(0,_n1##y,z,c)), \ (I[40] = I[41] = I[42] = I[43] = (T)(img)(0,_n2##y,z,c)), \ (I[48] = I[49] = I[50] = I[51] = (T)(img)(0,_n3##y,z,c)), \ (I[56] = I[57] = I[58] = I[59] = (T)(img)(0,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width()-1:4); \ (_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in8x8(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in8((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p3##x = x-3<0?0:x-3, \ _p2##x = x-2<0?0:x-2, \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(img).width()?(img).width()-1:x+1, \ _n2##x = x+2>=(img).width()?(img).width()-1:x+2, \ _n3##x = x+3>=(img).width()?(img).width()-1:x+3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[8] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[16] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[24] = (T)(img)(_p3##x,y,z,c)), \ (I[32] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[40] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[48] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[56] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[9] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[17] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[25] = (T)(img)(_p2##x,y,z,c)), \ (I[33] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[41] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[49] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[57] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[10] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[26] = (T)(img)(_p1##x,y,z,c)), \ (I[34] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[42] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[50] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[58] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[3] = (T)(img)(x,_p3##y,z,c)), \ (I[11] = (T)(img)(x,_p2##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,z,c)), \ (I[27] = (T)(img)(x,y,z,c)), \ (I[35] = (T)(img)(x,_n1##y,z,c)), \ (I[43] = (T)(img)(x,_n2##y,z,c)), \ (I[51] = (T)(img)(x,_n3##y,z,c)), \ (I[59] = (T)(img)(x,_n4##y,z,c)), \ (I[4] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[12] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[28] = (T)(img)(_n1##x,y,z,c)), \ (I[36] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[44] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[52] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[60] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[13] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[21] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[29] = (T)(img)(_n2##x,y,z,c)), \ (I[37] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[45] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[53] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[61] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[14] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[22] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[30] = (T)(img)(_n3##x,y,z,c)), \ (I[38] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[46] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[54] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[62] = (T)(img)(_n3##x,_n4##y,z,c)), \ x+4>=(img).width()?(img).width()-1:x+4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[7] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[15] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[23] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[31] = (T)(img)(_n4##x,y,z,c)), \ (I[39] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[47] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[55] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[63] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], \ I[8] = I[9], I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], \ I[16] = I[17], I[17] = I[18], I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], \ I[24] = I[25], I[25] = I[26], I[26] = I[27], I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], \ I[32] = I[33], I[33] = I[34], I[34] = I[35], I[35] = I[36], I[36] = I[37], I[37] = I[38], I[38] = I[39], \ I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], I[44] = I[45], I[45] = I[46], I[46] = I[47], \ I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], I[53] = I[54], I[54] = I[55], \ I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], I[62] = I[63], \ _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for9x9(img,x,y,z,c,I,T) \ cimg_for9((img)._height,y) for (int x = 0, \ _p4##x = 0, _p3##x = 0, _p2##x = 0, _p1##x = 0, \ _n1##x = 1>=((img)._width)?(img).width()-1:1, \ _n2##x = 2>=((img)._width)?(img).width()-1:2, \ _n3##x = 3>=((img)._width)?(img).width()-1:3, \ _n4##x = (int)( \ (I[0] = I[1] = I[2] = I[3] = I[4] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = I[10] = I[11] = I[12] = I[13] = (T)(img)(0,_p3##y,z,c)), \ (I[18] = I[19] = I[20] = I[21] = I[22] = (T)(img)(0,_p2##y,z,c)), \ (I[27] = I[28] = I[29] = I[30] = I[31] = (T)(img)(0,_p1##y,z,c)), \ (I[36] = I[37] = I[38] = I[39] = I[40] = (T)(img)(0,y,z,c)), \ (I[45] = I[46] = I[47] = I[48] = I[49] = (T)(img)(0,_n1##y,z,c)), \ (I[54] = I[55] = I[56] = I[57] = I[58] = (T)(img)(0,_n2##y,z,c)), \ (I[63] = I[64] = I[65] = I[66] = I[67] = (T)(img)(0,_n3##y,z,c)), \ (I[72] = I[73] = I[74] = I[75] = I[76] = (T)(img)(0,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ 4>=((img)._width)?(img).width()-1:4); \ (_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], \ I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], \ I[45] = I[46], I[46] = I[47], I[47] = I[48], I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], \ I[54] = I[55], I[55] = I[56], I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], \ I[63] = I[64], I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for_in9x9(img,x0,y0,x1,y1,x,y,z,c,I,T) \ cimg_for_in9((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p4##x = x-4<0?0:x-4, \ _p3##x = x-3<0?0:x-3, \ _p2##x = x-2<0?0:x-2, \ _p1##x = x-1<0?0:x-1, \ _n1##x = x+1>=(img).width()?(img).width()-1:x+1, \ _n2##x = x+2>=(img).width()?(img).width()-1:x+2, \ _n3##x = x+3>=(img).width()?(img).width()-1:x+3, \ _n4##x = (int)( \ (I[0] = (T)(img)(_p4##x,_p4##y,z,c)), \ (I[9] = (T)(img)(_p4##x,_p3##y,z,c)), \ (I[18] = (T)(img)(_p4##x,_p2##y,z,c)), \ (I[27] = (T)(img)(_p4##x,_p1##y,z,c)), \ (I[36] = (T)(img)(_p4##x,y,z,c)), \ (I[45] = (T)(img)(_p4##x,_n1##y,z,c)), \ (I[54] = (T)(img)(_p4##x,_n2##y,z,c)), \ (I[63] = (T)(img)(_p4##x,_n3##y,z,c)), \ (I[72] = (T)(img)(_p4##x,_n4##y,z,c)), \ (I[1] = (T)(img)(_p3##x,_p4##y,z,c)), \ (I[10] = (T)(img)(_p3##x,_p3##y,z,c)), \ (I[19] = (T)(img)(_p3##x,_p2##y,z,c)), \ (I[28] = (T)(img)(_p3##x,_p1##y,z,c)), \ (I[37] = (T)(img)(_p3##x,y,z,c)), \ (I[46] = (T)(img)(_p3##x,_n1##y,z,c)), \ (I[55] = (T)(img)(_p3##x,_n2##y,z,c)), \ (I[64] = (T)(img)(_p3##x,_n3##y,z,c)), \ (I[73] = (T)(img)(_p3##x,_n4##y,z,c)), \ (I[2] = (T)(img)(_p2##x,_p4##y,z,c)), \ (I[11] = (T)(img)(_p2##x,_p3##y,z,c)), \ (I[20] = (T)(img)(_p2##x,_p2##y,z,c)), \ (I[29] = (T)(img)(_p2##x,_p1##y,z,c)), \ (I[38] = (T)(img)(_p2##x,y,z,c)), \ (I[47] = (T)(img)(_p2##x,_n1##y,z,c)), \ (I[56] = (T)(img)(_p2##x,_n2##y,z,c)), \ (I[65] = (T)(img)(_p2##x,_n3##y,z,c)), \ (I[74] = (T)(img)(_p2##x,_n4##y,z,c)), \ (I[3] = (T)(img)(_p1##x,_p4##y,z,c)), \ (I[12] = (T)(img)(_p1##x,_p3##y,z,c)), \ (I[21] = (T)(img)(_p1##x,_p2##y,z,c)), \ (I[30] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[39] = (T)(img)(_p1##x,y,z,c)), \ (I[48] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[57] = (T)(img)(_p1##x,_n2##y,z,c)), \ (I[66] = (T)(img)(_p1##x,_n3##y,z,c)), \ (I[75] = (T)(img)(_p1##x,_n4##y,z,c)), \ (I[4] = (T)(img)(x,_p4##y,z,c)), \ (I[13] = (T)(img)(x,_p3##y,z,c)), \ (I[22] = (T)(img)(x,_p2##y,z,c)), \ (I[31] = (T)(img)(x,_p1##y,z,c)), \ (I[40] = (T)(img)(x,y,z,c)), \ (I[49] = (T)(img)(x,_n1##y,z,c)), \ (I[58] = (T)(img)(x,_n2##y,z,c)), \ (I[67] = (T)(img)(x,_n3##y,z,c)), \ (I[76] = (T)(img)(x,_n4##y,z,c)), \ (I[5] = (T)(img)(_n1##x,_p4##y,z,c)), \ (I[14] = (T)(img)(_n1##x,_p3##y,z,c)), \ (I[23] = (T)(img)(_n1##x,_p2##y,z,c)), \ (I[32] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[41] = (T)(img)(_n1##x,y,z,c)), \ (I[50] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[59] = (T)(img)(_n1##x,_n2##y,z,c)), \ (I[68] = (T)(img)(_n1##x,_n3##y,z,c)), \ (I[77] = (T)(img)(_n1##x,_n4##y,z,c)), \ (I[6] = (T)(img)(_n2##x,_p4##y,z,c)), \ (I[15] = (T)(img)(_n2##x,_p3##y,z,c)), \ (I[24] = (T)(img)(_n2##x,_p2##y,z,c)), \ (I[33] = (T)(img)(_n2##x,_p1##y,z,c)), \ (I[42] = (T)(img)(_n2##x,y,z,c)), \ (I[51] = (T)(img)(_n2##x,_n1##y,z,c)), \ (I[60] = (T)(img)(_n2##x,_n2##y,z,c)), \ (I[69] = (T)(img)(_n2##x,_n3##y,z,c)), \ (I[78] = (T)(img)(_n2##x,_n4##y,z,c)), \ (I[7] = (T)(img)(_n3##x,_p4##y,z,c)), \ (I[16] = (T)(img)(_n3##x,_p3##y,z,c)), \ (I[25] = (T)(img)(_n3##x,_p2##y,z,c)), \ (I[34] = (T)(img)(_n3##x,_p1##y,z,c)), \ (I[43] = (T)(img)(_n3##x,y,z,c)), \ (I[52] = (T)(img)(_n3##x,_n1##y,z,c)), \ (I[61] = (T)(img)(_n3##x,_n2##y,z,c)), \ (I[70] = (T)(img)(_n3##x,_n3##y,z,c)), \ (I[79] = (T)(img)(_n3##x,_n4##y,z,c)), \ x+4>=(img).width()?(img).width()-1:x+4); \ x<=(int)(x1) && ((_n4##x<(img).width() && ( \ (I[8] = (T)(img)(_n4##x,_p4##y,z,c)), \ (I[17] = (T)(img)(_n4##x,_p3##y,z,c)), \ (I[26] = (T)(img)(_n4##x,_p2##y,z,c)), \ (I[35] = (T)(img)(_n4##x,_p1##y,z,c)), \ (I[44] = (T)(img)(_n4##x,y,z,c)), \ (I[53] = (T)(img)(_n4##x,_n1##y,z,c)), \ (I[62] = (T)(img)(_n4##x,_n2##y,z,c)), \ (I[71] = (T)(img)(_n4##x,_n3##y,z,c)), \ (I[80] = (T)(img)(_n4##x,_n4##y,z,c)),1)) || \ _n3##x==--_n4##x || _n2##x==--_n3##x || _n1##x==--_n2##x || x==(_n4##x = _n3##x = _n2##x = --_n1##x)); \ I[0] = I[1], I[1] = I[2], I[2] = I[3], I[3] = I[4], I[4] = I[5], I[5] = I[6], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[11] = I[12], I[12] = I[13], I[13] = I[14], I[14] = I[15], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[20] = I[21], I[21] = I[22], I[22] = I[23], I[23] = I[24], I[24] = I[25], I[25] = I[26], \ I[27] = I[28], I[28] = I[29], I[29] = I[30], I[30] = I[31], I[31] = I[32], I[32] = I[33], I[33] = I[34], I[34] = I[35], \ I[36] = I[37], I[37] = I[38], I[38] = I[39], I[39] = I[40], I[40] = I[41], I[41] = I[42], I[42] = I[43], I[43] = I[44], \ I[45] = I[46], I[46] = I[47], I[47] = I[48], I[48] = I[49], I[49] = I[50], I[50] = I[51], I[51] = I[52], I[52] = I[53], \ I[54] = I[55], I[55] = I[56], I[56] = I[57], I[57] = I[58], I[58] = I[59], I[59] = I[60], I[60] = I[61], I[61] = I[62], \ I[63] = I[64], I[64] = I[65], I[65] = I[66], I[66] = I[67], I[67] = I[68], I[68] = I[69], I[69] = I[70], I[70] = I[71], \ I[72] = I[73], I[73] = I[74], I[74] = I[75], I[75] = I[76], I[76] = I[77], I[77] = I[78], I[78] = I[79], I[79] = I[80], \ _p4##x = _p3##x, _p3##x = _p2##x, _p2##x = _p1##x, _p1##x = x++, ++_n1##x, ++_n2##x, ++_n3##x, ++_n4##x) #define cimg_for2x2x2(img,x,y,z,c,I,T) \ cimg_for2((img)._depth,z) cimg_for2((img)._height,y) for (int x = 0, \ _n1##x = (int)( \ (I[0] = (T)(img)(0,y,z,c)), \ (I[2] = (T)(img)(0,_n1##y,z,c)), \ (I[4] = (T)(img)(0,y,_n1##z,c)), \ (I[6] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for_in2x2x2(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in2((img)._depth,z0,z1,z) cimg_for_in2((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _n1##x = (int)( \ (I[0] = (T)(img)(x,y,z,c)), \ (I[2] = (T)(img)(x,_n1##y,z,c)), \ (I[4] = (T)(img)(x,y,_n1##z,c)), \ (I[6] = (T)(img)(x,_n1##y,_n1##z,c)), \ x+1>=(int)(img)._width?(img).width()-1:x+1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[1] = (T)(img)(_n1##x,y,z,c)), \ (I[3] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[7] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[2] = I[3], I[4] = I[5], I[6] = I[7], \ ++x, ++_n1##x) #define cimg_for3x3x3(img,x,y,z,c,I,T) \ cimg_for3((img)._depth,z) cimg_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = I[4] = (T)(img)(0,y,_p1##z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,_p1##z,c)), \ (I[9] = I[10] = (T)(img)(0,_p1##y,z,c)), \ (I[12] = I[13] = (T)(img)(0,y,z,c)), \ (I[15] = I[16] = (T)(img)(0,_n1##y,z,c)), \ (I[18] = I[19] = (T)(img)(0,_p1##y,_n1##z,c)), \ (I[21] = I[22] = (T)(img)(0,y,_n1##z,c)), \ (I[24] = I[25] = (T)(img)(0,_n1##y,_n1##z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimg_for_in3x3x3(img,x0,y0,z0,x1,y1,z1,x,y,z,c,I,T) \ cimg_for_in3((img)._depth,z0,z1,z) cimg_for_in3((img)._height,y0,y1,y) for (int x = (int)(x0)<0?0:(int)(x0), \ _p1##x = x-1<0?0:x-1, \ _n1##x = (int)( \ (I[0] = (T)(img)(_p1##x,_p1##y,_p1##z,c)), \ (I[3] = (T)(img)(_p1##x,y,_p1##z,c)), \ (I[6] = (T)(img)(_p1##x,_n1##y,_p1##z,c)), \ (I[9] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[12] = (T)(img)(_p1##x,y,z,c)), \ (I[15] = (T)(img)(_p1##x,_n1##y,z,c)), \ (I[18] = (T)(img)(_p1##x,_p1##y,_n1##z,c)), \ (I[21] = (T)(img)(_p1##x,y,_n1##z,c)), \ (I[24] = (T)(img)(_p1##x,_n1##y,_n1##z,c)), \ (I[1] = (T)(img)(x,_p1##y,_p1##z,c)), \ (I[4] = (T)(img)(x,y,_p1##z,c)), \ (I[7] = (T)(img)(x,_n1##y,_p1##z,c)), \ (I[10] = (T)(img)(x,_p1##y,z,c)), \ (I[13] = (T)(img)(x,y,z,c)), \ (I[16] = (T)(img)(x,_n1##y,z,c)), \ (I[19] = (T)(img)(x,_p1##y,_n1##z,c)), \ (I[22] = (T)(img)(x,y,_n1##z,c)), \ (I[25] = (T)(img)(x,_n1##y,_n1##z,c)), \ x+1>=(int)(img)._width?(img).width()-1:x+1); \ x<=(int)(x1) && ((_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,_p1##z,c)), \ (I[5] = (T)(img)(_n1##x,y,_p1##z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,_p1##z,c)), \ (I[11] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[14] = (T)(img)(_n1##x,y,z,c)), \ (I[17] = (T)(img)(_n1##x,_n1##y,z,c)), \ (I[20] = (T)(img)(_n1##x,_p1##y,_n1##z,c)), \ (I[23] = (T)(img)(_n1##x,y,_n1##z,c)), \ (I[26] = (T)(img)(_n1##x,_n1##y,_n1##z,c)),1)) || \ x==--_n1##x); \ I[0] = I[1], I[1] = I[2], I[3] = I[4], I[4] = I[5], I[6] = I[7], I[7] = I[8], \ I[9] = I[10], I[10] = I[11], I[12] = I[13], I[13] = I[14], I[15] = I[16], I[16] = I[17], \ I[18] = I[19], I[19] = I[20], I[21] = I[22], I[22] = I[23], I[24] = I[25], I[25] = I[26], \ _p1##x = x++, ++_n1##x) #define cimglist_for(list,l) for (int l = 0; l<(int)(list)._width; ++l) #define cimglist_for_in(list,l0,l1,l) \ for (int l = (int)(l0)<0?0:(int)(l0), _max##l = (unsigned int)l1<(list)._width?(int)(l1):(int)(list)._width-1; l<=_max##l; ++l) #define cimglist_apply(list,fn) cimglist_for(list,__##fn) (list)[__##fn].fn // Macros used to display error messages when exceptions are thrown. // You should not use these macros is your own code. #define _cimgdisplay_instance "[instance(%u,%u,%u,%c%s%c)] CImgDisplay::" #define cimgdisplay_instance _width,_height,_normalization,_title?'\"':'[',_title?_title:"untitled",_title?'\"':']' #define _cimg_instance "[instance(%u,%u,%u,%u,%p,%sshared)] CImg<%s>::" #define cimg_instance _width,_height,_depth,_spectrum,_data,_is_shared?"":"non-",pixel_type() #define _cimglist_instance "[instance(%u,%u,%p)] CImgList<%s>::" #define cimglist_instance _width,_allocated_width,_data,pixel_type() /*------------------------------------------------ # # # Define cimg_library:: namespace # # -------------------------------------------------*/ //! Contains <i>all classes and functions</i> of the \CImg library. /** This namespace is defined to avoid functions and class names collisions that could happen with the inclusion of other C++ header files. Anyway, it should not happen often and you should reasonnably start most of your \CImg-based programs with \code #include "CImg.h" using namespace cimg_library; \endcode to simplify the declaration of \CImg Library objects afterwards. **/ namespace cimg_library_suffixed { // Declare the four classes of the CImg Library. template<typename T=float> struct CImg; template<typename T=float> struct CImgList; struct CImgDisplay; struct CImgException; // Declare cimg:: namespace. // This is an uncomplete namespace definition here. It only contains some // necessary stuffs to ensure a correct declaration order of the classes and functions // defined afterwards. namespace cimg { // Define ascii sequences for colored terminal output. #ifdef cimg_use_vt100 const char t_normal[] = { 0x1b, '[', '0', ';', '0', ';', '0', 'm', 0 }; const char t_black[] = { 0x1b, '[', '0', ';', '3', '0', ';', '5', '9', 'm', 0 }; const char t_red[] = { 0x1b, '[', '0', ';', '3', '1', ';', '5', '9', 'm', 0 }; const char t_green[] = { 0x1b, '[', '0', ';', '3', '2', ';', '5', '9', 'm', 0 }; const char t_yellow[] = { 0x1b, '[', '0', ';', '3', '3', ';', '5', '9', 'm', 0 }; const char t_blue[] = { 0x1b, '[', '0', ';', '3', '4', ';', '5', '9', 'm', 0 }; const char t_magenta[] = { 0x1b, '[', '0', ';', '3', '5', ';', '5', '9', 'm', 0 }; const char t_cyan[] = { 0x1b, '[', '0', ';', '3', '6', ';', '5', '9', 'm', 0 }; const char t_white[] = { 0x1b, '[', '0', ';', '3', '7', ';', '5', '9', 'm', 0 }; const char t_bold[] = { 0x1b, '[', '1', 'm', 0 }; const char t_underscore[] = { 0x1b, '[', '4', 'm', 0 }; #else const char t_normal[] = { 0 }; const char *const t_black = cimg::t_normal, *const t_red = cimg::t_normal, *const t_green = cimg::t_normal, *const t_yellow = cimg::t_normal, *const t_blue = cimg::t_normal, *const t_magenta = cimg::t_normal, *const t_cyan = cimg::t_normal, *const t_white = cimg::t_normal, *const t_bold = cimg::t_normal, *const t_underscore = cimg::t_normal; #endif inline std::FILE* output(std::FILE *file=0); inline void info(); //! Avoid warning messages due to unused parameters. Do nothing actually. template<typename T> inline void unused(const T&, ...) {} inline unsigned int& _exception_mode(const unsigned int value, const bool is_set) { static unsigned int mode = cimg_verbosity; if (is_set) mode = value; return mode; } //! Set current \CImg exception mode. /** The way error messages are handled by \CImg can be changed dynamically, using this function. \param mode Desired exception mode. Possible values are: - \c 0: Hide library messages (quiet mode). - \c 1: Print library messages on the console. - \c 2: Display library messages on a dialog window (default behavior). - \c 3: Do as \c 1 + add extra debug warnings (slow down the code!). - \c 4: Do as \c 2 + add extra debug warnings (slow down the code!). **/ inline unsigned int& exception_mode(const unsigned int mode) { return _exception_mode(mode,true); } //! Return current \CImg exception mode. /** \note By default, return the value of configuration macro \c cimg_verbosity **/ inline unsigned int& exception_mode() { return _exception_mode(0,false); } inline int dialog(const char *const title, const char *const msg, const char *const button1_label="OK", const char *const button2_label=0, const char *const button3_label=0, const char *const button4_label=0, const char *const button5_label=0, const char *const button6_label=0, const bool centering=false); inline double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0); } /*--------------------------------------- # # Define the CImgException structures # --------------------------------------*/ //! Instances of \c CImgException are thrown when errors are encountered in a \CImg function call. /** \par Overview CImgException is the base class of all exceptions thrown by \CImg. CImgException is never thrown itself. Derived classes that specify the type of errord are thrown instead. These derived classes can be: - \b CImgArgumentException: Thrown when one argument of a called \CImg function is invalid. This is probably one of the most thrown exception by \CImg. For instance, the following example throws a \c CImgArgumentException: \code CImg<float> img(100,100,1,3); // Define a 100x100 color image with float-valued pixels. img.mirror('e'); // Try to mirror image along the (non-existing) 'e'-axis. \endcode - \b CImgDisplayException: Thrown when something went wrong during the display of images in CImgDisplay instances. - \b CImgInstanceException: Thrown when an instance associated to a called \CImg method does not fit the function requirements. For instance, the following example throws a \c CImgInstanceException: \code const CImg<float> img; // Define an empty image. const float value = img.at(0); // Try to read first pixel value (does not exist). \endcode - \b CImgIOException: Thrown when an error occured when trying to load or save image files. This happens when trying to read files that do not exist or with invalid formats. For instance, the following example throws a \c CImgIOException: \code const CImg<float> img("missing_file.jpg"); // Try to load a file that does not exist. \endcode - \b CImgWarningException: Thrown only if configuration macro \c cimg_strict_warnings is set, and when a \CImg function has to display a warning message (see cimg::warn()). It is not recommended to throw CImgException instances by yourself, since they are expected to be thrown only by \CImg. When an error occurs in a library function call, \CImg may display error messages on the screen or on the standard output, depending on the current \CImg exception mode. The \CImg exception mode can be get and set by functions cimg::exception_mode() and cimg::exception_mode(unsigned int). \par Exceptions handling In all cases, when an error occurs in \CImg, an instance of the corresponding exception class is thrown. This may lead the program to break (this is the default behavior), but you can bypass this behavior by handling the exceptions by yourself, using a usual <tt>try { ... } catch () { ... }</tt> bloc, as in the following example: \code #define "CImg.h" using namespace cimg_library; int main() { cimg::exception_mode(0); // Enable quiet exception mode. try { ... // Here, do what you want to stress the CImg library. } catch (CImgException &e) { // You succeeded: something went wrong! std::fprintf(stderr,"CImg Library Error: %s",e.what()); // Display your custom error message. ... // Do what you want now to save the ship! } } \endcode **/ struct CImgException : public std::exception { #define _cimg_exception_err(etype,disp_flag) \ std::va_list ap; va_start(ap,format); cimg_vsnprintf(_message,sizeof(_message),format,ap); va_end(ap); \ if (cimg::exception_mode()) { \ std::fprintf(cimg::output(),"\n%s[CImg] *** %s ***%s %s\n",cimg::t_red,etype,cimg::t_normal,_message); \ if (cimg_display && disp_flag && !(cimg::exception_mode()%2)) try { cimg::dialog(etype,_message,"Abort"); } catch (CImgException&) {} \ if (cimg::exception_mode()>=3) cimg_library_suffixed::cimg::info(); \ } char _message[16384]; CImgException() { *_message = 0; } CImgException(const char *const format, ...) { _cimg_exception_err("CImgException",true); } //! Return a C-string containing the error message associated to the thrown exception. const char *what() const throw() { return _message; } }; // The CImgInstanceException class is used to throw an exception related // to an invalid instance encountered in a library function call. struct CImgInstanceException : public CImgException { CImgInstanceException(const char *const format, ...) { _cimg_exception_err("CImgInstanceException",true); } }; // The CImgArgumentException class is used to throw an exception related // to invalid arguments encountered in a library function call. struct CImgArgumentException : public CImgException { CImgArgumentException(const char *const format, ...) { _cimg_exception_err("CImgArgumentException",true); } }; // The CImgIOException class is used to throw an exception related // to input/output file problems encountered in a library function call. struct CImgIOException : public CImgException { CImgIOException(const char *const format, ...) { _cimg_exception_err("CImgIOException",true); } }; // The CImgDisplayException class is used to throw an exception related // to display problems encountered in a library function call. struct CImgDisplayException : public CImgException { CImgDisplayException(const char *const format, ...) { _cimg_exception_err("CImgDisplayException",false); } }; // The CImgWarningException class is used to throw an exception for warnings // encountered in a library function call. struct CImgWarningException : public CImgException { CImgWarningException(const char *const format, ...) { _cimg_exception_err("CImgWarningException",false); } }; /*------------------------------------- # # Define cimg:: namespace # -----------------------------------*/ //! Contains \a low-level functions and variables of the \CImg Library. /** Most of the functions and variables within this namespace are used by the \CImg library for low-level operations. You may use them to access specific const values or environment variables internally used by \CImg. \warning Never write <tt>using namespace cimg_library::cimg;</tt> in your source code. Lot of functions in the <tt>cimg:: namespace</tt> have the same names as standard C functions that may be defined in the global namespace <tt>::</tt>. **/ namespace cimg { // Define traits that will be used to determine the best data type to work in CImg functions. // template<typename T> struct type { static const char* string() { static const char* s[] = { "unknown", "unknown8", "unknown16", "unknown24", "unknown32", "unknown40", "unknown48", "unknown56", "unknown64", "unknown72", "unknown80", "unknown88", "unknown96", "unknown104", "unknown112", "unknown120", "unknown128" }; return s[(sizeof(T)<17)?sizeof(T):0]; } static bool is_float() { return false; } static bool is_inf(const T) { return false; } static bool is_nan(const T) { return false; } static T min() { return (T)-1>0?(T)0:(T)-1<<(8*sizeof(T)-1); } static T max() { return (T)-1>0?(T)-1:~((T)-1<<(8*sizeof(T)-1)); } static T inf() { return max(); } static T cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(T)val; } static const char* format() { return "%s"; } static const char* format(const T val) { static const char *const s = "unknown"; cimg::unused(val); return s; } }; template<> struct type<bool> { static const char* string() { static const char *const s = "bool"; return s; } static bool is_float() { return false; } static bool is_inf(const bool) { return false; } static bool is_nan(const bool) { return false; } static bool min() { return false; } static bool max() { return true; } static bool inf() { return max(); } static bool is_inf() { return false; } static bool cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(bool)val; } static const char* format() { return "%s"; } static const char* format(const bool val) { static const char* s[] = { "false", "true" }; return s[val?1:0]; } }; template<> struct type<unsigned char> { static const char* string() { static const char *const s = "unsigned char"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned char) { return false; } static bool is_nan(const unsigned char) { return false; } static unsigned char min() { return 0; } static unsigned char max() { return (unsigned char)~0U; } static unsigned char inf() { return max(); } static unsigned char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned char)val; } static const char* format() { return "%u"; } static unsigned int format(const unsigned char val) { return (unsigned int)val; } }; template<> struct type<char> { static const char* string() { static const char *const s = "char"; return s; } static bool is_float() { return false; } static bool is_inf(const char) { return false; } static bool is_nan(const char) { return false; } static char min() { return (char)(-1L<<(8*sizeof(char)-1)); } static char max() { return (char)~((char)(-1L<<(8*sizeof(char)-1))); } static char inf() { return max(); } static char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(char)val; } static const char* format() { return "%d"; } static int format(const char val) { return (int)val; } }; template<> struct type<signed char> { static const char* string() { static const char *const s = "signed char"; return s; } static bool is_float() { return false; } static bool is_inf(const signed char) { return false; } static bool is_nan(const signed char) { return false; } static signed char min() { return (signed char)(-1L<<(8*sizeof(signed char)-1)); } static signed char max() { return ~((signed char)(-1L<<(8*sizeof(signed char)-1))); } static signed char inf() { return max(); } static signed char cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(signed char)val; } static const char* format() { return "%d"; } static unsigned int format(const signed char val) { return (int)val; } }; template<> struct type<unsigned short> { static const char* string() { static const char *const s = "unsigned short"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned short) { return false; } static bool is_nan(const unsigned short) { return false; } static unsigned short min() { return 0; } static unsigned short max() { return (unsigned short)~0U; } static unsigned short inf() { return max(); } static unsigned short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned short)val; } static const char* format() { return "%u"; } static unsigned int format(const unsigned short val) { return (unsigned int)val; } }; template<> struct type<short> { static const char* string() { static const char *const s = "short"; return s; } static bool is_float() { return false; } static bool is_inf(const short) { return false; } static bool is_nan(const short) { return false; } static short min() { return (short)(-1L<<(8*sizeof(short)-1)); } static short max() { return ~((short)(-1L<<(8*sizeof(short)-1))); } static short inf() { return max(); } static short cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(short)val; } static const char* format() { return "%d"; } static int format(const short val) { return (int)val; } }; template<> struct type<unsigned int> { static const char* string() { static const char *const s = "unsigned int"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned int) { return false; } static bool is_nan(const unsigned int) { return false; } static unsigned int min() { return 0; } static unsigned int max() { return (unsigned int)~0U; } static unsigned int inf() { return max(); } static unsigned int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned int)val; } static const char* format() { return "%u"; } static unsigned int format(const unsigned int val) { return val; } }; template<> struct type<int> { static const char* string() { static const char *const s = "int"; return s; } static bool is_float() { return false; } static bool is_inf(const int) { return false; } static bool is_nan(const int) { return false; } static int min() { return (int)(-1L<<(8*sizeof(int)-1)); } static int max() { return ~((int)(-1L<<(8*sizeof(int)-1))); } static int inf() { return max(); } static int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(int)val; } static const char* format() { return "%d"; } static int format(const int val) { return val; } }; template<> struct type<unsigned long> { static const char* string() { static const char *const s = "unsigned long"; return s; } static bool is_float() { return false; } static bool is_inf(const unsigned long) { return false; } static bool is_nan(const unsigned long) { return false; } static unsigned long min() { return 0; } static unsigned long max() { return (unsigned long)~0UL; } static unsigned long inf() { return max(); } static unsigned long cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(unsigned long)val; } static const char* format() { return "%lu"; } static unsigned long format(const unsigned long val) { return val; } }; template<> struct type<long> { static const char* string() { static const char *const s = "long"; return s; } static bool is_float() { return false; } static bool is_inf(const long) { return false; } static bool is_nan(const long) { return false; } static long min() { return (long)(-1L<<(8*sizeof(long)-1)); } static long max() { return ~((long)(-1L<<(8*sizeof(long)-1))); } static long inf() { return max(); } static long cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(long)val; } static const char* format() { return "%ld"; } static long format(const long val) { return val; } }; template<> struct type<double> { static const char* string() { static const char *const s = "double"; return s; } static bool is_float() { return true; } static bool is_inf(const double val) { return !is_nan(val) && val+1==val; } static bool is_nan(const double val) { return !(val<=0 || val>=0); } static double min() { return -1.7E308; } static double max() { return 1.7E308; } static double inf() { return max()*max(); } static double nan() { static const double val_nan = -std::sqrt(-1.0); return val_nan; } static double cut(const double val) { return val<min()?min():val>max()?max():val; } static const char* format() { return "%.16g"; } static double format(const double val) { return val; } }; template<> struct type<float> { static const char* string() { static const char *const s = "float"; return s; } static bool is_float() { return true; } static bool is_inf(const float val) { return cimg::type<double>::is_inf((double)val); } static bool is_nan(const float val) { return cimg::type<double>::is_nan((double)val); } static float min() { return -3.4E38f; } static float max() { return 3.4E38f; } static float inf() { return (float)cimg::type<double>::inf(); } static float nan() { return (float)cimg::type<double>::nan(); } static float cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(float)val; } static const char* format() { return "%.16g"; } static double format(const float val) { return (double)val; } }; template<typename T, typename t> struct superset { typedef T type; }; template<> struct superset<bool,unsigned char> { typedef unsigned char type; }; template<> struct superset<bool,char> { typedef char type; }; template<> struct superset<bool,signed char> { typedef signed char type; }; template<> struct superset<bool,unsigned short> { typedef unsigned short type; }; template<> struct superset<bool,short> { typedef short type; }; template<> struct superset<bool,unsigned int> { typedef unsigned int type; }; template<> struct superset<bool,int> { typedef int type; }; template<> struct superset<bool,unsigned long> { typedef unsigned long type; }; template<> struct superset<bool,long> { typedef long type; }; template<> struct superset<bool,float> { typedef float type; }; template<> struct superset<bool,double> { typedef double type; }; template<> struct superset<unsigned char,char> { typedef short type; }; template<> struct superset<unsigned char,signed char> { typedef short type; }; template<> struct superset<unsigned char,unsigned short> { typedef unsigned short type; }; template<> struct superset<unsigned char,short> { typedef short type; }; template<> struct superset<unsigned char,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned char,int> { typedef int type; }; template<> struct superset<unsigned char,unsigned long> { typedef unsigned long type; }; template<> struct superset<unsigned char,long> { typedef long type; }; template<> struct superset<unsigned char,float> { typedef float type; }; template<> struct superset<unsigned char,double> { typedef double type; }; template<> struct superset<signed char,unsigned char> { typedef short type; }; template<> struct superset<signed char,char> { typedef short type; }; template<> struct superset<signed char,unsigned short> { typedef int type; }; template<> struct superset<signed char,short> { typedef short type; }; template<> struct superset<signed char,unsigned int> { typedef long type; }; template<> struct superset<signed char,int> { typedef int type; }; template<> struct superset<signed char,unsigned long> { typedef long type; }; template<> struct superset<signed char,long> { typedef long type; }; template<> struct superset<signed char,float> { typedef float type; }; template<> struct superset<signed char,double> { typedef double type; }; template<> struct superset<char,unsigned char> { typedef short type; }; template<> struct superset<char,signed char> { typedef short type; }; template<> struct superset<char,unsigned short> { typedef int type; }; template<> struct superset<char,short> { typedef short type; }; template<> struct superset<char,unsigned int> { typedef long type; }; template<> struct superset<char,int> { typedef int type; }; template<> struct superset<char,unsigned long> { typedef long type; }; template<> struct superset<char,long> { typedef long type; }; template<> struct superset<char,float> { typedef float type; }; template<> struct superset<char,double> { typedef double type; }; template<> struct superset<unsigned short,char> { typedef int type; }; template<> struct superset<unsigned short,signed char> { typedef int type; }; template<> struct superset<unsigned short,short> { typedef int type; }; template<> struct superset<unsigned short,unsigned int> { typedef unsigned int type; }; template<> struct superset<unsigned short,int> { typedef int type; }; template<> struct superset<unsigned short,unsigned long> { typedef unsigned long type; }; template<> struct superset<unsigned short,long> { typedef long type; }; template<> struct superset<unsigned short,float> { typedef float type; }; template<> struct superset<unsigned short,double> { typedef double type; }; template<> struct superset<short,unsigned short> { typedef int type; }; template<> struct superset<short,unsigned int> { typedef long type; }; template<> struct superset<short,int> { typedef int type; }; template<> struct superset<short,unsigned long> { typedef long type; }; template<> struct superset<short,long> { typedef long type; }; template<> struct superset<short,float> { typedef float type; }; template<> struct superset<short,double> { typedef double type; }; template<> struct superset<unsigned int,char> { typedef long type; }; template<> struct superset<unsigned int,signed char> { typedef long type; }; template<> struct superset<unsigned int,short> { typedef long type; }; template<> struct superset<unsigned int,int> { typedef long type; }; template<> struct superset<unsigned int,unsigned long> { typedef unsigned long type; }; template<> struct superset<unsigned int,long> { typedef long type; }; template<> struct superset<unsigned int,float> { typedef float type; }; template<> struct superset<unsigned int,double> { typedef double type; }; template<> struct superset<int,unsigned int> { typedef long type; }; template<> struct superset<int,unsigned long> { typedef long type; }; template<> struct superset<int,long> { typedef long type; }; template<> struct superset<int,float> { typedef float type; }; template<> struct superset<int,double> { typedef double type; }; template<> struct superset<unsigned long,char> { typedef long type; }; template<> struct superset<unsigned long,signed char> { typedef long type; }; template<> struct superset<unsigned long,short> { typedef long type; }; template<> struct superset<unsigned long,int> { typedef long type; }; template<> struct superset<unsigned long,long> { typedef long type; }; template<> struct superset<unsigned long,float> { typedef float type; }; template<> struct superset<unsigned long,double> { typedef double type; }; template<> struct superset<long,float> { typedef float type; }; template<> struct superset<long,double> { typedef double type; }; template<> struct superset<float,double> { typedef double type; }; template<typename t1, typename t2, typename t3> struct superset2 { typedef typename superset<t1, typename superset<t2,t3>::type>::type type; }; template<typename t1, typename t2, typename t3, typename t4> struct superset3 { typedef typename superset<t1, typename superset2<t2,t3,t4>::type>::type type; }; template<typename t1, typename t2> struct last { typedef t2 type; }; #define _cimg_Tt typename cimg::superset<T,t>::type #define _cimg_Tfloat typename cimg::superset<T,float>::type #define _cimg_Ttfloat typename cimg::superset2<T,t,float>::type #define _cimg_Ttdouble typename cimg::superset2<T,t,double>::type // Define variables used internally by CImg. #if cimg_display==1 struct X11_info { volatile unsigned int nb_wins; pthread_t* event_thread; CImgDisplay* wins[1024]; Display* display; unsigned int nb_bits; bool is_blue_first; bool is_shm_enabled; bool byte_order; #ifdef cimg_use_xrandr XRRScreenSize *resolutions; Rotation curr_rotation; unsigned int curr_resolution; unsigned int nb_resolutions; #endif X11_info():nb_wins(0),event_thread(0),display(0), nb_bits(0),is_blue_first(false),is_shm_enabled(false),byte_order(false) { #ifdef cimg_use_xrandr resolutions = 0; curr_rotation = 0; curr_resolution = nb_resolutions = 0; #endif } }; #if defined(cimg_module) X11_info& X11_attr(); #elif defined(cimg_main) X11_info& X11_attr() { static X11_info val; return val; } #else inline X11_info& X11_attr() { static X11_info val; return val; } #endif #elif cimg_display==2 struct Win32_info { HANDLE wait_event; Win32_info() { wait_event = CreateEvent(0,FALSE,FALSE,0); } }; #if defined(cimg_module) Win32_info& Win32_attr(); #elif defined(cimg_main) Win32_info& Win32_attr() { static Win32_info val; return val; } #else inline Win32_info& Win32_attr() { static Win32_info val; return val; } #endif #endif #if defined(cimg_use_magick) static struct Magick_info { Magick_info() { Magick::InitializeMagick(""); } } _Magick_info; #endif #if cimg_display==1 // Define keycodes for X11-based graphical systems. const unsigned int keyESC = XK_Escape; const unsigned int keyF1 = XK_F1; const unsigned int keyF2 = XK_F2; const unsigned int keyF3 = XK_F3; const unsigned int keyF4 = XK_F4; const unsigned int keyF5 = XK_F5; const unsigned int keyF6 = XK_F6; const unsigned int keyF7 = XK_F7; const unsigned int keyF8 = XK_F8; const unsigned int keyF9 = XK_F9; const unsigned int keyF10 = XK_F10; const unsigned int keyF11 = XK_F11; const unsigned int keyF12 = XK_F12; const unsigned int keyPAUSE = XK_Pause; const unsigned int key1 = XK_1; const unsigned int key2 = XK_2; const unsigned int key3 = XK_3; const unsigned int key4 = XK_4; const unsigned int key5 = XK_5; const unsigned int key6 = XK_6; const unsigned int key7 = XK_7; const unsigned int key8 = XK_8; const unsigned int key9 = XK_9; const unsigned int key0 = XK_0; const unsigned int keyBACKSPACE = XK_BackSpace; const unsigned int keyINSERT = XK_Insert; const unsigned int keyHOME = XK_Home; const unsigned int keyPAGEUP = XK_Page_Up; const unsigned int keyTAB = XK_Tab; const unsigned int keyQ = XK_q; const unsigned int keyW = XK_w; const unsigned int keyE = XK_e; const unsigned int keyR = XK_r; const unsigned int keyT = XK_t; const unsigned int keyY = XK_y; const unsigned int keyU = XK_u; const unsigned int keyI = XK_i; const unsigned int keyO = XK_o; const unsigned int keyP = XK_p; const unsigned int keyDELETE = XK_Delete; const unsigned int keyEND = XK_End; const unsigned int keyPAGEDOWN = XK_Page_Down; const unsigned int keyCAPSLOCK = XK_Caps_Lock; const unsigned int keyA = XK_a; const unsigned int keyS = XK_s; const unsigned int keyD = XK_d; const unsigned int keyF = XK_f; const unsigned int keyG = XK_g; const unsigned int keyH = XK_h; const unsigned int keyJ = XK_j; const unsigned int keyK = XK_k; const unsigned int keyL = XK_l; const unsigned int keyENTER = XK_Return; const unsigned int keySHIFTLEFT = XK_Shift_L; const unsigned int keyZ = XK_z; const unsigned int keyX = XK_x; const unsigned int keyC = XK_c; const unsigned int keyV = XK_v; const unsigned int keyB = XK_b; const unsigned int keyN = XK_n; const unsigned int keyM = XK_m; const unsigned int keySHIFTRIGHT = XK_Shift_R; const unsigned int keyARROWUP = XK_Up; const unsigned int keyCTRLLEFT = XK_Control_L; const unsigned int keyAPPLEFT = XK_Super_L; const unsigned int keyALT = XK_Alt_L; const unsigned int keySPACE = XK_space; const unsigned int keyALTGR = XK_Alt_R; const unsigned int keyAPPRIGHT = XK_Super_R; const unsigned int keyMENU = XK_Menu; const unsigned int keyCTRLRIGHT = XK_Control_R; const unsigned int keyARROWLEFT = XK_Left; const unsigned int keyARROWDOWN = XK_Down; const unsigned int keyARROWRIGHT = XK_Right; const unsigned int keyPAD0 = XK_KP_0; const unsigned int keyPAD1 = XK_KP_1; const unsigned int keyPAD2 = XK_KP_2; const unsigned int keyPAD3 = XK_KP_3; const unsigned int keyPAD4 = XK_KP_4; const unsigned int keyPAD5 = XK_KP_5; const unsigned int keyPAD6 = XK_KP_6; const unsigned int keyPAD7 = XK_KP_7; const unsigned int keyPAD8 = XK_KP_8; const unsigned int keyPAD9 = XK_KP_9; const unsigned int keyPADADD = XK_KP_Add; const unsigned int keyPADSUB = XK_KP_Subtract; const unsigned int keyPADMUL = XK_KP_Multiply; const unsigned int keyPADDIV = XK_KP_Divide; #elif cimg_display==2 // Define keycodes for Windows. const unsigned int keyESC = VK_ESCAPE; const unsigned int keyF1 = VK_F1; const unsigned int keyF2 = VK_F2; const unsigned int keyF3 = VK_F3; const unsigned int keyF4 = VK_F4; const unsigned int keyF5 = VK_F5; const unsigned int keyF6 = VK_F6; const unsigned int keyF7 = VK_F7; const unsigned int keyF8 = VK_F8; const unsigned int keyF9 = VK_F9; const unsigned int keyF10 = VK_F10; const unsigned int keyF11 = VK_F11; const unsigned int keyF12 = VK_F12; const unsigned int keyPAUSE = VK_PAUSE; const unsigned int key1 = '1'; const unsigned int key2 = '2'; const unsigned int key3 = '3'; const unsigned int key4 = '4'; const unsigned int key5 = '5'; const unsigned int key6 = '6'; const unsigned int key7 = '7'; const unsigned int key8 = '8'; const unsigned int key9 = '9'; const unsigned int key0 = '0'; const unsigned int keyBACKSPACE = VK_BACK; const unsigned int keyINSERT = VK_INSERT; const unsigned int keyHOME = VK_HOME; const unsigned int keyPAGEUP = VK_PRIOR; const unsigned int keyTAB = VK_TAB; const unsigned int keyQ = 'Q'; const unsigned int keyW = 'W'; const unsigned int keyE = 'E'; const unsigned int keyR = 'R'; const unsigned int keyT = 'T'; const unsigned int keyY = 'Y'; const unsigned int keyU = 'U'; const unsigned int keyI = 'I'; const unsigned int keyO = 'O'; const unsigned int keyP = 'P'; const unsigned int keyDELETE = VK_DELETE; const unsigned int keyEND = VK_END; const unsigned int keyPAGEDOWN = VK_NEXT; const unsigned int keyCAPSLOCK = VK_CAPITAL; const unsigned int keyA = 'A'; const unsigned int keyS = 'S'; const unsigned int keyD = 'D'; const unsigned int keyF = 'F'; const unsigned int keyG = 'G'; const unsigned int keyH = 'H'; const unsigned int keyJ = 'J'; const unsigned int keyK = 'K'; const unsigned int keyL = 'L'; const unsigned int keyENTER = VK_RETURN; const unsigned int keySHIFTLEFT = VK_SHIFT; const unsigned int keyZ = 'Z'; const unsigned int keyX = 'X'; const unsigned int keyC = 'C'; const unsigned int keyV = 'V'; const unsigned int keyB = 'B'; const unsigned int keyN = 'N'; const unsigned int keyM = 'M'; const unsigned int keySHIFTRIGHT = VK_SHIFT; const unsigned int keyARROWUP = VK_UP; const unsigned int keyCTRLLEFT = VK_CONTROL; const unsigned int keyAPPLEFT = VK_LWIN; const unsigned int keyALT = VK_LMENU; const unsigned int keySPACE = VK_SPACE; const unsigned int keyALTGR = VK_CONTROL; const unsigned int keyAPPRIGHT = VK_RWIN; const unsigned int keyMENU = VK_APPS; const unsigned int keyCTRLRIGHT = VK_CONTROL; const unsigned int keyARROWLEFT = VK_LEFT; const unsigned int keyARROWDOWN = VK_DOWN; const unsigned int keyARROWRIGHT = VK_RIGHT; const unsigned int keyPAD0 = 0x60; const unsigned int keyPAD1 = 0x61; const unsigned int keyPAD2 = 0x62; const unsigned int keyPAD3 = 0x63; const unsigned int keyPAD4 = 0x64; const unsigned int keyPAD5 = 0x65; const unsigned int keyPAD6 = 0x66; const unsigned int keyPAD7 = 0x67; const unsigned int keyPAD8 = 0x68; const unsigned int keyPAD9 = 0x69; const unsigned int keyPADADD = VK_ADD; const unsigned int keyPADSUB = VK_SUBTRACT; const unsigned int keyPADMUL = VK_MULTIPLY; const unsigned int keyPADDIV = VK_DIVIDE; #else // Define random keycodes when no display is available. // (should rarely be used then!). const unsigned int keyESC = 1U; //!< Keycode for the \c ESC key (architecture-dependent). const unsigned int keyF1 = 2U; //!< Keycode for the \c F1 key (architecture-dependent). const unsigned int keyF2 = 3U; //!< Keycode for the \c F2 key (architecture-dependent). const unsigned int keyF3 = 4U; //!< Keycode for the \c F3 key (architecture-dependent). const unsigned int keyF4 = 5U; //!< Keycode for the \c F4 key (architecture-dependent). const unsigned int keyF5 = 6U; //!< Keycode for the \c F5 key (architecture-dependent). const unsigned int keyF6 = 7U; //!< Keycode for the \c F6 key (architecture-dependent). const unsigned int keyF7 = 8U; //!< Keycode for the \c F7 key (architecture-dependent). const unsigned int keyF8 = 9U; //!< Keycode for the \c F8 key (architecture-dependent). const unsigned int keyF9 = 10U; //!< Keycode for the \c F9 key (architecture-dependent). const unsigned int keyF10 = 11U; //!< Keycode for the \c F10 key (architecture-dependent). const unsigned int keyF11 = 12U; //!< Keycode for the \c F11 key (architecture-dependent). const unsigned int keyF12 = 13U; //!< Keycode for the \c F12 key (architecture-dependent). const unsigned int keyPAUSE = 14U; //!< Keycode for the \c PAUSE key (architecture-dependent). const unsigned int key1 = 15U; //!< Keycode for the \c 1 key (architecture-dependent). const unsigned int key2 = 16U; //!< Keycode for the \c 2 key (architecture-dependent). const unsigned int key3 = 17U; //!< Keycode for the \c 3 key (architecture-dependent). const unsigned int key4 = 18U; //!< Keycode for the \c 4 key (architecture-dependent). const unsigned int key5 = 19U; //!< Keycode for the \c 5 key (architecture-dependent). const unsigned int key6 = 20U; //!< Keycode for the \c 6 key (architecture-dependent). const unsigned int key7 = 21U; //!< Keycode for the \c 7 key (architecture-dependent). const unsigned int key8 = 22U; //!< Keycode for the \c 8 key (architecture-dependent). const unsigned int key9 = 23U; //!< Keycode for the \c 9 key (architecture-dependent). const unsigned int key0 = 24U; //!< Keycode for the \c 0 key (architecture-dependent). const unsigned int keyBACKSPACE = 25U; //!< Keycode for the \c BACKSPACE key (architecture-dependent). const unsigned int keyINSERT = 26U; //!< Keycode for the \c INSERT key (architecture-dependent). const unsigned int keyHOME = 27U; //!< Keycode for the \c HOME key (architecture-dependent). const unsigned int keyPAGEUP = 28U; //!< Keycode for the \c PAGEUP key (architecture-dependent). const unsigned int keyTAB = 29U; //!< Keycode for the \c TAB key (architecture-dependent). const unsigned int keyQ = 30U; //!< Keycode for the \c Q key (architecture-dependent). const unsigned int keyW = 31U; //!< Keycode for the \c W key (architecture-dependent). const unsigned int keyE = 32U; //!< Keycode for the \c E key (architecture-dependent). const unsigned int keyR = 33U; //!< Keycode for the \c R key (architecture-dependent). const unsigned int keyT = 34U; //!< Keycode for the \c T key (architecture-dependent). const unsigned int keyY = 35U; //!< Keycode for the \c Y key (architecture-dependent). const unsigned int keyU = 36U; //!< Keycode for the \c U key (architecture-dependent). const unsigned int keyI = 37U; //!< Keycode for the \c I key (architecture-dependent). const unsigned int keyO = 38U; //!< Keycode for the \c O key (architecture-dependent). const unsigned int keyP = 39U; //!< Keycode for the \c P key (architecture-dependent). const unsigned int keyDELETE = 40U; //!< Keycode for the \c DELETE key (architecture-dependent). const unsigned int keyEND = 41U; //!< Keycode for the \c END key (architecture-dependent). const unsigned int keyPAGEDOWN = 42U; //!< Keycode for the \c PAGEDOWN key (architecture-dependent). const unsigned int keyCAPSLOCK = 43U; //!< Keycode for the \c CAPSLOCK key (architecture-dependent). const unsigned int keyA = 44U; //!< Keycode for the \c A key (architecture-dependent). const unsigned int keyS = 45U; //!< Keycode for the \c S key (architecture-dependent). const unsigned int keyD = 46U; //!< Keycode for the \c D key (architecture-dependent). const unsigned int keyF = 47U; //!< Keycode for the \c F key (architecture-dependent). const unsigned int keyG = 48U; //!< Keycode for the \c G key (architecture-dependent). const unsigned int keyH = 49U; //!< Keycode for the \c H key (architecture-dependent). const unsigned int keyJ = 50U; //!< Keycode for the \c J key (architecture-dependent). const unsigned int keyK = 51U; //!< Keycode for the \c K key (architecture-dependent). const unsigned int keyL = 52U; //!< Keycode for the \c L key (architecture-dependent). const unsigned int keyENTER = 53U; //!< Keycode for the \c ENTER key (architecture-dependent). const unsigned int keySHIFTLEFT = 54U; //!< Keycode for the \c SHIFTLEFT key (architecture-dependent). const unsigned int keyZ = 55U; //!< Keycode for the \c Z key (architecture-dependent). const unsigned int keyX = 56U; //!< Keycode for the \c X key (architecture-dependent). const unsigned int keyC = 57U; //!< Keycode for the \c C key (architecture-dependent). const unsigned int keyV = 58U; //!< Keycode for the \c V key (architecture-dependent). const unsigned int keyB = 59U; //!< Keycode for the \c B key (architecture-dependent). const unsigned int keyN = 60U; //!< Keycode for the \c N key (architecture-dependent). const unsigned int keyM = 61U; //!< Keycode for the \c M key (architecture-dependent). const unsigned int keySHIFTRIGHT = 62U; //!< Keycode for the \c SHIFTRIGHT key (architecture-dependent). const unsigned int keyARROWUP = 63U; //!< Keycode for the \c ARROWUP key (architecture-dependent). const unsigned int keyCTRLLEFT = 64U; //!< Keycode for the \c CTRLLEFT key (architecture-dependent). const unsigned int keyAPPLEFT = 65U; //!< Keycode for the \c APPLEFT key (architecture-dependent). const unsigned int keyALT = 66U; //!< Keycode for the \c ALT key (architecture-dependent). const unsigned int keySPACE = 67U; //!< Keycode for the \c SPACE key (architecture-dependent). const unsigned int keyALTGR = 68U; //!< Keycode for the \c ALTGR key (architecture-dependent). const unsigned int keyAPPRIGHT = 69U; //!< Keycode for the \c APPRIGHT key (architecture-dependent). const unsigned int keyMENU = 70U; //!< Keycode for the \c MENU key (architecture-dependent). const unsigned int keyCTRLRIGHT = 71U; //!< Keycode for the \c CTRLRIGHT key (architecture-dependent). const unsigned int keyARROWLEFT = 72U; //!< Keycode for the \c ARROWLEFT key (architecture-dependent). const unsigned int keyARROWDOWN = 73U; //!< Keycode for the \c ARROWDOWN key (architecture-dependent). const unsigned int keyARROWRIGHT = 74U; //!< Keycode for the \c ARROWRIGHT key (architecture-dependent). const unsigned int keyPAD0 = 75U; //!< Keycode for the \c PAD0 key (architecture-dependent). const unsigned int keyPAD1 = 76U; //!< Keycode for the \c PAD1 key (architecture-dependent). const unsigned int keyPAD2 = 77U; //!< Keycode for the \c PAD2 key (architecture-dependent). const unsigned int keyPAD3 = 78U; //!< Keycode for the \c PAD3 key (architecture-dependent). const unsigned int keyPAD4 = 79U; //!< Keycode for the \c PAD4 key (architecture-dependent). const unsigned int keyPAD5 = 80U; //!< Keycode for the \c PAD5 key (architecture-dependent). const unsigned int keyPAD6 = 81U; //!< Keycode for the \c PAD6 key (architecture-dependent). const unsigned int keyPAD7 = 82U; //!< Keycode for the \c PAD7 key (architecture-dependent). const unsigned int keyPAD8 = 83U; //!< Keycode for the \c PAD8 key (architecture-dependent). const unsigned int keyPAD9 = 84U; //!< Keycode for the \c PAD9 key (architecture-dependent). const unsigned int keyPADADD = 85U; //!< Keycode for the \c PADADD key (architecture-dependent). const unsigned int keyPADSUB = 86U; //!< Keycode for the \c PADSUB key (architecture-dependent). const unsigned int keyPADMUL = 87U; //!< Keycode for the \c PADMUL key (architecture-dependent). const unsigned int keyPADDIV = 88U; //!< Keycode for the \c PADDDIV key (architecture-dependent). #endif const double PI = 3.14159265358979323846; //!< Value of the mathematical constant PI // Define a 10x13 font (small size). const unsigned int font10x13[256*10*13/32] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80100c0, 0x68000300,0x801,0xc00010,0x100c000,0x68100,0x100c0680,0x2,0x403000,0x1000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0,0x0,0x0,0x4020120, 0x58120480,0x402,0x1205008,0x2012050,0x58080,0x20120581,0x40000001,0x804812,0x2000000,0x0,0x300,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x140,0x80000,0x200402,0x800000,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x7010,0x7000000,0x8000200,0x20000,0xc0002000,0x8008,0x0,0x0,0x0,0x0,0x808,0x4000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x80000000,0x0,0x0,0x0,0x40000,0x0,0x0,0x0,0x0,0x480,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x70,0x80100c0,0x68000480,0x1001, 0xc00010,0x1018000,0x68100,0x100c0680,0x4,0x403000,0x1020000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20140,0x28081883,0x200801, 0x2a00000,0x10,0x1c0201c0,0x70040f80,0xc0f81c07,0x0,0x70,0x3e0303c0,0x3c3c0f83,0xe03c2107,0xe08810,0x18c31070,0x3c0703c0, 0x783e0842,0x22222208,0x83e04010,0x1008000,0x4000200,0x20001,0x2002,0x408008,0x0,0x0,0x100000,0x0,0x1008,0x2000000,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20080,0x38000880,0x8078140f,0x81c00000,0x3e000,0xc020180,0x60080001,0xe0000002,0xc00042,0x108e2010, 0xc0300c0,0x300c0303,0xf83c3e0f,0x83e0f81c,0x701c070,0x3c0c41c0,0x701c0701,0xc0001d08,0x42108421,0x8820088,0x4020120,0x58140480, 0x802,0x1205008,0x3014050,0xc058080,0x20120581,0x40000002,0x804814,0x2020050,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20140, 0x281e2484,0x80200801,0x1c02000,0x10,0x22060220,0x880c0801,0x82208,0x80000001,0x20008,0x41030220,0x40220802,0x402102,0x209010, 0x18c31088,0x22088220,0x80080842,0x22222208,0x80204010,0x1014000,0x200,0x20001,0x2000,0x8008,0x0,0x0,0x100000,0x0,0x1008, 0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x40000500,0x80800010,0x40200000,0x41000,0x12020040,0x10000003,0xa0000006, 0x12000c4,0x31014000,0xc0300c0,0x300c0302,0x80402008,0x2008008,0x2008020,0x220c4220,0x88220882,0x20002208,0x42108421,0x8820088, 0x0,0x300,0x0,0x0,0x0,0x14000000,0x0,0x200200,0x0,0x20000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000,0xfc282504,0x80001000, 0x82a02000,0x20,0x22020020,0x8140802,0x102208,0x80801006,0x18008,0x9c848220,0x80210802,0x802102,0x20a010,0x15429104,0x22104220, 0x80080842,0x22221405,0x404008,0x1022000,0x703c0,0x381e0701,0xc0783c02,0xc09008,0x1d83c070,0x3c078140,0x381c0882,0x21242208, 0x81e01008,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x201e0,0x40220500,0x80800027,0x20e02800,0x9c800,0x12020040, 0x20000883,0xa0200002,0x120a044,0x11064010,0x12048120,0x48120484,0x80802008,0x2008008,0x2008020,0x210a4411,0x4411044,0x10884508, 0x42108421,0x503c0b0,0x1c0701c0,0x701c0707,0x70381c07,0x1c07008,0x2008020,0x20f01c0,0x701c0701,0xc0201c08,0x82208822,0x883c088, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000,0x50281903,0x20001000,0x80802000,0x20,0x22020040,0x30240f03,0xc0101c08,0x80801018, 0x1fc06010,0xa48483c0,0x80210f03,0xe0803f02,0x20c010,0x15429104,0x22104220,0x70080841,0x41540805,0x804008,0x1041000,0x8220, 0x40220881,0x882202,0x40a008,0x12422088,0x22088180,0x40100882,0x21241408,0x80201008,0x2031000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x20280,0x401c0200,0x700028,0x21205000,0x92800,0xc1fc080,0x10000883,0xa0200002,0x1205049,0x12c19010,0x12048120,0x48120484, 0xf0803c0f,0x3c0f008,0x2008020,0x790a4411,0x4411044,0x10504908,0x42108421,0x5022088,0x2008020,0x8020080,0x88402208,0x82208808, 0x2008020,0x1e088220,0x88220882,0x20002608,0x82208822,0x8822088,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000,0x501c0264, 0xa0001000,0x8001fc00,0x7000020,0x22020080,0x83e0082,0x20202207,0x80000020,0x1020,0xa4848220,0x80210802,0x9c2102,0x20c010, 0x12425104,0x3c1043c0,0x8080841,0x41540802,0x804008,0x1000000,0x78220,0x40220f81,0x882202,0x40c008,0x12422088,0x22088100, 0x60100881,0x41540805,0x406008,0x1849000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20280,0xf0140200,0x880028,0x20e0a03f,0x709c800, 0x201c0,0x60000881,0xa0000007,0xc0284b,0x122eb020,0x12048120,0x48120487,0x80802008,0x2008008,0x2008020,0x21094411,0x4411044, 0x10204908,0x42108421,0x2022088,0x1e0781e0,0x781e0787,0xf8403e0f,0x83e0f808,0x2008020,0x22088220,0x88220882,0x21fc2a08,0x82208822, 0x5022050,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20001,0xf80a0294,0x40001000,0x80002000,0x20,0x22020100,0x8040082,0x20202200, 0x80000018,0x1fc06020,0xa48fc220,0x80210802,0x842102,0x20a010,0x12425104,0x20104240,0x8080841,0x41541402,0x1004008,0x1000000, 0x88220,0x40220801,0x882202,0x40a008,0x12422088,0x22088100,0x18100881,0x41540805,0x801008,0x2046000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x20280,0x401c0f80,0x80880028,0x20005001,0x94800,0x20000,0x880,0xa0000000,0x5015,0x4215040,0x3f0fc3f0,0xfc3f0fc8, 0x80802008,0x2008008,0x2008020,0x21094411,0x4411044,0x10505108,0x42108421,0x203c088,0x22088220,0x88220888,0x80402008,0x2008008, 0x2008020,0x22088220,0x88220882,0x20002a08,0x82208822,0x5022050,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xa00a0494,0x60001000, 0x80002004,0x8020,0x22020200,0x88040882,0x20402201,0x801006,0x18000,0x9f084220,0x40220802,0x442102,0x209010,0x10423088,0x20088220, 0x8080840,0x80882202,0x2004008,0x1000000,0x88220,0x40220881,0x882202,0x409008,0x12422088,0x22088100,0x8100880,0x80881402, 0x1001008,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20280,0x40220200,0x80700027,0x20002801,0x92800,0x1fc000,0x980, 0xa0000000,0xa017,0x84417840,0x21084210,0x84210848,0x80402008,0x2008008,0x2008020,0x2208c220,0x88220882,0x20882208,0x42108421, 0x2020088,0x22088220,0x88220888,0xc8402208,0x82208808,0x2008020,0x22088220,0x88220882,0x20203208,0x82208822,0x2022020,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000,0xa03c0463,0x90000801,0x2004,0x8040,0x1c0703e0,0x70040701,0xc0401c06,0x801001,0x20020, 0x400843c0,0x3c3c0f82,0x3c2107,0x1c0881e,0x10423070,0x20070210,0xf0080780,0x80882202,0x3e04004,0x1000000,0x783c0,0x381e0701, 0x782202,0x408808,0x12422070,0x3c078100,0x700c0780,0x80882202,0x1e01008,0x2000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x201e0, 0xf8000200,0x80080010,0x40000001,0x41000,0x0,0xe80,0xa0000000,0x21,0x8e21038,0x21084210,0x84210848,0xf83c3e0f,0x83e0f81c, 0x701c070,0x3c08c1c0,0x701c0701,0xc0005c07,0x81e0781e,0x20200b0,0x1e0781e0,0x781e0787,0x30381c07,0x1c07008,0x2008020,0x1c0881c0, 0x701c0701,0xc0201c07,0x81e0781e,0x203c020,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80000,0x801,0x4,0x40,0x0,0x0,0x0,0x1000, 0x0,0x3c000000,0x0,0x0,0x0,0x0,0x10000,0x0,0x0,0x4004,0x1000000,0x0,0x0,0x80000,0x400000,0x0,0x20008000,0x0,0x4,0x1008,0x2000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x0,0x8008000f,0x80000000,0x3e000,0x0,0x800,0xa0000400,0x0,0x0,0x0,0x0,0x80000,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x100000,0x0,0x0,0x0,0x0,0x2000,0x0,0x4020040,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80000, 0x402,0x8,0x40,0x0,0x0,0x0,0x2000,0x0,0x0,0x0,0x0,0x0,0x0,0xc000,0x0,0x0,0x7004,0x70000fc,0x0,0x0,0x700000,0x800000,0x0,0x20008000, 0x0,0x4,0x808,0x4000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x80,0x0,0x80f00000,0x0,0x0,0x0,0x800,0xa0001800,0x0,0x0,0x0,0x0, 0x300000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x600000,0x0,0x0,0x0,0x0,0x0,0x0,0x4020040 }; // Define a 12x24 font (normal size). const unsigned int font12x24[12*24*256/32] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x19,0x80000000,0x198000,0x0,0x0,0x0,0x0, 0x0,0x198,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc001806,0xc81980,0x60000000,0xc001806,0x1980c00,0x18060198,0xc80c, 0x180600,0xc8198000,0xc001,0x80601980,0x18000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf,0x0,0xf0000,0x0,0x0,0x0,0x0,0x0,0x198,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x600300f,0x1301980,0x90000000,0x600300f,0x1980600,0x300f0198,0x13006,0x300f01,0x30198000,0x6003, 0xf01980,0x30000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x6,0x0,0x60000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7007,0x3c0000,0x3006019, 0x80000000,0x90000000,0x3006019,0x80000300,0x60198000,0x3,0x601980,0x0,0x3006,0x1980000,0x60000000,0x0,0x0,0xe0000000,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x18000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000000, 0x0,0x0,0x0,0x0,0x0,0xc800019,0x80000000,0x198000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc0,0x0,0x0,0x1001,0x420000,0x0,0x0,0x90000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x18000c06,0xc80001,0x10000000,0x18000c06,0x1800,0xc060000,0xc818,0xc0600,0xc8000000, 0x18000,0xc0600000,0xc000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6019,0x80660207,0x800f8060,0x300c004,0x0,0x6, 0xe00703f,0x3f00383,0xf80f07fc,0x1f01f000,0x0,0xf8,0x607f,0x7c7e07,0xfe7fe0f8,0x6063fc1f,0x86066007,0xe7060f0,0x7f80f07f, 0x81f8fff6,0x6606c03,0x70ee077f,0xe0786000,0xf0070000,0xc000060,0xc0,0x3e000,0x60006003,0x600fc00,0x0,0x0,0x0,0x0,0x0,0x3c0603, 0xc0000000,0x7800000,0xf0000,0x0,0xf00001f,0x80001fe0,0x7fe000,0x0,0x0,0x0,0x168fe609,0x0,0x90e07,0x6000,0x3c000e,0x70000f8, 0x1980001f,0x0,0x1f8,0xf00000f,0xf00180,0xfe000,0xe00e,0x1001,0x20060,0x6006006,0x600600,0x600fe07c,0x7fe7fe7f,0xe7fe3fc3, 0xfc3fc3fc,0x7e07060f,0xf00f00,0xf00f0000,0xf360660,0x6606606e,0x76001e0,0xc00180f,0x1681981,0x10000000,0xc00180f,0x1980c00, 0x180f0198,0x3801680c,0x180f01,0x68198000,0xc001,0x80f01980,0x18600198,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6019, 0x8044020c,0xc01f8060,0x2004004,0x0,0xc,0x3f81f07f,0x87f80383,0xf81f87fc,0x3f83f800,0x0,0x1fc,0x780607f,0x81fe7f87,0xfe7fe1fc, 0x6063fc1f,0x860c6007,0xe7061f8,0x7fc1f87f,0xc3fcfff6,0x6606c03,0x30c6067f,0xe0783000,0xf00d8000,0x6000060,0xc0,0x7e000,0x60006003, 0x600fc00,0x0,0x0,0xc00,0x0,0x0,0x7c0603,0xe0000000,0xfc00000,0x1f0000,0x0,0x900003f,0xc0003fe0,0x7fe000,0x0,0x0,0x0,0x1302660f, 0x0,0xf0606,0x6004,0x7e0006,0x60601f8,0x19800001,0x80000000,0x1f8,0x19800010,0x81080300,0x3f2000,0x2011,0x1001,0x1c0060,0x6006006, 0x600600,0x601fe1fe,0x7fe7fe7f,0xe7fe3fc3,0xfc3fc3fc,0x7f87061f,0x81f81f81,0xf81f8000,0x3fa60660,0x66066066,0x66003f0,0x6003009, 0x1301981,0x10000000,0x6003009,0x1980600,0x30090198,0x1f013006,0x300901,0x30198000,0x6003,0x901980,0x30600198,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6019,0x80cc0f8c,0xc0180060,0x6006044,0x40000000,0xc,0x3181b041,0xc41c0783,0x388018, 0x71c71800,0x0,0x106,0x18c0f061,0xc38261c6,0x600384,0x60606001,0x86186007,0xe78630c,0x60e30c60,0xe7040606,0x630cc03,0x39c30c00, 0xc0603000,0x3018c000,0x3000060,0xc0,0x60000,0x60000000,0x6000c00,0x0,0x0,0xc00,0x0,0x0,0x600600,0x60000000,0x18400000,0x180000, 0x0,0x19800070,0x40003600,0xc000,0x0,0x0,0x0,0x25a06,0x0,0x6030c,0x4,0xe20007,0xe060180,0xf000,0x80000000,0xf0000,0x10800000, 0x80080600,0x7f2000,0x2020,0x80001001,0x20000,0xf00f00f,0xf00f00,0x601b0382,0x60060060,0x6000600,0x60060060,0x61c78630,0xc30c30c3, 0xc30c000,0x30e60660,0x66066063,0xc600738,0x3006019,0x80000000,0xe0000000,0x3006019,0x80000300,0x60198000,0x3e000003,0x601980, 0x0,0x3006,0x1980000,0x60600000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6019,0x80cc1fcc,0xc0180060,0x6006035,0x80000000, 0x18,0x71c03000,0xc00c0583,0x300018,0x60c60c00,0x0,0x6,0x3060f060,0xc30060c6,0x600300,0x60606001,0x86306007,0x9e78670e,0x60670e60, 0x66000606,0x630c606,0x19830c01,0xc0601800,0x30306000,0x60,0xc0,0x60000,0x60000000,0x6000c00,0x0,0x0,0xc00,0x0,0x0,0x600600, 0x60000000,0x18000000,0x300000,0x0,0x78060,0x6600,0x1c000,0x300c,0x39819c0,0x0,0x25a00,0x0,0x30c,0x4,0xc00003,0xc060180,0x30c1f, 0x80000000,0x30c000,0x10800001,0x80700000,0x7f2000,0x2020,0x80001001,0x20060,0xf00f00f,0xf00f00,0xf01b0300,0x60060060,0x6000600, 0x60060060,0x60c78670,0xe70e70e7,0xe70e000,0x70c60660,0x66066063,0xc7f8618,0x0,0x0,0x0,0x0,0x0,0x0,0x7000000,0x0,0x0,0x0, 0x0,0x600000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6019,0x87ff3a4c,0xc0180060,0x400600e,0x600000,0x18,0x60c03000, 0xc00c0d83,0x700018,0x60c60c00,0x20,0x400006,0x3060f060,0xc6006066,0x600600,0x60606001,0x86606006,0x966c6606,0x60660660,0x66000606, 0x630c666,0xf019801,0x80601800,0x30603000,0x1f06f,0xf01ec0,0xf03fe1ec,0x6703e01f,0x61c0c06,0xdc6701f0,0x6f01ec0c,0xe1f87fc6, 0xc60cc03,0x71c60c7f,0xc0600600,0x60000000,0x30000000,0x300000,0x40040,0x88060,0x6600,0x18000,0x300c,0x1981980,0x0,0x2421f, 0x80003ce0,0x7fc198,0x601f,0xc02021,0x980600c0,0x40230,0x80000000,0x402000,0x19806003,0x80006,0xc7f2000,0x2020,0x80001001, 0x420060,0xf00f00f,0xf00f00,0xf01b0600,0x60060060,0x6000600,0x60060060,0x6066c660,0x66066066,0x6606208,0x60e60660,0x66066061, 0x987fc670,0x1f01f01f,0x1f01f01,0xf039c0f0,0xf00f00f,0xf03e03,0xe03e03e0,0x1f06701f,0x1f01f01,0xf01f0060,0x1e660c60,0xc60c60c6, 0xc6f060c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x7ff3207,0x8c0c0000,0xc00300e,0x600000,0x30,0x60c03000, 0xc01c0983,0xf0600030,0x31860c06,0x6001e0,0x78000e,0x23e1f861,0xc6006066,0x600600,0x60606001,0x86c06006,0x966c6606,0x60660660, 0xe7000606,0x630c666,0xf01f803,0x600c00,0x30000000,0x3f87f,0x83f83fc3,0xf83fe3fc,0x7f83e01f,0x6380c07,0xfe7f83f8,0x7f83fc0d, 0xf3fc7fc6,0xc71cc03,0x3183187f,0xc0600600,0x60000000,0xff806000,0x300000,0x40040,0x88070,0x6600,0x60030060,0x6001818,0x1883180, 0x0,0x2423f,0xc0007ff0,0x607fc1f8,0x603f,0x80c01fc1,0xf80601e0,0x5f220,0x80420000,0x5f2000,0xf006006,0x80006,0xc7f2000,0x2020, 0x82107c07,0xc03c0060,0x1f81f81f,0x81f81f80,0xf03b0600,0x60060060,0x6000600,0x60060060,0x6066c660,0x66066066,0x660671c,0x61660660, 0x66066061,0xf860e6c0,0x3f83f83f,0x83f83f83,0xf87fe3f8,0x3f83f83f,0x83f83e03,0xe03e03e0,0x3f87f83f,0x83f83f83,0xf83f8060, 0x3fc60c60,0xc60c60c3,0x187f8318,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x883200,0x300c0000,0xc003035,0x80600000, 0x30,0x66c03001,0xc0f81983,0xf86f0030,0x1f071c06,0x600787,0xfe1e001c,0x6261987f,0x86006067,0xfe7fc600,0x7fe06001,0x87c06006, 0xf6646606,0x60e6067f,0xc3e00606,0x61986f6,0x600f007,0x600c00,0x30000000,0x21c71,0x830831c3,0x1c06031c,0x71c06003,0x6700c06, 0x6671c318,0x71831c0f,0x16040c06,0xc318606,0x1b031803,0x80600600,0x60000000,0x30009000,0x300000,0x40040,0x7003e,0x67e0,0x90070090, 0x9001818,0x8c3100,0x0,0x60,0x4000e730,0x900380f0,0x6034,0x80c018c7,0xfe060338,0xb0121,0x80c60000,0x909000,0x6008,0x1080006, 0xc3f2000,0x2011,0x3180060,0x60060e0,0x19819819,0x81981981,0x9833c600,0x7fe7fe7f,0xe7fe0600,0x60060060,0x60664660,0x66066066, 0x66063b8,0x62660660,0x66066060,0xf06066c0,0x21c21c21,0xc21c21c2,0x1c466308,0x31c31c31,0xc31c0600,0x60060060,0x31871c31,0x83183183, 0x18318000,0x71860c60,0xc60c60c3,0x18718318,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x1981a00,0xe03e0000,0xc003044, 0x40600000,0x60,0x66c03001,0x80f03182,0x1c7f8030,0x3f83fc06,0x601e07,0xfe078038,0x6661987f,0x86006067,0xfe7fc61e,0x7fe06001, 0x87e06006,0x66666606,0x7fc6067f,0x81f80606,0x61986f6,0x6006006,0x600600,0x30000000,0xc60,0xc60060c6,0xc06060c,0x60c06003, 0x6e00c06,0x6660c60c,0x60c60c0e,0x6000c06,0xc318666,0x1f031803,0x600600,0x603c2000,0x30016800,0x1fe0000,0x1f81f8,0x1c1f,0x804067e1, 0x68060168,0x16800810,0xc42300,0x0,0x60,0x20c331,0x68030060,0x6064,0x3fc1040,0xf006031c,0xa011e,0x818c7fe0,0x909000,0x7fe1f, 0x80f00006,0xc0f2060,0xf80e,0x18c0780,0x780781c0,0x19819819,0x81981981,0x9833c600,0x7fe7fe7f,0xe7fe0600,0x60060060,0xfc666660, 0x66066066,0x66061f0,0x66660660,0x66066060,0x606066e0,0xc00c00,0xc00c00c0,0xc066600,0x60c60c60,0xc60c0600,0x60060060,0x60c60c60, 0xc60c60c6,0xc60c000,0x61c60c60,0xc60c60c3,0x1860c318,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x1980f81,0x80373000, 0xc003004,0x7fe0001,0xf0000060,0x60c03003,0x183180,0xc71c060,0x3181ec00,0x7000,0xe070,0x66619860,0xc6006066,0x60061e,0x60606001, 0x87606006,0x66626606,0x7f860661,0xc01c0606,0x6198696,0xf00600e,0x600600,0x30000000,0x1fc60,0xc60060c7,0xfc06060c,0x60c06003, 0x7c00c06,0x6660c60c,0x60c60c0c,0x7f00c06,0xc3b8666,0xe01b007,0x3c00600,0x3c7fe000,0xff03ec00,0x1fe0000,0x40040,0xe001,0xc0806603, 0xec0e03ec,0x3ec00010,0x0,0x60000000,0x7f,0x10c3f3,0xec070060,0x6064,0x3fc1040,0x6000030c,0xa0100,0x3187fe1,0xf09f1000,0x7fe00, 0x6,0xc012060,0x0,0xc63c03,0xc03c0380,0x19819819,0x81981981,0x98330600,0x60060060,0x6000600,0x60060060,0xfc662660,0x66066066, 0x66060e0,0x6c660660,0x66066060,0x6060e630,0x1fc1fc1f,0xc1fc1fc1,0xfc3fe600,0x7fc7fc7f,0xc7fc0600,0x60060060,0x60c60c60,0xc60c60c6, 0xc60c7fe,0x62c60c60,0xc60c60c1,0xb060c1b0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0xffe02c6,0x3c633000,0xc003004, 0x7fe0001,0xf00000c0,0x60c03006,0xc6180,0xc60c060,0x60c00c00,0x7000,0xe060,0x66639c60,0x66006066,0x600606,0x60606001,0x86306006, 0x66636606,0x60060660,0xc0060606,0x61f8696,0xf00600c,0x600300,0x30000000,0x3fc60,0xc60060c7,0xfc06060c,0x60c06003,0x7c00c06, 0x6660c60c,0x60c60c0c,0x1f80c06,0xc1b0666,0xe01b00e,0x3c00600,0x3c43c000,0x3007de00,0x600000,0x40040,0x30000,0x61006607,0xde0c07de, 0x7de00000,0x0,0xf07fefff,0x1f,0x8008c3f7,0xde0e0060,0x6064,0xc01047,0xfe00018c,0xb013f,0x86300061,0xf0911000,0x6000,0x6, 0xc012060,0x3f,0x8063c0cc,0x3cc0c700,0x39c39c39,0xc39c39c1,0x98630600,0x60060060,0x6000600,0x60060060,0x60663660,0x66066066, 0x66061f0,0x78660660,0x66066060,0x607fc618,0x3fc3fc3f,0xc3fc3fc3,0xfc7fe600,0x7fc7fc7f,0xc7fc0600,0x60060060,0x60c60c60,0xc60c60c6, 0xc60c7fe,0x64c60c60,0xc60c60c1,0xb060c1b0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0xffe0260,0x6661b000,0xc003000, 0x600000,0xc0,0x60c0300c,0xc7fe0,0xc60c060,0x60c01c00,0x1e07,0xfe078060,0x6663fc60,0x66006066,0x600606,0x60606001,0x86386006, 0x6636606,0x60060660,0xe0060606,0x60f039c,0x1b806018,0x600300,0x30000000,0x70c60,0xc60060c6,0x6060c,0x60c06003,0x7600c06, 0x6660c60c,0x60c60c0c,0x1c0c06,0xc1b03fc,0xe01f01c,0xe00600,0x70000000,0x3007fc00,0x600000,0x40040,0x0,0x62006607,0xfc1807fc, 0x7fc00000,0x0,0xf0000000,0x1,0xc004c307,0xfc1c0060,0x6064,0xc018c0,0x600000d8,0x5f200,0x3180060,0x50a000,0x6000,0x6,0xc012000, 0x0,0xc601c0,0x4201c600,0x3fc3fc3f,0xc3fc3fc3,0xfc7f0600,0x60060060,0x6000600,0x60060060,0x60663660,0x66066066,0x66063b8, 0x70660660,0x66066060,0x607f860c,0x70c70c70,0xc70c70c7,0xcc60600,0x60060060,0x6000600,0x60060060,0x60c60c60,0xc60c60c6,0xc60c000, 0x68c60c60,0xc60c60c1,0xf060c1f0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3300260,0x6661e000,0xc003000,0x600000, 0x180,0x71c03018,0xc7fe0,0xc60c0c0,0x60c01800,0x787,0xfe1e0060,0x6663fc60,0x630060c6,0x600306,0x60606001,0x86186006,0x661e70e, 0x60070c60,0x60060606,0x60f039c,0x19806038,0x600180,0x30000000,0x60c60,0xc60060c6,0x6060c,0x60c06003,0x6700c06,0x6660c60c, 0x60c60c0c,0xc0c06,0xc1b039c,0x1f00e018,0x600600,0x60000000,0x1803f800,0x600000,0x40040,0x39e00,0x63006603,0xf83803f8,0x3f800000, 0x0,0x60000000,0x0,0xc00cc303,0xf8180060,0x6064,0xc01fc0,0x60060070,0x40200,0x18c0060,0x402000,0x6000,0x6,0xc012000,0x0,0x18c0140, 0x2014600,0x3fc3fc3f,0xc3fc3fc3,0xfc7f0300,0x60060060,0x6000600,0x60060060,0x60c61e70,0xe70e70e7,0xe70e71c,0x60e60660,0x66066060, 0x6060060c,0x60c60c60,0xc60c60c6,0xcc60600,0x60060060,0x6000600,0x60060060,0x60c60c60,0xc60c60c6,0xc60c000,0x70c60c60,0xc60c60c0, 0xe060c0e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x33022e0,0x6670c000,0xc003000,0x600600,0x60180,0x31803030, 0x41c0184,0x1831c0c0,0x71c23806,0x6001e0,0x780000,0x62630c60,0xe38261c6,0x600386,0x60606043,0x860c6006,0x661e30c,0x60030c60, 0x740e0607,0xe0f039c,0x31c06030,0x600180,0x30000000,0x61c71,0x830831c3,0x406031c,0x60c06003,0x6300c06,0x6660c318,0x71831c0c, 0x41c0c07,0x1c0e039c,0x1b00e030,0x600600,0x60000000,0x1c41b00e,0x601cc0,0x401f8,0x45240,0xe1803601,0xb03001b0,0x1b000000, 0x0,0x0,0x41,0xc008e711,0xb0300060,0x6034,0x80c02020,0x60060030,0x30c00,0xc60000,0x30c000,0x0,0x7,0x1c012000,0x0,0x3180240, 0x6024608,0x30c30c30,0xc30c30c3,0xc630382,0x60060060,0x6000600,0x60060060,0x61c61e30,0xc30c30c3,0xc30c208,0x70c70e70,0xe70e70e0, 0x6060068c,0x61c61c61,0xc61c61c6,0x1cc62308,0x30430430,0x43040600,0x60060060,0x31860c31,0x83183183,0x18318060,0x31c71c71, 0xc71c71c0,0xe07180e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x2203fc0,0x663f6000,0x6006000,0x600600,0x60300, 0x3f81fe7f,0xc7f80187,0xf83f80c0,0x3f83f006,0x600020,0x400060,0x33e6067f,0xc1fe7f87,0xfe6001fe,0x6063fc7f,0x60e7fe6,0x660e3f8, 0x6001f860,0x37fc0603,0xfc06030c,0x30c0607f,0xe06000c0,0x30000000,0x7fc7f,0x83f83fc3,0xfc0603fc,0x60c7fe03,0x61807c6,0x6660c3f8, 0x7f83fc0c,0x7f80fc3,0xfc0e039c,0x3180607f,0xc0600600,0x60000000,0xfc0e00c,0x601986,0x66040040,0x4527f,0xc0803fe0,0xe07fe0e0, 0xe000000,0x0,0x0,0x7f,0x80107ff0,0xe07fc060,0x603f,0x83fe0000,0x60060018,0xf000,0x420000,0xf0000,0x7fe00,0x7,0xfe012000, 0x0,0x2100640,0xc0643f8,0x60660660,0x66066067,0xec3e1fe,0x7fe7fe7f,0xe7fe3fc3,0xfc3fc3fc,0x7f860e3f,0x83f83f83,0xf83f8000, 0x5fc3fc3f,0xc3fc3fc0,0x606006fc,0x7fc7fc7f,0xc7fc7fc7,0xfcffe3f8,0x3fc3fc3f,0xc3fc7fe7,0xfe7fe7fe,0x3f860c3f,0x83f83f83, 0xf83f8060,0x7f83fc3f,0xc3fc3fc0,0x607f8060,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x2201f80,0x3c1e7000,0x6006000, 0x600,0x60300,0xe01fe7f,0xc3f00183,0xe01f0180,0x1f01e006,0x600000,0x60,0x3006067f,0x807c7e07,0xfe6000f8,0x6063fc3e,0x6067fe6, 0x660e0f0,0x6000f060,0x3bf80601,0xf806030c,0x60e0607f,0xe06000c0,0x30000000,0x1ec6f,0xf01ec0,0xf80601ec,0x60c7fe03,0x61c03c6, 0x6660c1f0,0x6f01ec0c,0x3f007c1,0xcc0e030c,0x71c0c07f,0xc0600600,0x60000000,0x7804018,0xe01186,0x66040040,0x39e3f,0x80401fe0, 0x407fe040,0x4000000,0x0,0x0,0x3f,0x203ce0,0x407fc060,0x601f,0x3fe0000,0x60060018,0x0,0x0,0x0,0x7fe00,0x6,0xe6012000,0x0, 0x7e0,0x1807e1f0,0x60660660,0x66066066,0x6c3e07c,0x7fe7fe7f,0xe7fe3fc3,0xfc3fc3fc,0x7e060e0f,0xf00f00,0xf00f0000,0x8f01f81f, 0x81f81f80,0x60600670,0x1ec1ec1e,0xc1ec1ec1,0xec79c0f0,0xf80f80f,0x80f87fe7,0xfe7fe7fe,0x1f060c1f,0x1f01f01,0xf01f0000,0x4f01cc1c, 0xc1cc1cc0,0xc06f00c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200,0x0,0x6006000,0x600,0x600,0x0,0x0,0x0,0x0, 0x600000,0x0,0x18000000,0x0,0x0,0x0,0x0,0x0,0x1800,0x0,0x0,0x0,0x600060,0x30000000,0x0,0x0,0xc,0x3,0x0,0x0,0x60000c00,0x0, 0x0,0xc000,0x600600,0x60000000,0x18,0xc03100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x601f8,0x0,0x0,0x0,0x0,0x6, 0x12000,0x2000000,0x40,0x20004000,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0xc06000c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200,0x0,0x2004000,0xc00,0x0,0x0,0x0,0x0,0x0,0xc00000, 0x0,0x1c000000,0x0,0x0,0x0,0x0,0x0,0xc00,0x0,0x0,0x0,0x780000,0xf0000000,0x0,0x0,0x21c,0x3,0x0,0x0,0x60000c00,0x0,0x0,0xc000, 0x7c0603,0xe0000000,0x10,0xc02300,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x601f0,0x0,0x0,0x0,0x0,0x6,0x12000,0x1000000, 0x40,0x7e004000,0x0,0x0,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc06000c0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200,0x0,0x300c000,0xc00,0x0,0x0,0x0,0x0,0x0,0xc00000,0x0,0x7800000,0x0, 0x0,0x0,0x0,0x0,0x800,0x0,0x0,0x0,0x780000,0xf0000000,0x0,0x0,0x3f8,0x3e,0x0,0x0,0x60000c00,0x0,0x0,0x38000,0x3c0603,0xc0000000, 0x10,0xfc00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x60000,0x0,0x0,0x0,0x0,0x6,0x0,0x1000000,0x0,0x0,0x0,0x0, 0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x80600380,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xffc,0x0, 0x0,0x1f0,0x3c,0x0,0x0,0x60000c00,0x0,0x0,0x38000,0x600,0x0,0x0,0xf000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x6,0x0,0xe000000,0x0,0x0,0x0,0x0,0x70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x70,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x3,0x80600380,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xffc,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x600,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0 }; // Define a 16x32 font (large size). const unsigned int font16x32[16*32*256/32] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc300000,0x0,0xc300000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x70000e0,0x3c00730,0xe7001c0,0x0,0x70000e0,0x3c00e70,0x70000e0,0x3c00e70,0x730,0x70000e0,0x3c00730, 0xe700000,0x700,0xe003c0,0xe7000e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x6600000,0x0,0x6600000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x18001c0,0x6600ff0,0xe7003e0,0x0,0x18001c0,0x6600e70,0x18001c0,0x6600e70,0xff0,0x18001c0,0x6600ff0,0xe700000,0x180, 0x1c00660,0xe7001c0,0x0,0x0,0x0,0x380,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000, 0x0,0x3c00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c00380, 0xc300ce0,0xe700630,0x0,0x1c00380,0xc300e70,0x1c00380,0xc300e70,0xce0,0x1c00380,0xc300ce0,0xe700000,0x1c0,0x3800c30,0xe700380, 0x0,0x0,0x0,0x7c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xe000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1800000,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0xc300000,0x0,0xc300000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x700000,0x0,0x0,0x0,0x7c007c00,0x3e000000, 0x0,0x0,0x630,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe000070,0x1800000,0xc60,0x0,0xe000070,0x1800000,0xe000070, 0x1800000,0x0,0xe000070,0x1800000,0x0,0xe00,0x700180,0x70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x800000,0x0,0x600600,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x3f0,0xfc0,0x0,0x7000000,0x38000000,0x1c0000,0xfc0000,0x380001c0,0xe01c00,0x7f800000,0x0,0x0,0x0,0x0,0x0,0x0,0x7c, 0x1801f00,0x0,0x0,0x1c,0x0,0x0,0x3c00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7300000,0x6600000,0x0,0x6600000,0x0,0x0,0x0,0x0,0xe700000, 0x0,0x0,0x0,0x0,0x0,0xe00000,0x0,0x0,0x0,0xc000c00,0x43800000,0x0,0x0,0x630,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xf80,0x70000e0,0x3c00730,0xe700c60,0x0,0x70000e0,0x3c00e70,0x70000e0,0x3c00e70,0xe000730,0x70000e0,0x3c00730,0xe700000,0x700, 0xe003c0,0xe7000e0,0x38000e70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x6300000,0x803c00,0x7c00180, 0xc00300,0x1000000,0x0,0x1c,0x3c007c0,0xfc007e0,0xe01ff8,0x3f03ffc,0x7e007c0,0x0,0x0,0x7c0,0x1c0,0x7f8003f0,0x7f007ff8,0x7ff803f0, 0x70381ffc,0xff0700e,0x7000783c,0x783807c0,0x7fc007c0,0x7fc00fc0,0x7fff7038,0x700ee007,0x780f780f,0x7ffc03f0,0x70000fc0,0x3c00000, 0x3000000,0x38000000,0x1c0000,0x1fc0000,0x380001c0,0xe01c00,0x7f800000,0x0,0x0,0x0,0x0,0x0,0x0,0xfc,0x1801f80,0x0,0x1f80000, 0x7e,0x0,0x0,0x2400000,0xfc00000,0x7ff0000,0x7ffc0000,0x0,0x0,0x0,0x0,0xf30fb0c,0x2400000,0x0,0x240780f,0x1c0,0xfc,0x780f, 0x18003f0,0xe700000,0x7c00000,0x0,0xff0,0x3c00000,0x78007c0,0xc00000,0xff80000,0xf80,0x7c00000,0xc000c00,0x18001c0,0x1c001c0, 0x1c001c0,0x1c003e0,0x7fe03f0,0x7ff87ff8,0x7ff87ff8,0x1ffc1ffc,0x1ffc1ffc,0x7f007838,0x7c007c0,0x7c007c0,0x7c00000,0x7c67038, 0x70387038,0x7038780f,0x70001fe0,0x30000c0,0x2400f30,0xe700c60,0x0,0x30000c0,0x2400e70,0x30000c0,0x2400e70,0xf700f30,0x30000c0, 0x2400f30,0xe700000,0x300,0xc00240,0xe7000c0,0x38000e70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0, 0x630018c,0x807e00,0xfe00180,0xc00300,0x1000000,0x0,0x38,0xff01fc0,0x3ff01ff0,0x1e01ff8,0x7f83ffc,0x1ff80ff0,0x0,0x0,0xff0, 0x1f003e0,0x7fe00ff8,0x7fc07ff8,0x7ff80ff8,0x70381ffc,0xff0701c,0x7000783c,0x78381ff0,0x7fe01ff0,0x7fe01ff0,0x7fff7038,0x781ee007, 0x3c1e380e,0x7ffc0380,0x380001c0,0x3c00000,0x1800000,0x38000000,0x1c0000,0x3c00000,0x380001c0,0xe01c00,0x3800000,0x0,0x0, 0x0,0x7000000,0x0,0x0,0x1e0,0x18003c0,0x0,0x3fc0000,0x70,0x0,0x0,0x6600000,0x1ff00000,0x1fff0000,0x7ffc0000,0x0,0x0,0x0,0x0, 0xcf0239c,0x3c00000,0x0,0x3c0380e,0x1c0,0x2001fe,0x380e,0x18007f8,0xe700000,0x8600000,0x0,0xff0,0x7e00000,0x8c00870,0x1800000, 0x1ff80000,0x180,0xc600000,0xc000c00,0x38001c0,0x3e003e0,0x3e003e0,0x3e001c0,0x7fe0ff8,0x7ff87ff8,0x7ff87ff8,0x1ffc1ffc,0x1ffc1ffc, 0x7fc07838,0x1ff01ff0,0x1ff01ff0,0x1ff00000,0x1fec7038,0x70387038,0x7038380e,0x70003ce0,0x1800180,0x6600cf0,0xe7007c0,0x0, 0x1800180,0x6600e70,0x1800180,0x6600e70,0x7c00cf0,0x1800180,0x6600cf0,0xe700000,0x180,0x1800660,0xe700180,0x38000e70,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x630030c,0x3f0e700,0x1e200180,0x1800180,0x21100000,0x0, 0x38,0x1e7819c0,0x38781038,0x1e01c00,0xf080038,0x1c381c38,0x0,0x0,0x1878,0x7fc03e0,0x70e01e18,0x70e07000,0x70001e18,0x703801c0, 0x707038,0x70007c7c,0x7c381c70,0x70701c70,0x70703830,0x1c07038,0x381ce007,0x1c1c3c1e,0x3c0380,0x380001c0,0x7e00000,0xc00000, 0x38000000,0x1c0000,0x3800000,0x38000000,0x1c00,0x3800000,0x0,0x0,0x0,0x7000000,0x0,0x0,0x1c0,0x18001c0,0x0,0x70c0000,0xe0, 0x0,0x0,0xc300000,0x38300000,0x3c700000,0x3c0000,0x0,0x0,0x0,0x0,0xce022f4,0x1800000,0x0,0x1803c1e,0x1c0,0x2003c2,0x3c1e, 0x1800e08,0x7e0,0x300000,0x0,0x7e00000,0xe700000,0x600030,0x3000000,0x3f980000,0x180,0x18200000,0xc000c00,0x1e0001c0,0x3e003e0, 0x3e003e0,0x3e003e0,0xfe01e18,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x70e07c38,0x1c701c70,0x1c701c70,0x1c700000,0x3c787038, 0x70387038,0x70383c1e,0x70003870,0xc00300,0xc300ce0,0x380,0x0,0xc00300,0xc300000,0xc00300,0xc300000,0xfc00ce0,0xc00300,0xc300ce0, 0x0,0xc0,0x3000c30,0x300,0x38000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x630031c,0xff8c300, 0x1c000180,0x1800180,0x39380000,0x0,0x70,0x1c3801c0,0x203c001c,0x3e01c00,0x1c000038,0x381c3838,0x0,0x0,0x1038,0xe0e03e0,0x70703c08, 0x70707000,0x70003808,0x703801c0,0x707070,0x70007c7c,0x7c383838,0x70383838,0x70387010,0x1c07038,0x381c700e,0x1e3c1c1c,0x780380, 0x1c0001c0,0xe700000,0x0,0x38000000,0x1c0000,0x3800000,0x38000000,0x1c00,0x3800000,0x0,0x0,0x0,0x7000000,0x0,0x0,0x1c0,0x18001c0, 0x0,0xe000000,0xe0,0x0,0x1000100,0x3800,0x70100000,0x38700000,0x780000,0x1c0,0x7801ce0,0xe380000,0x0,0x2264,0x0,0x0,0x1c1c, 0x0,0x200780,0x1c1c,0x1800c00,0x1818,0x7f00000,0x0,0x18180000,0xc300000,0x600070,0x0,0x7f980000,0x180,0x18300000,0xc000c00, 0x3000000,0x3e003e0,0x3e003e0,0x3e003e0,0xee03c08,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x70707c38,0x38383838,0x38383838, 0x38380000,0x38387038,0x70387038,0x70381c1c,0x7fc03870,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xbc00000,0x0,0x0,0x0,0x0,0x0,0x0, 0x38000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x6300318,0xe88c300,0x1c000180,0x38001c0, 0xfe00180,0x0,0x70,0x1c3801c0,0x1c001c,0x6e01c00,0x1c000078,0x381c3818,0x0,0x40000,0x40000038,0x1c0607e0,0x70703800,0x70707000, 0x70003800,0x703801c0,0x7070e0,0x70007c7c,0x7c383838,0x70383838,0x70387000,0x1c07038,0x381c700e,0xf780e38,0x700380,0x1c0001c0, 0x1c380000,0x0,0x38000000,0x1c0000,0x3800000,0x38000000,0x1c00,0x3800000,0x0,0x0,0x0,0x7000000,0x0,0x0,0x1c0,0x18001c0,0x0, 0xe000000,0xe0,0x0,0x1000100,0x4400,0x70000000,0x38700000,0x700000,0xe0,0x7001c70,0xe380000,0x0,0x2264,0x0,0x0,0xe38,0x0, 0x200700,0xe38,0x1800c00,0x300c,0xc300000,0x0,0x300c0000,0xc300180,0x6003c0,0x0,0x7f980000,0x180,0x18300000,0xc000c00,0x1800000, 0x7e007e0,0x7e007e0,0x7e003e0,0xee03800,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x70707c38,0x38383838,0x38383838,0x38380000, 0x38387038,0x70387038,0x70380e38,0x7ff039f0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1e00000,0x0,0x0,0x0,0x40000,0x0,0x0,0x38000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x6300318,0x1c80e700,0x1c000180,0x38001c0,0x3800180, 0x0,0xe0,0x381c01c0,0x1c001c,0x6e01c00,0x38000070,0x381c381c,0x0,0x3c0000,0x78000078,0x38030770,0x70707800,0x70387000,0x70007000, 0x703801c0,0x7071c0,0x7000745c,0x7638701c,0x7038701c,0x70387000,0x1c07038,0x1c38718e,0x7700f78,0xf00380,0xe0001c0,0x381c0000, 0x7e0,0x39e003e0,0x79c03f0,0x3ffc079c,0x39e01fc0,0xfe01c1e,0x3807778,0x39e007e0,0x39e0079c,0x73c07e0,0x7ff83838,0x701ce007, 0x783c701c,0x1ffc01c0,0x18001c0,0x0,0x1c000100,0xe0,0x0,0x1000100,0x4200,0x70000000,0x70700100,0xf00100,0x10000e0,0x7000c70, 0xc700000,0x0,0x2204,0x7e00000,0x1e380100,0x1ffc0f78,0x0,0xf80700,0xf78,0x1800e00,0x63e6,0x18300000,0x0,0x6fe60000,0xe700180, 0xc00060,0x3838,0x7f980000,0x180,0x18300000,0xc000c00,0x18001c0,0x7700770,0x7700770,0x77007f0,0xee07800,0x70007000,0x70007000, 0x1c001c0,0x1c001c0,0x70387638,0x701c701c,0x701c701c,0x701c1008,0x707c7038,0x70387038,0x70380f78,0x707039c0,0x7e007e0,0x7e007e0, 0x7e007e0,0x1f3c03e0,0x3f003f0,0x3f003f0,0x1fc01fc0,0x1fc01fc0,0x7f039e0,0x7e007e0,0x7e007e0,0x7e00380,0x7ce3838,0x38383838, 0x3838701c,0x39e0701c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x6307fff,0x1c807e0c,0xe000180, 0x30000c0,0x3800180,0x0,0xe0,0x381c01c0,0x1c001c,0xce01fe0,0x38000070,0x381c381c,0x3800380,0xfc0000,0x7e0000f0,0x30030770, 0x70707000,0x70387000,0x70007000,0x703801c0,0x707380,0x700076dc,0x7638701c,0x7038701c,0x70387800,0x1c07038,0x1c3873ce,0x7f00770, 0xe00380,0xe0001c0,0x700e0000,0x1ff8,0x3ff00ff0,0xffc0ff8,0x3ffc0ffc,0x3bf01fc0,0xfe01c3c,0x3807f78,0x3bf00ff0,0x3ff00ffc, 0x77e0ff0,0x7ff83838,0x3838e007,0x3c783838,0x1ffc01c0,0x18001c0,0x0,0x7ff00380,0x1e0,0x0,0x1000100,0x4200,0x78000000,0x70700380, 0xe00380,0x3800060,0xe000e30,0x1c600000,0x0,0x2204,0xff00000,0x7f7c0380,0x1ffc0770,0x1c0,0x3fc0700,0x18040770,0x1800780,0x4e12, 0x18300104,0x0,0x4c320000,0x7e00180,0x1c00030,0x3838,0x7f980000,0x180,0x18302080,0xc000c00,0x18001c0,0x7700770,0x7700770, 0x7700770,0x1ee07000,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x70387638,0x701c701c,0x701c701c,0x701c381c,0x705c7038,0x70387038, 0x70380770,0x70383b80,0x1ff81ff8,0x1ff81ff8,0x1ff81ff8,0x3fbe0ff0,0xff80ff8,0xff80ff8,0x1fc01fc0,0x1fc01fc0,0xff83bf0,0xff00ff0, 0xff00ff0,0xff00380,0xffc3838,0x38383838,0x38383838,0x3ff03838,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x1c0,0x7fff,0x1c803c38,0xf000000,0x70000e0,0xfe00180,0x0,0x1c0,0x381c01c0,0x3c0078,0xce01ff0,0x39e000f0,0x1c38381c,0x3800380, 0x3e07ffc,0xf8001f0,0x307b0770,0x70e07000,0x70387000,0x70007000,0x703801c0,0x707700,0x700076dc,0x7638701c,0x7038701c,0x70387e00, 0x1c07038,0x1c3873ce,0x3e007f0,0x1e00380,0x70001c0,0x0,0x1038,0x3c381e18,0x1c7c1e3c,0x3801e3c,0x3c7801c0,0xe01c78,0x380739c, 0x3c781c38,0x3c381c3c,0x7c21e10,0x7003838,0x3838700e,0x1ef03838,0x3c01c0,0x18001c0,0x0,0x7fe007c0,0x1c0,0x0,0x1000100,0x6400, 0x7e000000,0x707007c0,0x1e007c0,0x7c00070,0xe000638,0x18600000,0x0,0x0,0x1e100000,0x73ce07c0,0x3c07f0,0x1c0,0x7240700,0x1ddc3ffe, 0x1800de0,0x8c01,0x1870030c,0x0,0x8c310000,0x3c00180,0x3800030,0x3838,0x7f980000,0x180,0x183030c0,0xc000c00,0x430001c0,0x7700770, 0x7700770,0x7700770,0x1ce07000,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x70387638,0x701c701c,0x701c701c,0x701c1c38,0x70dc7038, 0x70387038,0x703807f0,0x70383b80,0x10381038,0x10381038,0x10381038,0x21e71e18,0x1e3c1e3c,0x1e3c1e3c,0x1c001c0,0x1c001c0,0x1e383c78, 0x1c381c38,0x1c381c38,0x1c380380,0x1c383838,0x38383838,0x38383838,0x3c383838,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x1c0,0x630,0x1e8000e0,0x1f000000,0x70000e0,0x39380180,0x0,0x1c0,0x3b9c01c0,0x3c07f0,0x18e01078,0x3bf800e0, 0x7e0383c,0x3800380,0x1f807ffc,0x3f001c0,0x61ff0e38,0x7fc07000,0x70387ff0,0x7ff07000,0x7ff801c0,0x707f00,0x7000729c,0x7338701c, 0x7070701c,0x70703fc0,0x1c07038,0x1e7873ce,0x1c003e0,0x3c00380,0x70001c0,0x0,0x1c,0x3c381c00,0x1c3c1c1c,0x3801c3c,0x383801c0, 0xe01cf0,0x380739c,0x38381c38,0x3c381c3c,0x7801c00,0x7003838,0x3838700e,0xfe03c78,0x7801c0,0x18001c0,0x0,0x1c000c20,0xff8, 0x0,0x1ff01ff0,0x3818,0x3fc00100,0x707e0c20,0x3c00c20,0xc200030,0xc000618,0x18c00000,0x0,0x0,0x1c000080,0xe1ce0c20,0x7803e0, 0x1c0,0xe200700,0xff83ffe,0x1801878,0x9801,0x1cf0071c,0x7ffc0000,0x8c310000,0x7ffe,0x7000030,0x3838,0x3f980380,0x180,0xc6038e0, 0x7f9c7f9c,0x3e1c01c0,0xe380e38,0xe380e38,0xe380f78,0x1cfc7000,0x7ff07ff0,0x7ff07ff0,0x1c001c0,0x1c001c0,0xfe387338,0x701c701c, 0x701c701c,0x701c0e70,0x719c7038,0x70387038,0x703803e0,0x70383b80,0x1c001c,0x1c001c,0x1c001c,0xe71c00,0x1c1c1c1c,0x1c1c1c1c, 0x1c001c0,0x1c001c0,0x1c383838,0x1c381c38,0x1c381c38,0x1c380000,0x3c383838,0x38383838,0x38383c78,0x3c383c78,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x630,0xf800380,0x3f830000,0x70000e0,0x31080180,0x0,0x380,0x3b9c01c0, 0x7807e0,0x38e00038,0x3c3800e0,0xff01c3c,0x3800380,0x7c000000,0x7c03c0,0x61870e38,0x7fc07000,0x70387ff0,0x7ff070fc,0x7ff801c0, 0x707f80,0x7000739c,0x7338701c,0x7ff0701c,0x7fe00ff0,0x1c07038,0xe7073ce,0x1c003e0,0x3800380,0x38001c0,0x0,0x1c,0x381c3800, 0x381c380e,0x380381c,0x383801c0,0xe01de0,0x380739c,0x3838381c,0x381c381c,0x7001e00,0x7003838,0x1c70718e,0x7e01c70,0xf00380, 0x18001e0,0x1e000000,0x1c001bb0,0xff8,0x0,0x1000100,0xe0,0xff00300,0x707e1bb0,0x3801bb0,0x1bb00010,0x8000308,0x30c00000,0x0, 0x0,0x1e0000c0,0xe1ce1bb0,0xf003e0,0x1c0,0x1c203ff8,0x63003e0,0x180181c,0x9801,0xfb00e38,0x7ffc0000,0x8fc10000,0x7ffe,0xe000860, 0x3838,0x1f980380,0x180,0x7c01c70,0x1f001f0,0x1f003c0,0xe380e38,0xe380e38,0xe380e38,0x1cfc7000,0x7ff07ff0,0x7ff07ff0,0x1c001c0, 0x1c001c0,0xfe387338,0x701c701c,0x701c701c,0x701c07e0,0x731c7038,0x70387038,0x703803e0,0x70383980,0x1c001c,0x1c001c,0x1c001c, 0xe73800,0x380e380e,0x380e380e,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c0000,0x387c3838,0x38383838,0x38381c70, 0x381c1c70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0xc30,0x7f00e00,0x33c30000,0x70000e0,0x1007ffe, 0x0,0x380,0x3b9c01c0,0xf00078,0x30e0001c,0x3c1c01c0,0x1c381fdc,0x0,0x70000000,0x1c0380,0x63030e38,0x70707000,0x70387000,0x700070fc, 0x703801c0,0x707b80,0x7000739c,0x7338701c,0x7fc0701c,0x7fc001f0,0x1c07038,0xe703e5c,0x3e001c0,0x7800380,0x38001c0,0x0,0x7fc, 0x381c3800,0x381c380e,0x380381c,0x383801c0,0xe01fe0,0x380739c,0x3838381c,0x381c381c,0x7001fc0,0x7003838,0x1c70718e,0x7c01c70, 0xe01f00,0x180007c,0x7f8c0000,0x7fc03fb8,0x1c0,0x0,0x1000100,0x700,0x1f00600,0x70703fb8,0x7803fb8,0x3fb80000,0x8000000,0x180, 0x0,0x0,0x1fc00060,0xe1ce3fb8,0xe001c0,0x1c0,0x1c203ff8,0xc1801c0,0x180c,0x9801,0x1c70,0xc0000,0x8cc10000,0x180,0xfe007c0, 0x3838,0x7980380,0xff0,0xe38,0x3e003e00,0x3e000380,0xe380e38,0xe380e38,0xe380e38,0x38e07000,0x70007000,0x70007000,0x1c001c0, 0x1c001c0,0x70387338,0x701c701c,0x701c701c,0x701c03c0,0x731c7038,0x70387038,0x703801c0,0x703838e0,0x7fc07fc,0x7fc07fc,0x7fc07fc, 0xe73800,0x380e380e,0x380e380e,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c7ffc,0x38dc3838,0x38383838,0x38381c70, 0x381c1c70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0xc60,0xf83878,0x71e30000,0x70000e0,0x1007ffe, 0x7f0,0x380,0x381c01c0,0x1e0003c,0x60e0001c,0x381c01c0,0x381c079c,0x0,0x7c000000,0x7c0380,0x63031c1c,0x70307000,0x70387000, 0x7000701c,0x703801c0,0x7071c0,0x7000739c,0x71b8701c,0x7000701c,0x71e00078,0x1c07038,0xe703e7c,0x7e001c0,0xf000380,0x38001c0, 0x0,0x1ffc,0x381c3800,0x381c3ffe,0x380381c,0x383801c0,0xe01fc0,0x380739c,0x3838381c,0x381c381c,0x7000ff0,0x7003838,0x1ef03bdc, 0x3800ee0,0x1e01f00,0x180007c,0x61fc0000,0x7fc07f3c,0x1c0,0x0,0x1000100,0x1800,0x780c00,0x70707f3c,0xf007f3c,0x7f3c0000,0x0, 0x3c0,0x3ffcffff,0x0,0xff00030,0xe1fe7f3c,0x1e001c0,0x1c0,0x1c200700,0xc183ffe,0xe0c,0x9801,0x1ff038e0,0xc07f0,0x8c610000, 0x180,0x0,0x3838,0x1980380,0x0,0x1ff0071c,0xe000e000,0xe0000f80,0x1c1c1c1c,0x1c1c1c1c,0x1c1c1e38,0x38e07000,0x70007000,0x70007000, 0x1c001c0,0x1c001c0,0x703871b8,0x701c701c,0x701c701c,0x701c03c0,0x761c7038,0x70387038,0x703801c0,0x70703870,0x1ffc1ffc,0x1ffc1ffc, 0x1ffc1ffc,0xfff3800,0x3ffe3ffe,0x3ffe3ffe,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c7ffc,0x389c3838,0x38383838, 0x38380ee0,0x381c0ee0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0xfffc,0xbc60fc,0x70e30000,0x70000e0, 0x180,0x7f0,0x700,0x381c01c0,0x3e0001c,0x7ffc001c,0x381c03c0,0x381c001c,0x0,0x1f807ffc,0x3f00380,0x63031ffc,0x70387000,0x70387000, 0x7000701c,0x703801c0,0x7071e0,0x7000701c,0x71b8701c,0x7000701c,0x70f00038,0x1c07038,0x7e03e7c,0x77001c0,0xe000380,0x1c001c0, 0x0,0x3c1c,0x381c3800,0x381c3ffe,0x380381c,0x383801c0,0xe01fe0,0x380739c,0x3838381c,0x381c381c,0x70003f8,0x7003838,0xee03bdc, 0x3c00ee0,0x3c00380,0x18000e0,0xf00000,0x1c007e7c,0x3c0,0x0,0x1000100,0x0,0x381800,0x70707e7c,0xe007e7c,0x7e7c0000,0x0,0x7c0, 0x0,0x0,0x3f80018,0xe1fe7e7c,0x3c001c0,0x1c0,0x1c200700,0xc183ffe,0xf0c,0x8c01,0x38e0,0xc07f0,0x8c710000,0x180,0x0,0x3838, 0x1980000,0x0,0x71c,0x7000f0,0x700f00,0x1ffc1ffc,0x1ffc1ffc,0x1ffc1ffc,0x3fe07000,0x70007000,0x70007000,0x1c001c0,0x1c001c0, 0x703871b8,0x701c701c,0x701c701c,0x701c07e0,0x7c1c7038,0x70387038,0x703801c0,0x7ff03838,0x3c1c3c1c,0x3c1c3c1c,0x3c1c3c1c, 0x3fff3800,0x3ffe3ffe,0x3ffe3ffe,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c0000,0x391c3838,0x38383838,0x38380ee0, 0x381c0ee0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfffc,0x9c01ce,0x70f60000,0x70000e0,0x180, 0x0,0x700,0x381c01c0,0x780001c,0x7ffc001c,0x381c0380,0x381c003c,0x0,0x3e07ffc,0xf800380,0x63031ffc,0x70387000,0x70387000, 0x7000701c,0x703801c0,0x7070f0,0x7000701c,0x71b8701c,0x7000701c,0x70700038,0x1c07038,0x7e03e7c,0xf7801c0,0x1e000380,0x1c001c0, 0x0,0x381c,0x381c3800,0x381c3800,0x380381c,0x383801c0,0xe01fe0,0x380739c,0x3838381c,0x381c381c,0x7000078,0x7003838,0xee03a5c, 0x7c00fe0,0x78001c0,0x18001c0,0x0,0x1c003ef8,0x380,0x0,0x1000100,0x810,0x383000,0x70703ef8,0x1e003ef8,0x3ef80000,0x0,0x7c0, 0x0,0x0,0x78000c,0xe1c03ef8,0x78001c0,0x1c0,0x1c200700,0x63001c0,0x18003f8,0x4e12,0x1c70,0xc0000,0x4c320000,0x180,0x0,0x3838, 0x1980000,0x0,0xe38,0x700118,0x701e00,0x1ffc1ffc,0x1ffc1ffc,0x1ffc1ffc,0x7fe07000,0x70007000,0x70007000,0x1c001c0,0x1c001c0, 0x703871b8,0x701c701c,0x701c701c,0x701c0e70,0x7c1c7038,0x70387038,0x703801c0,0x7fc0381c,0x381c381c,0x381c381c,0x381c381c, 0x78e03800,0x38003800,0x38003800,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c0000,0x3b1c3838,0x38383838,0x38380fe0, 0x381c0fe0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1860,0x9c0186,0x707e0000,0x30000c0,0x180, 0x0,0xe00,0x183801c0,0xf00001c,0xe0001c,0x181c0380,0x381c0038,0x0,0xfc0000,0x7e000000,0x61873c1e,0x70383800,0x70707000,0x7000381c, 0x703801c0,0x707070,0x7000701c,0x70f83838,0x70003838,0x70780038,0x1c07038,0x7e03c3c,0xe3801c0,0x1c000380,0xe001c0,0x0,0x381c, 0x381c3800,0x381c3800,0x380381c,0x383801c0,0xe01ef0,0x380739c,0x3838381c,0x381c381c,0x7000038,0x7003838,0xfe03e7c,0xfe007c0, 0x70001c0,0x18001c0,0x0,0xe001ff0,0x380,0x0,0x1000100,0x162c,0x381800,0x30701ff0,0x1c001ff0,0x1ff00000,0x0,0x3c0,0x0,0x0, 0x380018,0xe1c01ff0,0x70001c0,0x1c0,0x1c200700,0xff801c0,0x18000f0,0x63e6,0xe38,0x0,0x6c3e0000,0x0,0x0,0x3838,0x1980000,0x0, 0x1c70,0xf0000c,0xf01c00,0x3c1e3c1e,0x3c1e3c1e,0x3c1e3c1c,0x70e03800,0x70007000,0x70007000,0x1c001c0,0x1c001c0,0x707070f8, 0x38383838,0x38383838,0x38381c38,0x38387038,0x70387038,0x703801c0,0x7000381c,0x381c381c,0x381c381c,0x381c381c,0x70e03800, 0x38003800,0x38003800,0x1c001c0,0x1c001c0,0x381c3838,0x381c381c,0x381c381c,0x381c0380,0x3e1c3838,0x38383838,0x383807c0,0x381c07c0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x18c0,0x9c0186,0x783c0000,0x38001c0,0x180,0x3800000, 0x3800e00,0x1c3801c0,0x1e00003c,0xe00038,0x1c1c0780,0x381c0038,0x3800380,0x3c0000,0x78000000,0x61ff380e,0x70383808,0x70707000, 0x7000381c,0x703801c0,0x40707078,0x7000701c,0x70f83838,0x70003838,0x70384038,0x1c07038,0x7e03c3c,0x1e3c01c0,0x3c000380,0xe001c0, 0x0,0x383c,0x3c381c00,0x1c3c1c00,0x3801c3c,0x383801c0,0xe01c78,0x380739c,0x38381c38,0x3c381c3c,0x7000038,0x7003878,0x7c01e78, 0x1ef007c0,0xf0001c0,0x18001c0,0x0,0xe000ee0,0x7800380,0xe380000,0x1001ff0,0x2242,0x40380c00,0x38700ee0,0x3c000ee0,0xee00000, 0x0,0x0,0x0,0x0,0x380030,0xe1c00ee0,0xf0001c0,0x1c0,0xe200700,0xdd801c0,0x1800038,0x300c,0x71c,0x0,0x300c0000,0x0,0x0,0x3838, 0x1980000,0x0,0x38e0,0xb0000c,0xb01c08,0x380e380e,0x380e380e,0x380e380e,0x70e03808,0x70007000,0x70007000,0x1c001c0,0x1c001c0, 0x707070f8,0x38383838,0x38383838,0x3838381c,0x38387038,0x70387038,0x703801c0,0x7000381c,0x383c383c,0x383c383c,0x383c383c, 0x70e01c00,0x1c001c00,0x1c001c00,0x1c001c0,0x1c001c0,0x1c383838,0x1c381c38,0x1c381c38,0x1c380380,0x1c383878,0x38783878,0x387807c0, 0x3c3807c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x18c0,0x10b801ce,0x3c3e0000,0x38001c0,0x180, 0x3800000,0x3801c00,0x1e7801c0,0x3c002078,0xe02078,0x1c380700,0x1c3810f0,0x3800380,0x40000,0x40000380,0x307b380e,0x70701e18, 0x70e07000,0x70001c1c,0x703801c0,0x60e0703c,0x7000701c,0x70f83c78,0x70003c70,0x703c70f0,0x1c03870,0x3c01c3c,0x3c1c01c0,0x78000380, 0x7001c0,0x0,0x3c7c,0x3c381e18,0x1c7c1e0c,0x3801c3c,0x383801c0,0xe01c38,0x3c0739c,0x38381c38,0x3c381c3c,0x7001078,0x7803c78, 0x7c01c38,0x1c780380,0x1e0001c0,0x18001c0,0x0,0x70c06c0,0x7000380,0xe300000,0x1000100,0x2142,0x70f00600,0x3c7006c0,0x780006c0, 0x6c00000,0x0,0x0,0x0,0x0,0x10780060,0x73e206c0,0x1e0001c0,0x1c0,0x7240700,0x180c01c0,0x1800018,0x1818,0x30c,0x0,0x18180000, 0x0,0x0,0x3c78,0x1980000,0x0,0x30c0,0x130000c,0x1301c18,0x380e380e,0x380e380e,0x380e380e,0x70e01e18,0x70007000,0x70007000, 0x1c001c0,0x1c001c0,0x70e070f8,0x3c783c78,0x3c783c78,0x3c781008,0x7c783870,0x38703870,0x387001c0,0x70003a3c,0x3c7c3c7c,0x3c7c3c7c, 0x3c7c3c7c,0x79f11e18,0x1e0c1e0c,0x1e0c1e0c,0x1c001c0,0x1c001c0,0x1c783838,0x1c381c38,0x1c381c38,0x1c380380,0x1c383c78,0x3c783c78, 0x3c780380,0x3c380380,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x38c0,0x1ff800fc,0x1fee0000, 0x1800180,0x180,0x3800000,0x3801c00,0xff01ffc,0x3ffc3ff0,0xe03ff0,0xff00700,0x1ff81fe0,0x3800380,0x0,0x380,0x3000780f,0x7ff00ff8, 0x7fc07ff8,0x70000ffc,0x70381ffc,0x7fe0701c,0x7ff8701c,0x70781ff0,0x70001ff0,0x701c7ff0,0x1c01fe0,0x3c01c38,0x380e01c0,0x7ffc0380, 0x7001c0,0x0,0x1fdc,0x3ff00ff0,0xffc0ffc,0x3800fdc,0x38383ffe,0xe01c3c,0x1fc739c,0x38380ff0,0x3ff00ffc,0x7001ff0,0x3f81fb8, 0x7c01c38,0x3c3c0380,0x1ffc01c0,0x18001c0,0x0,0x3fc0380,0x7000380,0xc70718c,0x1000100,0x2244,0x7ff00200,0x1fff0380,0x7ffc0380, 0x3800000,0x0,0x0,0x0,0x0,0x1ff000c0,0x7f7e0380,0x1ffc01c0,0x1c0,0x3fc3ffe,0x1c0,0x1800018,0x7e0,0x104,0x0,0x7e00000,0x7ffe, 0x0,0x3fde,0x1980000,0x0,0x2080,0x3300018,0x3300ff0,0x780f780f,0x780f780f,0x780f780e,0xf0fe0ff8,0x7ff87ff8,0x7ff87ff8,0x1ffc1ffc, 0x1ffc1ffc,0x7fc07078,0x1ff01ff0,0x1ff01ff0,0x1ff00000,0x7ff01fe0,0x1fe01fe0,0x1fe001c0,0x70003bf8,0x1fdc1fdc,0x1fdc1fdc, 0x1fdc1fdc,0x3fbf0ff0,0xffc0ffc,0xffc0ffc,0x3ffe3ffe,0x3ffe3ffe,0xff03838,0xff00ff0,0xff00ff0,0xff00000,0x3ff01fb8,0x1fb81fb8, 0x1fb80380,0x3ff00380,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1c0,0x31c0,0x7e00078,0x7cf0000,0x1800180, 0x0,0x3800000,0x3803800,0x3c01ffc,0x3ffc0fe0,0xe01fc0,0x3e00e00,0x7e00f80,0x3800380,0x0,0x380,0x18007007,0x7fc003f0,0x7f007ff8, 0x700003f0,0x70381ffc,0x3f80701e,0x7ff8701c,0x707807c0,0x700007c0,0x701e1fc0,0x1c00fc0,0x3c01818,0x780f01c0,0x7ffc0380,0x3801c0, 0x0,0xf9c,0x39e003e0,0x79c03f0,0x380079c,0x38383ffe,0xe01c1e,0x7c739c,0x383807e0,0x39e0079c,0x7000fc0,0x1f80f38,0x3801c38, 0x781e0380,0x1ffc01c0,0x18001c0,0x0,0x1f80100,0xe000700,0x1c60718c,0x1000100,0x1e3c,0x1fc00100,0x7ff0100,0x7ffc0100,0x1000000, 0x0,0x0,0x0,0x0,0xfc00080,0x3e3c0100,0x1ffc01c0,0x1c0,0xf83ffe,0x1c0,0x1800838,0x0,0x0,0x0,0x0,0x7ffe,0x0,0x3b9e,0x1980000, 0x0,0x0,0x2300038,0x23003e0,0x70077007,0x70077007,0x70077007,0xe0fe03f0,0x7ff87ff8,0x7ff87ff8,0x1ffc1ffc,0x1ffc1ffc,0x7f007078, 0x7c007c0,0x7c007c0,0x7c00000,0xc7c00fc0,0xfc00fc0,0xfc001c0,0x700039f0,0xf9c0f9c,0xf9c0f9c,0xf9c0f9c,0x1f1e03e0,0x3f003f0, 0x3f003f0,0x3ffe3ffe,0x3ffe3ffe,0x7e03838,0x7e007e0,0x7e007e0,0x7e00000,0x63e00f38,0xf380f38,0xf380380,0x39e00380,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x800000,0x0,0xc00300,0x0,0x3000000,0x3800,0x0,0x0,0x0,0x0, 0x0,0x300,0x0,0x0,0x1c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe0,0x0,0x0,0x0,0x0,0x380,0x3801c0,0x0,0x0,0x0,0x0,0x1c,0x0,0xe00000, 0x0,0x0,0x3800001c,0x0,0x0,0x0,0x700,0x1c0,0x18001c0,0x0,0x0,0xe000700,0x18600000,0x1000100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x200000,0x0,0x1800ff0,0x0,0x0,0x0,0x0,0x0,0x0,0x3800,0x1980000,0x1800000,0x0,0x6300070,0x6300000,0x0, 0x0,0x0,0xc0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xc0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x40000000, 0x0,0x700,0x38000700,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x800000,0x0,0xc00300,0x0,0x7000000, 0x7000,0x0,0x0,0x0,0x0,0x0,0x700,0x0,0x0,0xf040000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x78,0x0,0x0,0x0,0x0,0x3f0,0x1c0fc0,0x0,0x0, 0x0,0x0,0x1c,0x0,0xe00000,0x0,0x0,0x3800001c,0x0,0x0,0x0,0x700,0x1e0,0x18003c0,0x0,0x0,0xc000700,0x18c00000,0x1000000,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200000,0x0,0x18007e0,0x0,0x0,0x0,0x0,0x0,0x0,0x3800,0x1980000,0xc00000, 0x0,0x7f800e0,0x7f80000,0x0,0x0,0x0,0x60,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x60,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x700,0x38000700,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x800000, 0x0,0x600600,0x0,0x6000000,0x0,0x0,0x0,0x0,0x0,0x0,0x600,0x0,0x0,0x7fc0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30,0x0,0x0,0x0,0x0, 0x3f0,0xfc0,0x0,0x0,0x0,0x0,0x838,0x0,0x1e00000,0x0,0x0,0x3800001c,0x0,0x0,0x0,0xf00,0xfc,0x1801f80,0x0,0x0,0x8008e00,0x30c00000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200000,0x0,0x1800000,0x0,0x0,0x0,0x0,0x0,0x0,0x3800,0x1980000,0xc00000, 0x0,0x3001c0,0x300000,0x0,0x0,0x0,0x60,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x60,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0xf00,0x38000f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x800000,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfc0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0xff0,0x0,0x1fc00000,0x0,0x0,0x3800001c,0x0,0x0,0x0,0x3e00,0x7c,0x1801f00,0x0,0x0,0x800fe00,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x200000,0x0,0x1800000,0x0,0x0,0x0,0x0,0x0,0x0,0x3800,0x0,0x7c00000,0x0,0x3001fc,0x300000, 0x0,0x0,0x0,0x3e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x3e00,0x38003e00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfff8,0x0,0x0,0x0,0x7e0,0x0,0x1f000000, 0x0,0x0,0x3800001c,0x0,0x0,0x0,0x3c00,0x0,0x1800000,0x0,0x0,0x7800,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3800,0x0,0x7800000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00,0x38003c00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfff8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1800000,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0 }; // Define a 29x57 font (extra large size). const unsigned int font29x57[29*57*256/32] = { 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x781e00,0x0,0x0,0x7,0x81e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7c0000,0xf8000,0x7e00000,0x0,0x7, 0xc0000000,0x0,0x7c00,0xf80,0x7e000,0x0,0x7c00000,0xf80000,0x7e000000,0x0,0x0,0x1f00,0x3e0,0x1f800,0x0,0x0,0x0,0x3,0xe0000000, 0x7c00003f,0x0,0xf8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x3c3c00,0x0,0x0,0x3,0xc3c00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e1f00, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e0000, 0x1f0000,0x7e00000,0xf838001f,0xf80001f,0xf0000000,0x0,0x3e00,0x1f00,0x7e000,0x3e1f000,0x3e00000,0x1f00000,0x7e00003e,0x1f000000, 0x3e0,0xe0000f80,0x7c0,0x1f800,0x3e0e00,0x7c3e000,0x0,0x1,0xf0000000,0xf800003f,0x1f0f,0x800001f0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1e7800,0x0,0x0, 0x1,0xe7800000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1e0000,0x1e0000,0xff00001,0xfe38001f,0xf80003f, 0xf8000000,0x0,0x1e00,0x1e00,0xff000,0x3e1f000,0x1e00000,0x1e00000,0xff00003e,0x1f000000,0x7f8,0xe0000780,0x780,0x3fc00,0x7f8e00, 0x7c3e000,0x0,0x0,0xf0000000,0xf000007f,0x80001f0f,0x800001e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xef000,0x0,0x0,0x0,0xef000000,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf0000,0x3c0000,0x1e780003,0xfff8001f,0xf80003c,0x78000000,0x0,0xf00,0x3c00,0x1e7800, 0x3e1f000,0xf00000,0x3c00001,0xe780003e,0x1f000000,0xfff,0xe00003c0,0xf00,0x79e00,0xfffe00,0x7c3e000,0x0,0x0,0x78000001,0xe00000f3, 0xc0001f0f,0x800003c0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7e000,0x0,0x0,0x0,0x7e000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x78000,0x780000,0x3c3c0003,0x8ff0001f,0xf800078,0x3c000000,0x0,0x780,0x7800,0x3c3c00,0x3e1f000,0x780000,0x7800003,0xc3c0003e, 0x1f000000,0xe3f,0xc00001e0,0x1e00,0xf0f00,0xe3fc00,0x7c3e000,0x0,0x0,0x3c000003,0xc00001e1,0xe0001f0f,0x80000780,0x0,0x0, 0x0,0x0,0x0,0x0,0x1f,0xf0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x7e000,0x0,0x0,0x0,0x7e000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfc00,0x7e000,0xfe000,0x0,0x3c000,0xf00000,0x781e0003, 0x83e0001f,0xf800070,0x1c000000,0x0,0x3c0,0xf000,0x781e00,0x3e1f000,0x3c0000,0xf000007,0x81e0003e,0x1f000000,0xe0f,0x800000f0, 0x3c00,0x1e0780,0xe0f800,0x7c3e000,0x0,0x0,0x1e000007,0x800003c0,0xf0001f0f,0x80000f00,0x0,0x0,0x0,0x0,0x0,0x0,0x3f,0xf8000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3fc00,0x1fe000,0x3ff800,0x0,0x0,0x0,0x0,0x0,0x70,0x1c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c,0x78000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1f00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x78,0xf000000,0x0,0x0,0x780f0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7c0, 0x0,0x0,0x0,0x0,0x0,0x0,0x3fc00,0x1fe000,0x3ffc00,0x0,0x0,0x0,0x0,0x0,0x70,0x1c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1f00000,0x3e000,0x3e00000,0x0,0x78,0x3c000000,0x0,0x1f000,0x3e0, 0x3e000,0x0,0x1f000000,0x3e0000,0x3e000000,0x0,0x0,0x7c00,0xf8,0xf800,0x0,0x0,0x0,0xf,0x80000000,0x1f00001f,0x0,0x3e,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x30000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf80000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xf80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x781c0000,0x38,0xe000000,0x0,0x0,0x380e0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf80,0x0,0x0,0x0,0x0,0x0,0x0,0x39c00,0x1ce000,0x303e00, 0x0,0x0,0x0,0x0,0x0,0x78,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4000,0x0,0x0,0x0,0x0, 0x0,0x0,0xf80000,0x7c000,0x3e00000,0xf0380000,0x70,0x1c000000,0x0,0xf800,0x7c0,0x3e000,0x0,0xf800000,0x7c0000,0x3e000000, 0x0,0x3c0,0xe0003e00,0x1f0,0xf800,0x3c0e00,0x0,0x0,0x7,0xc0000000,0x3e00001f,0x0,0x7c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000,0xff,0x0, 0xf8,0xf8000,0x1c000,0x0,0x0,0x0,0x0,0x1f,0xc0000000,0x1ff8,0xff00,0x0,0x0,0x3fe000,0x0,0x1fc00001,0xfe000000,0x0,0x0,0x0, 0x0,0x7f800,0x0,0x0,0x0,0xff00000,0x0,0x0,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0xf8000000,0xfe,0x0,0x7f80,0x0,0x0,0x0,0x0,0x0, 0x0,0x3f,0xf0000000,0x7fe0,0x0,0x0,0x780000,0x1,0xe0000000,0x0,0x780000,0x3,0xfe000000,0x78000,0x3c00,0xf000,0x7800003,0xffe00000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfc0000f0,0x3f000,0x0,0x0,0x3fc00,0x0,0x0,0x1fc000,0x0,0x0,0x0,0x1fc0, 0x0,0xff000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xfe1c0000,0x1c,0x1c000000,0x0,0x0,0x1c1c0,0x0,0x0,0x0,0x0,0x1fe0000, 0x0,0x0,0x1ff,0x1f0f8,0x0,0xff000,0x0,0x0,0x0,0x3f,0xff00000f,0x80000000,0xfe0,0x3f80,0xf00,0x0,0x0,0x0,0x1,0xf8000003,0xe0000000, 0x1c00,0xe000,0xe00,0x0,0x0,0x0,0x0,0x0,0x3c,0x78000000,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7f0,0x3f80,0x1fc00,0xfe000, 0x7f0000,0x0,0x1fc07000,0x0,0x0,0x0,0x0,0x0,0x3f800,0x780000,0x78000,0x7f00001,0xfc38001f,0xf800070,0x1c000000,0x0,0x7800, 0x780,0x7f000,0x3e1f000,0x7800000,0x780000,0x7f00003e,0x1f0003f0,0x7f0,0xe0001e00,0x1e0,0x1fc00,0x7f0e00,0x7c3e000,0x0,0x3, 0xc0000000,0x3c00003f,0x80001f0f,0x80000078,0x1e0000,0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000,0x1e078000,0x30000000,0x3ff,0xc00001e0,0xf0, 0x78000,0x1c000,0x0,0x0,0x0,0x0,0x1e0007f,0xf000007e,0x1ffff,0x7ffe0,0x1f80,0x3ffff80,0xfff803,0xfffff800,0xfff80007,0xff800000, 0x0,0x0,0x0,0x0,0x1ffe00,0x0,0xfe0003,0xfff80000,0x3ffe01ff,0xe00003ff,0xffe01fff,0xff0003ff,0xe01e0007,0x803ffff0,0xfff80, 0x3c000fc0,0x7800001f,0x8003f07e,0x1e000f,0xfe0007ff,0xf00003ff,0x8007ffe0,0x1fff8,0x7fffffe,0xf0003c1,0xe000079e,0xf1f,0x1f3e0, 0x1f01ff,0xfff8003f,0xf003c000,0x7fe0,0x3f00,0x0,0x3c0000,0x1,0xe0000000,0x0,0x780000,0xf,0xfe000000,0x78000,0x3c00,0xf000, 0x7800003,0xffe00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0xfc0000f0,0x3fe00,0x0,0x0,0xfff00,0x0,0x0,0x3fe000, 0x0,0x0,0x0,0x1dc0,0x0,0x3fff00,0x0,0x3ffff80,0x1f,0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xff1c07ff,0x3c0f001e,0x3c000000, 0x0,0x0,0x1e3c0,0xf80007c,0x0,0x780000,0x0,0xfff8000,0x3e00,0x1f00000,0x7ff,0xc001f0f8,0x0,0x3ffc00,0x0,0x0,0x0,0x3f,0xff00003f, 0xe0000000,0x3ff8,0xffe0,0x1e00,0x0,0xfffc00,0x0,0x7,0xf800000f,0xf8000000,0x1c00,0xe000,0xe00,0xf000,0x1fc000,0xfe0000,0x7f00000, 0x3f800001,0xfc00003f,0xf80000ff,0xffc003ff,0xe007ffff,0xc03ffffe,0x1fffff0,0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01ffc, 0xfc00,0x3c001ffc,0xffe0,0x7ff00,0x3ff800,0x1ffc000,0x0,0x7ff8f0f0,0x3c0780,0x1e03c00,0xf01e000,0x783e0001,0xf01e0000,0xffe00, 0x3c0000,0xf0000,0x7700001,0xfe38001f,0xf800070,0x1c000000,0x0,0x3c00,0xf00,0x77000,0x3e1f000,0x3c00000,0xf00000,0x7700003e, 0x1f0000f8,0xc0007f8,0xe0000f00,0x3c0,0x1dc00,0x7f8e00,0x7c3e000,0x0,0x1,0xe0000000,0x7800003b,0x80001f0f,0x800000f0,0x1e0000, 0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x780000,0x3c1e0000,0x1e070000,0x300001f0,0x7ff,0xc00001e0,0x1e0,0x7c000,0x1c000,0x0,0x0,0x0,0x0,0x3c000ff,0xf80007fe, 0x3ffff,0x801ffff8,0x1f80,0x3ffff80,0x3fff803,0xfffff801,0xfffc000f,0xffc00000,0x0,0x0,0x0,0x0,0x7fff80,0x0,0xfe0003,0xffff0000, 0xffff01ff,0xfc0003ff,0xffe01fff,0xff000fff,0xf01e0007,0x803ffff0,0xfff80,0x3c001f80,0x7800001f,0xc007f07e,0x1e001f,0xff0007ff, 0xfc0007ff,0xc007fffc,0x3fffc,0x7fffffe,0xf0003c1,0xf0000f9e,0xf0f,0x8003e1e0,0x1e01ff,0xfff8003f,0xf001e000,0x7fe0,0x3f00, 0x0,0x1e0000,0x1,0xe0000000,0x0,0x780000,0x1f,0xfe000000,0x78000,0x3c00,0xf000,0x7800003,0xffe00000,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0xf,0xfc0000f0,0x3ff00,0x0,0x0,0x1fff80,0x0,0x0,0xffe000,0x0,0x0,0x0,0x3de0,0x0,0x7fff80,0x0,0xfffff80, 0x1f,0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0xe7bc07ff,0x3e1f000f,0x78000000,0x0,0x0,0xf780,0x7800078,0x0,0x780000,0x180000, 0x1fff8000,0x1e00,0x1e0003c,0xfff,0xc001f0f8,0x0,0x7ffe00,0x0,0x0,0x0,0x3f,0xff00007f,0xf0000000,0x3ffc,0xfff0,0x3c00,0x0, 0x7fffc00,0x0,0x7,0xf800003f,0xfe000000,0x1c00,0xe000,0xe00,0xf000,0x1fc000,0xfe0000,0x7f00000,0x3f800001,0xfc00001f,0xe00001ff, 0xffc00fff,0xf007ffff,0xc03ffffe,0x1fffff0,0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01fff,0xc000fc00,0x3c003ffe,0x1fff0, 0xfff80,0x7ffc00,0x3ffe000,0x0,0xfffce0f0,0x3c0780,0x1e03c00,0xf01e000,0x781e0001,0xe01e0000,0x3fff00,0x1e0000,0x1e0000,0xf780003, 0xcf78001f,0xf800078,0x3c000000,0x0,0x1e00,0x1e00,0xf7800,0x3e1f000,0x1e00000,0x1e00000,0xf780003e,0x1f0000fc,0x7c000f3d, 0xe0000780,0x780,0x3de00,0xf3de00,0x7c3e000,0x0,0x0,0xf0000000,0xf000007b,0xc0001f0f,0x800001e0,0x1e0000,0x3e1f00,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000, 0x3c1e0000,0x1e0f0000,0x300007fc,0xfff,0xc00001e0,0x1e0,0x3c000,0x1c000,0x0,0x0,0x0,0x0,0x3c001ff,0xfc001ffe,0x3ffff,0xc01ffffc, 0x3f80,0x3ffff80,0x7fff803,0xfffff803,0xfffe001f,0xffe00000,0x0,0x0,0x0,0x0,0xffff80,0x7f800,0xfe0003,0xffff8001,0xffff01ff, 0xff0003ff,0xffe01fff,0xff001fff,0xf01e0007,0x803ffff0,0xfff80,0x3c003f00,0x7800001f,0xc007f07f,0x1e003f,0xff8007ff,0xff000fff, 0xe007ffff,0x7fffc,0x7fffffe,0xf0003c0,0xf0000f1e,0xf07,0x8003c1f0,0x3e01ff,0xfff8003f,0xf001e000,0x7fe0,0x7f80,0x0,0xe0000, 0x1,0xe0000000,0x0,0x780000,0x1f,0xfe000000,0x78000,0x3c00,0xf000,0x7800003,0xffe00000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c000,0x0, 0x0,0x0,0x0,0x0,0xf,0xfc0000f0,0x3ff00,0x0,0x0,0x3fff80,0x0,0x0,0xffe000,0x0,0x0,0x0,0x78f0,0x0,0xffff80,0x0,0x3fffff80,0x1f, 0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0xc7f80070,0x3e1f0007,0x70000000,0x0,0x0,0x7700,0x7c000f8,0x0,0x780000,0x180000, 0x3fff8000,0x1f00,0x3e0003c,0x1f03,0xc001f0f8,0x0,0x703f00,0x0,0x0,0x0,0x3f,0xff0000f0,0xf8000000,0x303e,0xc0f8,0x7800,0x0, 0xffffc00,0x0,0x7,0x3800003e,0x3e000000,0x1c00,0xe000,0x3c00,0xf000,0x1fc000,0xfe0000,0x7f00000,0x3f800001,0xfc00000f,0xe00001ff, 0xffc01fff,0xf007ffff,0xc03ffffe,0x1fffff0,0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01fff,0xf000fe00,0x3c007fff,0x3fff8, 0x1fffc0,0xfffe00,0x7fff000,0x1,0xffffc0f0,0x3c0780,0x1e03c00,0xf01e000,0x781f0003,0xe01e0000,0x3fff80,0xe0000,0x3c0000,0x1e3c0003, 0x8ff0001f,0xf80003c,0x78000000,0x0,0xe00,0x3c00,0x1e3c00,0x3e1f000,0xe00000,0x3c00001,0xe3c0003e,0x1f00007f,0xf8000e3f,0xc0000380, 0xf00,0x78f00,0xe3fc00,0x7c3e000,0x0,0x0,0x70000001,0xe00000f1,0xe0001f0f,0x800003c0,0x1e0000,0x3e1f00,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000,0x3c0f0000, 0x30000ffe,0xf80,0xc00001e0,0x3c0,0x1e000,0x101c040,0x0,0x0,0x0,0x0,0x78003f0,0x7e001ffe,0x3f807,0xe01f00fe,0x3f80,0x3ffff80, 0x7e01803,0xfffff007,0xe03f003f,0x3f00000,0x0,0x0,0x0,0x0,0xfc0fc0,0x3ffe00,0xfe0003,0xffffc003,0xf81f01ff,0xff8003ff,0xffe01fff, 0xff003f01,0xf01e0007,0x803ffff0,0xfff80,0x3c007e00,0x7800001f,0xc007f07f,0x1e007e,0xfc007ff,0xff801f83,0xf007ffff,0x800fc07c, 0x7fffffe,0xf0003c0,0xf0000f0f,0x1e07,0xc007c0f8,0x7c01ff,0xfff8003c,0xf000,0x1e0,0xffc0,0x0,0xf0000,0x1,0xe0000000,0x0,0x780000, 0x3e,0x0,0x78000,0x3c00,0xf000,0x7800000,0x1e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c000,0x0,0x0,0x0,0x0,0x0,0x1f,0x800000f0,0x1f80, 0x0,0x0,0x7e0780,0x0,0x0,0x1f82000,0x0,0x0,0x0,0x7070,0x0,0x1f80f80,0x0,0x7fffff80,0x1f,0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x1,0xc3f80070,0x3f3f0007,0xf0000000,0x0,0x0,0x7f00,0x3e001f0,0x0,0x780000,0x180000,0x7f018000,0xf80,0x7c0003c,0x3e00, 0x4001f0f8,0xfe00,0x400f00,0x0,0x0,0x0,0x7f000000,0xe0,0x38000000,0x1e,0x38,0x7800,0x0,0x1ffe1c00,0x0,0x0,0x38000078,0xf000000, 0x1c00,0xe000,0x7f800,0xf000,0x1fc000,0xfe0000,0x7f00000,0x3f800001,0xfc00001f,0xf00001ff,0xffc03f81,0xf007ffff,0xc03ffffe, 0x1fffff0,0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01fff,0xf800fe00,0x3c00fc1f,0x8007e0fc,0x3f07e0,0x1f83f00,0xfc1f800, 0x3,0xf07fc0f0,0x3c0780,0x1e03c00,0xf01e000,0x780f8007,0xc01e0000,0x7e0fc0,0xf0000,0x3c0000,0x1c1c0003,0x87f0001f,0xf80003f, 0xf8000000,0x0,0xf00,0x3c00,0x1c1c00,0x3e1f000,0xf00000,0x3c00001,0xc1c0003e,0x1f00003f,0xc0000e1f,0xc00003c0,0xf00,0x70700, 0xe1fc00,0x7c3e000,0x0,0x0,0x78000001,0xe00000e0,0xe0001f0f,0x800003c0,0x1e0000,0x3e1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000,0x3c0f0001,0xff801e0f, 0x1f00,0x1e0,0x3c0,0x1e000,0x3c1c1e0,0x0,0x0,0x0,0x0,0x78007c0,0x1f001f9e,0x3c001,0xf010003e,0x7780,0x3c00000,0xf800000,0xf007, 0xc01f007c,0x1f80000,0x0,0x0,0x0,0x0,0xe003e0,0x7fff00,0x1ef0003,0xc007e007,0xc00301e0,0x1fc003c0,0x1e00,0x7c00,0x301e0007, 0x80007800,0x780,0x3c00fc00,0x7800001f,0xe00ff07f,0x1e00f8,0x3e00780,0x1fc03e00,0xf807801f,0xc01f001c,0xf000,0xf0003c0,0xf0000f0f, 0x1e03,0xc00f8078,0x780000,0xf0003c,0xf000,0x1e0,0x1f3e0,0x0,0x78000,0x1,0xe0000000,0x0,0x780000,0x3c,0x0,0x78000,0x0,0x0, 0x7800000,0x1e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c000,0x0,0x0,0x0,0x0,0x0,0x1f,0xf0,0xf80,0x0,0x0,0xf80180,0x0,0x0,0x1e00000, 0x0,0x0,0x0,0xe038,0x0,0x3e00380,0x0,0xfe0f0000,0x0,0xf0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0xc0f00070,0x3b370003,0xe0000000, 0x0,0x0,0x3e00,0x1e001e0,0x0,0x780000,0x180000,0x7c000000,0x780,0x780003c,0x3c00,0x0,0x7ffc0,0x780,0x0,0x0,0x3,0xffe00000, 0x1c0,0x3c000000,0xe,0x38,0xf000,0x0,0x3ffe1c00,0x0,0x0,0x38000078,0xf000000,0x1c00,0xe000,0x7f000,0xf000,0x3de000,0x1ef0000, 0xf780000,0x7bc00003,0xde00001e,0xf00003e7,0x80007c00,0x30078000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001, 0xe0001e03,0xfc00fe00,0x3c01f007,0xc00f803e,0x7c01f0,0x3e00f80,0x1f007c00,0x7,0xc01f80f0,0x3c0780,0x1e03c00,0xf01e000,0x78078007, 0x801e0000,0x7803c0,0x78000,0x780000,0x380e0003,0x81e00000,0x1f,0xf0000000,0x0,0x780,0x7800,0x380e00,0x0,0x780000,0x7800003, 0x80e00000,0x1ff,0x80000e07,0x800001e0,0x1e00,0xe0380,0xe07800,0x0,0x0,0x0,0x3c000003,0xc00001c0,0x70000000,0x780,0x1e0000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x780000,0x3c1e0000,0x3c0e0007,0xfff01c07,0x1e00,0x1e0,0x780,0xf000,0x3e1c3e0,0x0,0x0,0x0,0x0,0xf0007c0,0x1f00181e,0x20000, 0xf000001f,0xf780,0x3c00000,0x1f000000,0x1f00f,0x800f8078,0xf80000,0x0,0x0,0x0,0x0,0x8003e0,0x1fc0f80,0x1ef0003,0xc001e007, 0x800101e0,0x7e003c0,0x1e00,0x7800,0x101e0007,0x80007800,0x780,0x3c00f800,0x7800001e,0xe00ef07f,0x801e00f0,0x1e00780,0x7c03c00, 0x78078007,0xc01e0004,0xf000,0xf0003c0,0x78001e0f,0x1e03,0xe00f807c,0xf80000,0x1f0003c,0x7800,0x1e0,0x3e1f0,0x0,0x3c000,0x1, 0xe0000000,0x0,0x780000,0x3c,0x0,0x78000,0x0,0x0,0x7800000,0x1e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c000,0x0,0x0,0x0,0x0,0x0, 0x1e,0xf0,0x780,0x0,0x0,0x1f00080,0x0,0x0,0x3c00000,0x0,0x0,0x0,0x1e03c,0x0,0x3c00080,0x0,0xf80f0000,0x0,0x1f0000,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x70,0x3bf70003,0xe0000000,0x0,0x0,0x3e00,0x1f003e0,0x0,0x780000,0x180000,0x78000000,0x7c0,0xf80003c, 0x3c00,0x0,0x1f01f0,0x780,0x0,0x0,0xf,0x80f80000,0x1c0,0x1c000000,0xe,0x38,0x1e000,0x0,0x7ffe1c00,0x0,0x0,0x380000f0,0x7800000, 0x1c00,0xe000,0x7fc00,0xf000,0x3de000,0x1ef0000,0xf780000,0x7bc00003,0xde00001e,0xf00003c7,0x80007800,0x10078000,0x3c0000, 0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x7e00ff00,0x3c01e003,0xc00f001e,0x7800f0,0x3c00780,0x1e003c00, 0x7,0x800f00f0,0x3c0780,0x1e03c00,0xf01e000,0x7807c00f,0x801e0000,0xf803c0,0x3c000,0xf00000,0x780f0000,0x0,0x7,0xc0000000, 0x0,0x3c0,0xf000,0x780f00,0x0,0x3c0000,0xf000007,0x80f00000,0x7ff,0xc0000000,0xf0,0x3c00,0x1e03c0,0x0,0x0,0x0,0x0,0x1e000007, 0x800003c0,0x78000000,0xf00,0x1e0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000,0x3c1e001f,0xfff03803,0x80001e00,0x1e0,0x780,0xf000,0xf9cf80, 0x0,0x0,0x0,0x0,0xf000780,0xf00001e,0x0,0xf800000f,0xe780,0x3c00000,0x1e000000,0x1e00f,0x78078,0x7c0000,0x0,0x0,0x0,0x0,0x1e0, 0x3f003c0,0x1ef0003,0xc000f00f,0x800001e0,0x1f003c0,0x1e00,0xf000,0x1e0007,0x80007800,0x780,0x3c01f000,0x7800001e,0xe00ef07f, 0x801e01f0,0x1e00780,0x3c07c00,0x78078003,0xc03e0000,0xf000,0xf0003c0,0x78001e0f,0x1e01,0xf01f003c,0xf00000,0x3e0003c,0x7800, 0x1e0,0x7c0f8,0x0,0x0,0x1,0xe0000000,0x0,0x780000,0x3c,0x0,0x78000,0x0,0x0,0x7800000,0x1e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x3c000, 0x0,0x0,0x0,0x0,0x0,0x1e,0xf0,0x780,0x0,0x0,0x1e00000,0x0,0x0,0x3c00000,0x0,0x8,0x40,0x0,0x7e0000,0x7c00000,0x1,0xf00f0000, 0x0,0x3e0000,0x0,0x3f,0xfc0,0xfc3f0,0xfc3f0,0x0,0x0,0x0,0x70,0x39e70000,0x0,0x0,0x0,0x0,0xf003c0,0x0,0x0,0x180000,0xf8000000, 0x3c0,0xf00003c,0x3c00,0x0,0x3c0078,0x7ff80,0x0,0x0,0x1e,0x3c0000,0x1c0,0x1c000000,0xe,0xf0,0x0,0x0,0x7ffe1c00,0x0,0x0,0x380000f0, 0x7800000,0x1c00,0xe000,0x3c00,0x0,0x3de000,0x1ef0000,0xf780000,0x7bc00003,0xde00001e,0xf00003c7,0x8000f800,0x78000,0x3c0000, 0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x1f00ff00,0x3c03e003,0xc01f001e,0xf800f0,0x7c00780,0x3e003c00, 0xf,0x800f80f0,0x3c0780,0x1e03c00,0xf01e000,0x7803c00f,0x1fffc0,0xf001e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x307,0xe0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1e0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000,0x781e003f,0xfff03803, 0x80001e00,0x1e0,0xf80,0xf000,0x3dde00,0x0,0x0,0x0,0x0,0xf000f00,0x780001e,0x0,0x7800000f,0x1e780,0x3c00000,0x3e000000,0x3e00f, 0x780f0,0x7c0000,0x0,0x0,0x0,0x0,0x1e0,0x7c001e0,0x3ef8003,0xc000f00f,0x1e0,0xf003c0,0x1e00,0xf000,0x1e0007,0x80007800,0x780, 0x3c03e000,0x7800001e,0xf01ef07b,0xc01e01e0,0xf00780,0x3e07800,0x3c078003,0xe03c0000,0xf000,0xf0003c0,0x78001e0f,0x1e00,0xf01e003e, 0x1f00000,0x3c0003c,0x7800,0x1e0,0x78078,0x0,0x0,0x1,0xe0000000,0x0,0x780000,0x3c,0x0,0x78000,0x0,0x0,0x7800000,0x1e00000, 0x0,0x0,0x0,0x0,0x0,0x0,0x3c000,0x0,0x0,0x0,0x0,0x0,0x1e,0xf0,0x780,0x0,0x0,0x1e00000,0x0,0x0,0x3c00000,0x0,0x18,0xc0,0x0, 0xe70000,0x7800000,0x1,0xe00f0000,0x0,0x3c0000,0x0,0x3f,0xfc0,0xfc1f0,0x1f83f0,0x0,0x0,0x0,0x70,0x39e70000,0x0,0x0,0x0,0x0, 0xf807c0,0x0,0x0,0x180000,0xf0000000,0x3e0,0x1f00003c,0x3e00,0x0,0x70001c,0x3fff80,0x0,0x0,0x38,0xe0000,0x1c0,0x1c000078, 0x1c,0x1fe0,0x0,0x0,0xfffe1c00,0x0,0x0,0x380000f0,0x7800000,0x1c00,0xe000,0xe00,0x0,0x7df000,0x3ef8000,0x1f7c0000,0xfbe00007, 0xdf00003c,0x780003c7,0x8000f000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0xf00f780, 0x3c03c001,0xe01e000f,0xf00078,0x78003c0,0x3c001e00,0xf,0xf80f0,0x3c0780,0x1e03c00,0xf01e000,0x7803e01f,0x1ffff8,0xf001e0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0xe0000000,0x0,0x0,0x0,0x0,0x0,0x0,0xc000,0x0,0x0,0x0,0x0,0x1e0000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x780000,0x3c1e0000,0x781e003e,0x30703803,0x80001e00,0x1e0,0xf00,0x7800,0xff800,0x1e0000,0x0,0x0,0x0,0x1e000f00,0x780001e, 0x0,0x7800000f,0x3c780,0x3c00000,0x3c000000,0x3c00f,0x780f0,0x3c0000,0x0,0x0,0x2000000,0x800000,0x1e0,0x78000e0,0x3c78003, 0xc000f01e,0x1e0,0xf803c0,0x1e00,0x1e000,0x1e0007,0x80007800,0x780,0x3c07c000,0x7800001e,0x701cf07b,0xc01e01e0,0xf00780,0x1e07800, 0x3c078001,0xe03c0000,0xf000,0xf0003c0,0x7c003e0f,0x1e00,0xf83e001e,0x1e00000,0x7c0003c,0x3c00,0x1e0,0xf807c,0x0,0x0,0x1fe0001, 0xe1fc0000,0x7f00003,0xf8780007,0xf000003c,0x7f0,0x783f0,0x0,0x0,0x7800000,0x1e00000,0x3e0f8000,0xfc00007,0xf8000007,0xf00001fc, 0xf,0xc0003fc0,0x3c000,0x0,0x0,0x0,0x0,0x0,0x1e,0xf0,0x780,0x0,0x0,0x3c00000,0x0,0x0,0x3c00000,0x0,0x18,0xc0,0x0,0x1818000, 0x7800000,0x1,0xe00f0000,0x0,0x7c0000,0x0,0x1f,0x80001f80,0x7c1f8,0x1f83e0,0x0,0x0,0x0,0x70,0x38c70007,0xf8000000,0x7f03, 0xf0000000,0x0,0x780780,0x0,0x0,0xfe0000,0xf0000000,0x1e0,0x1e00003c,0x3f00,0x0,0xe07f0e,0x7fff80,0x0,0x0,0x70,0x70000,0x1c0, 0x1c000078,0x3c,0x1fc0,0x0,0x0,0xfffe1c00,0x0,0x0,0x380000f0,0x7800000,0x1c00,0xe000,0xe00,0x0,0x78f000,0x3c78000,0x1e3c0000, 0xf1e00007,0x8f00003c,0x78000787,0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00, 0xf80f780,0x3c03c001,0xe01e000f,0xf00078,0x78003c0,0x3c001e00,0xf,0x1f80f0,0x3c0780,0x1e03c00,0xf01e000,0x7801e01e,0x1ffffc, 0xf007e0,0x3fc000,0x1fe0000,0xff00000,0x7f800003,0xfc00001f,0xe0000fc0,0xfc00007f,0xfe0,0x7f00,0x3f800,0x1fc000,0x0,0x0,0x0, 0x1,0xf000001f,0x80000ff0,0x7f80,0x3fc00,0x1fe000,0xff0000,0x1f80000,0x1fc1e000,0x0,0x0,0x0,0x0,0x1e1fc0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e0000, 0x781c007c,0x30003803,0x80001f00,0x1e0,0xf00,0x7800,0x7f000,0x1e0000,0x0,0x0,0x0,0x1e000f00,0x780001e,0x0,0x7800000f,0x3c780, 0x3c00000,0x3c000000,0x3c00f,0x780f0,0x3c0000,0x0,0x0,0x1e000000,0xf00000,0x3e0,0xf0000e0,0x3c78003,0xc000f01e,0x1e0,0x7803c0, 0x1e00,0x1e000,0x1e0007,0x80007800,0x780,0x3c0f8000,0x7800001e,0x701cf079,0xe01e01e0,0xf00780,0x1e07800,0x3c078001,0xe03c0000, 0xf000,0xf0003c0,0x3c003c0f,0x3e00,0x787c001f,0x3e00000,0xf80003c,0x3c00,0x1e0,0x1f003e,0x0,0x0,0x1fffc001,0xe7ff0000,0x3ffe000f, 0xfe78003f,0xfc001fff,0xfe001ffc,0xf0078ffc,0x1ffc00,0x7ff000,0x7800f80,0x1e0000f,0x7f1fc01e,0x3ff0001f,0xfe00079f,0xfc0007ff, 0x3c003c7f,0xf001fff8,0x1fffff0,0x3c003c0,0xf0000f1e,0xf1f,0x7c1f0,0x1f00ff,0xffe0001e,0xf0,0x780,0x0,0x0,0x3c00000,0x100000, 0x0,0x7800000,0x0,0x18,0xc0,0x0,0x1818000,0x7800000,0x1,0xe00f0000,0x1000000,0xf80000,0x40000002,0xf,0x80001f00,0x7e0f8,0x1f07c0, 0x0,0x0,0x0,0x70,0x38c7003f,0xff000000,0xff8f,0xf8000100,0xffffe,0x7c0f80,0x0,0x0,0x3ffc000,0xf0000020,0x1001f0,0x3c00003c, 0x1f80,0x0,0x1c3ffc7,0x7c0780,0x0,0x0,0xe3,0xff038000,0xe0,0x38000078,0x78,0x1ff0,0x0,0x3c003c0,0xfffe1c00,0x0,0x0,0x380000f0, 0x7800000,0x1c00,0xe000,0xe00,0xf000,0x78f000,0x3c78000,0x1e3c0000,0xf1e00007,0x8f00003c,0x78000787,0x8001e000,0x78000,0x3c0000, 0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x780f3c0,0x3c03c001,0xe01e000f,0xf00078,0x78003c0,0x3c001e00, 0x4000200f,0x3f80f0,0x3c0780,0x1e03c00,0xf01e000,0x7801f03e,0x1ffffe,0xf01fe0,0x3fff800,0x1fffc000,0xfffe0007,0xfff0003f, 0xff8001ff,0xfc003ff3,0xfe0003ff,0xe0007ff8,0x3ffc0,0x1ffe00,0xfff000,0x3ff80001,0xffc0000f,0xfe00007f,0xf000003f,0xf8003c7f, 0xe0003ffc,0x1ffe0,0xfff00,0x7ff800,0x3ffc000,0x1f80000,0xfff1c03c,0x3c01e0,0x1e00f00,0xf007800,0x781f0001,0xf01e7ff0,0x7c0007c, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000, 0x3c1e003f,0xfffff078,0x30003803,0x80000f00,0x1e0,0x1f00,0x7800,0x7f000,0x1e0000,0x0,0x0,0x0,0x3c000f00,0x780001e,0x0,0x7800000f, 0x78780,0x3c00000,0x3c000000,0x7c00f,0x780f0,0x3c0007,0xe000003f,0x0,0xfe000000,0xfe0000,0x3c0,0x1f000070,0x7c7c003,0xc000f01e, 0x1e0,0x7803c0,0x1e00,0x1e000,0x1e0007,0x80007800,0x780,0x3c1f0000,0x7800001e,0x783cf079,0xe01e03c0,0xf00780,0x1e0f000,0x3c078001, 0xe03c0000,0xf000,0xf0003c0,0x3c003c07,0x81f03c00,0x7c7c000f,0x87c00000,0xf00003c,0x1e00,0x1e0,0x3e001f,0x0,0x0,0x3fffe001, 0xefff8000,0x7fff001f,0xff78007f,0xfe001fff,0xfe003ffe,0xf0079ffe,0x1ffc00,0x7ff000,0x7801f00,0x1e0000f,0xffbfe01e,0x7ff8003f, 0xff0007bf,0xfe000fff,0xbc003cff,0xf803fffc,0x1fffff0,0x3c003c0,0x78001e1e,0xf0f,0x800f80f0,0x1e00ff,0xffe0001e,0xf0,0x780, 0x0,0x0,0x3c00000,0x380000,0x0,0x7800000,0x0,0x18,0xc0,0x0,0x1008000,0x7800000,0x3,0xe00f0000,0x3800000,0xf00000,0xe0000007, 0xf,0x80001f00,0x3e0f8,0x1e07c0,0x0,0x0,0x0,0x70,0x3807007f,0xff800000,0x1ffdf,0xfc000380,0xffffe,0x3e1f00,0x0,0x0,0xfffe000, 0xf0000030,0x3800f8,0x7c00003c,0xfc0,0x0,0x18780c3,0xf00780,0x80100,0x0,0xc3,0xffc18000,0xf0,0x78000078,0xf0,0xf0,0x0,0x3c003c0, 0xfffe1c00,0x0,0x0,0x380000f0,0x7800801,0x1c00,0xe000,0x1e00,0xf000,0xf8f800,0x7c7c000,0x3e3e0001,0xf1f0000f,0x8f80007c,0x7c000787, 0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x780f3c0,0x3c078001,0xe03c000f, 0x1e00078,0xf0003c0,0x78001e00,0xe000701f,0x3fc0f0,0x3c0780,0x1e03c00,0xf01e000,0x7800f87c,0x1e007f,0xf07e00,0x7fffc00,0x3fffe001, 0xffff000f,0xfff8007f,0xffc003ff,0xfe007ff7,0xff0007ff,0xf000fffc,0x7ffe0,0x3fff00,0x1fff800,0x3ff80001,0xffc0000f,0xfe00007f, 0xf00000ff,0xf8003cff,0xf0007ffe,0x3fff0,0x1fff80,0xfffc00,0x7ffe000,0x1f80001,0xfffb803c,0x3c01e0,0x1e00f00,0xf007800,0x780f0001, 0xe01efff8,0x3c00078,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x780000,0x3c1e003f,0xfffff078,0x30001c07,0xf80,0x1e0,0x1e00,0x3c00,0xff800,0x1e0000,0x0,0x0,0x0,0x3c001e00, 0x3c0001e,0x0,0x7800001e,0x70780,0x3c00000,0x78000000,0x78007,0x800f00f0,0x3e0007,0xe000003f,0x3,0xfe000000,0xff8000,0x7c0, 0x1e000070,0x783c003,0xc001f01e,0x1e0,0x7803c0,0x1e00,0x1e000,0x1e0007,0x80007800,0x780,0x3c3e0000,0x7800001e,0x3838f079, 0xe01e03c0,0x780780,0x1e0f000,0x1e078001,0xe03c0000,0xf000,0xf0003c0,0x3c007c07,0x81f03c00,0x3ef80007,0x87800000,0x1f00003c, 0x1e00,0x1e0,0x7c000f,0x80000000,0x0,0x3ffff001,0xffffc000,0xffff003f,0xff7800ff,0xff001fff,0xfe007ffe,0xf007bffe,0x1ffc00, 0x7ff000,0x7803e00,0x1e0000f,0xffffe01e,0xfff8007f,0xff8007ff,0xff001fff,0xbc003dff,0xf807fffc,0x1fffff0,0x3c003c0,0x78001e0f, 0x1e07,0xc01f00f0,0x1e00ff,0xffe0001e,0xf0,0x780,0x0,0x0,0x7c00000,0x7c0000,0x0,0x7800000,0x0,0x18,0xc0,0x0,0x1018000,0x7800000, 0x3,0xc00f0000,0x7c00000,0x1f00001,0xf000000f,0x80000007,0xc0003e00,0x1e07c,0x3e0780,0x0,0x0,0x0,0x70,0x380700ff,0xff800000, 0x3ffff,0xfe0007c0,0xffffe,0x1e1e00,0x0,0x780000,0x1fffe000,0xf0000078,0x7c0078,0x7800003c,0xff0,0x0,0x38e0003,0x80f00780, 0x180300,0x0,0x1c3,0x81e1c000,0x7f,0xf0000078,0x1e0,0x38,0x0,0x3c003c0,0xfffe1c00,0x0,0x0,0x380000f0,0x7800c01,0x80001c00, 0xe000,0x603e00,0xf000,0xf07800,0x783c000,0x3c1e0001,0xe0f0000f,0x7800078,0x3c000f87,0x8001e000,0x78000,0x3c0000,0x1e00000, 0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x780f3c0,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f01,0xf000f81e, 0x7bc0f0,0x3c0780,0x1e03c00,0xf01e000,0x78007878,0x1e001f,0xf0f800,0x7fffe00,0x3ffff001,0xffff800f,0xfffc007f,0xffe003ff, 0xff007fff,0xff800fff,0xf001fffe,0xffff0,0x7fff80,0x3fffc00,0x3ff80001,0xffc0000f,0xfe00007f,0xf00001ff,0xfc003dff,0xf000ffff, 0x7fff8,0x3fffc0,0x1fffe00,0xffff000,0x1f80003,0xffff803c,0x3c01e0,0x1e00f00,0xf007800,0x780f0001,0xe01ffffc,0x3c00078,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000, 0x3c1e003f,0xfffff078,0x30001e0f,0x300780,0x1e0,0x1e00,0x3c00,0x3dde00,0x1e0000,0x0,0x0,0x0,0x78001e00,0x3c0001e,0x0,0xf800003e, 0xf0780,0x3dfc000,0x783f8000,0xf8007,0xc01f00f0,0x3e0007,0xe000003f,0x1f,0xfc000000,0x7ff000,0xf80,0x3e007c70,0x783c003,0xc001e03c, 0x1e0,0x3c03c0,0x1e00,0x3c000,0x1e0007,0x80007800,0x780,0x3c7c0000,0x7800001e,0x3878f078,0xf01e03c0,0x780780,0x1e0f000,0x1e078001, 0xe03e0000,0xf000,0xf0003c0,0x1e007807,0x83f03c00,0x3ef00007,0xcf800000,0x3e00003c,0xf00,0x1e0,0xf80007,0xc0000000,0x0,0x3e01f801, 0xfe07e001,0xf80f007e,0x7f801f8,0x1f801fff,0xfe00fc0f,0xf007f83f,0x1ffc00,0x7ff000,0x7807c00,0x1e0000f,0x87e1e01f,0xe0fc00fc, 0xfc007f8,0x1f803f03,0xfc003df0,0x3807e03c,0x1fffff0,0x3c003c0,0x78003e0f,0x1e03,0xe03e00f8,0x3e00ff,0xffe0001e,0xf0,0x780, 0x0,0x0,0x7800000,0xfe0000,0x0,0x7800000,0x0,0x18,0xc0,0x0,0x1818000,0x7c00000,0x3,0xc00f0000,0xfe00000,0x3e00003,0xf800001f, 0xc0000007,0xc0003e00,0x1e03c,0x3c0f80,0x0,0x0,0x0,0x70,0x380700fc,0x7800000,0x7c1fe,0x3e000fe0,0xffffe,0x1f3e00,0x0,0x780000, 0x3f98e000,0xf000003c,0xfcf8007c,0xf800003c,0x3ffc,0x0,0x31c0001,0x80f00f80,0x380700,0x0,0x183,0x80e0c000,0x3f,0xe0000078, 0x3c0,0x38,0x0,0x3c003c0,0xfffe1c00,0x0,0x0,0x38000078,0xf000e01,0xc003ffe0,0x1fff00,0x7ffc00,0xf000,0xf07800,0x783c000,0x3c1e0001, 0xe0f0000f,0x7800078,0x3c000f07,0x8003c000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00, 0x3c0f1e0,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0xf801f01e,0xf3c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78007cf8, 0x1e000f,0x80f0f000,0x7c03f00,0x3e01f801,0xf00fc00f,0x807e007c,0x3f003e0,0x1f80707f,0x8f801f80,0xf003f03f,0x1f81f8,0xfc0fc0, 0x7e07e00,0x3ff80001,0xffc0000f,0xfe00007f,0xf00003ff,0xfc003fc1,0xf801f81f,0x800fc0fc,0x7e07e0,0x3f03f00,0x1f81f800,0x1f80007, 0xe07f003c,0x3c01e0,0x1e00f00,0xf007800,0x780f8003,0xe01fe07e,0x3e000f8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3f,0xfffff078,0x30000ffe,0x1f007c0,0x0,0x1e00, 0x3c00,0xf9cf80,0x1e0000,0x0,0x0,0x0,0x78001e00,0x3c0001e,0x0,0xf00000fc,0x1e0780,0x3fff800,0x78ffe000,0xf0003,0xe03e00f0, 0x3e0007,0xe000003f,0x7f,0xe01fffff,0xf00ffc00,0x1f80,0x3c01ff70,0x783c003,0xc007e03c,0x1e0,0x3c03c0,0x1e00,0x3c000,0x1e0007, 0x80007800,0x780,0x3cfc0000,0x7800001e,0x3c78f078,0xf01e03c0,0x780780,0x3e0f000,0x1e078003,0xc01f0000,0xf000,0xf0003c0,0x1e007807, 0x83f83c00,0x1ff00003,0xcf000000,0x3e00003c,0xf00,0x1e0,0x0,0x0,0x0,0x20007801,0xfc03e003,0xe003007c,0x3f803e0,0x7c0003c, 0xf807,0xf007e00f,0x3c00,0xf000,0x780f800,0x1e0000f,0x87e1f01f,0x803c00f8,0x7c007f0,0xf803e01,0xfc003f80,0x80f8004,0x3c000, 0x3c003c0,0x3c003c0f,0x1e03,0xe03e0078,0x3c0000,0x7c0001e,0xf0,0x780,0x0,0x0,0x3ffff800,0x1ff0000,0x0,0x7800000,0x0,0x18, 0xc0,0x0,0x1818000,0x3e00000,0x3,0xc00f0000,0x1ff00000,0x3e00007,0xfc00003f,0xe0000003,0xc0003c00,0xf03c,0x3c0f00,0x0,0x0, 0x0,0x70,0x380701f0,0x800000,0x780fc,0x1e001ff0,0x7c,0xf3c00,0x0,0x780000,0x7e182000,0xf000001f,0xfff00ffc,0xffc0003c,0x3cfe, 0x0,0x31c0001,0x80f01f80,0x780f00,0x0,0x183,0x80e0c000,0xf,0x80000078,0x780,0x38,0x0,0x3c003c0,0x7ffe1c00,0x0,0x0,0x38000078, 0xf000f01,0xe003ffe0,0x1fff00,0x7ff800,0xf000,0xf07800,0x783c000,0x3c1e0001,0xe0f0000f,0x78000f8,0x3e000f07,0x8003c000,0x78000, 0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x3c0f1e0,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0, 0x78000f00,0x7c03e01e,0x1e3c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78003cf0,0x1e0007,0x80f1e000,0x4000f00,0x20007801,0x3c008, 0x1e0040,0xf00200,0x780403f,0x7803e00,0x3007c00f,0x803e007c,0x1f003e0,0xf801f00,0x780000,0x3c00000,0x1e000000,0xf00007f0, 0x3e003f00,0x7801f00f,0x800f807c,0x7c03e0,0x3e01f00,0x1f00f800,0x1f80007,0xc03e003c,0x3c01e0,0x1e00f00,0xf007800,0x78078003, 0xc01fc03e,0x1e000f0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x780000,0x0,0xf078007c,0x300007fc,0x7e00fe0,0x0,0x1e00,0x3c00,0x3e1c3e0,0x1e0000,0x0,0x0,0x0,0xf0001e00, 0x3c0001e,0x1,0xf000fff8,0x1e0780,0x3fffe00,0x79fff000,0x1f0001,0xfffc00f0,0x7e0007,0xe000003f,0x3ff,0x801fffff,0xf003ff80, 0x3f00,0x3c03fff0,0xf01e003,0xffffc03c,0x1e0,0x3c03ff,0xffc01fff,0xfe03c000,0x1fffff,0x80007800,0x780,0x3df80000,0x7800001e, 0x1c70f078,0x781e03c0,0x780780,0x3c0f000,0x1e078007,0xc01f8000,0xf000,0xf0003c0,0x1e007807,0x83f83c00,0xfe00003,0xff000000, 0x7c00003c,0x780,0x1e0,0x0,0x0,0x0,0x7c01,0xf801f007,0xc00100f8,0x1f803c0,0x3c0003c,0x1f003,0xf007c00f,0x80003c00,0xf000, 0x783f000,0x1e0000f,0x3c0f01f,0x3e01f0,0x3e007e0,0x7c07c00,0xfc003f00,0xf0000,0x3c000,0x3c003c0,0x3c003c0f,0x1e01,0xf07c007c, 0x7c0000,0xfc0001e,0xf0,0x780,0x0,0x0,0x3ffff000,0x3838000,0x0,0x7800000,0x0,0x18,0xc0,0x0,0xff0000,0x3f00000,0x3,0xc00fff00, 0x38380000,0x7c0000e,0xe000070,0x70000001,0xe0003c00,0xf01e,0x780e00,0x0,0x0,0x0,0x0,0x1e0,0x0,0x780f8,0xf003838,0xfc,0xffc00, 0x0,0x780000,0x7c180000,0xf000000f,0xffe00fff,0xffc0003c,0x783f,0x80000000,0x6380000,0xc0f83f80,0xf81f00,0x0,0x303,0x80e06000, 0x0,0x78,0xf00,0x78,0x0,0x3c003c0,0x7ffe1c00,0x0,0x0,0x3800003c,0x3e000f81,0xf003ffe0,0x1fff00,0x1fc000,0xf000,0x1e03c00, 0xf01e000,0x780f0003,0xc078001e,0x3c000f0,0x1e000f07,0xff83c000,0x7ffff,0x803ffffc,0x1ffffe0,0xfffff00,0xf00000,0x7800000, 0x3c000001,0xe0001e00,0x3c0f0f0,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x3e07c01e,0x1e3c0f0,0x3c0780,0x1e03c00, 0xf01e000,0x78003ff0,0x1e0007,0x80f1e000,0xf80,0x7c00,0x3e000,0x1f0000,0xf80000,0x7c0001e,0x3c07c00,0x10078007,0x803c003c, 0x1e001e0,0xf000f00,0x780000,0x3c00000,0x1e000000,0xf00007c0,0x1e003e00,0x7c03e007,0xc01f003e,0xf801f0,0x7c00f80,0x3e007c00, 0xf,0x801f003c,0x3c01e0,0x1e00f00,0xf007800,0x7807c007,0xc01f801f,0x1f001f0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x0,0xe078003c,0x300001f0,0x3f801ff0,0x0, 0x3c00,0x1e00,0x3c1c1e0,0x1e0000,0x0,0x0,0x0,0xf0001e0f,0x3c0001e,0x3,0xe000fff0,0x3c0780,0x3ffff00,0x7bfff800,0x1e0000,0x7ff00078, 0x7e0007,0xe000003f,0x1ffc,0x1fffff,0xf0007ff0,0x7e00,0x3c07c3f0,0xf01e003,0xffff003c,0x1e0,0x3c03ff,0xffc01fff,0xfe03c000, 0x1fffff,0x80007800,0x780,0x3ffc0000,0x7800001e,0x1ef0f078,0x781e03c0,0x780780,0x7c0f000,0x1e07801f,0x800ff000,0xf000,0xf0003c0, 0xf00f807,0x83b83c00,0xfc00001,0xfe000000,0xf800003c,0x780,0x1e0,0x0,0x0,0x0,0x3c01,0xf000f007,0xc00000f0,0xf80780,0x3c0003c, 0x1e001,0xf007c007,0x80003c00,0xf000,0x787e000,0x1e0000f,0x3c0f01f,0x1e01e0,0x1e007c0,0x3c07800,0x7c003f00,0xf0000,0x3c000, 0x3c003c0,0x3e007c07,0x80003c00,0xf8f8003c,0x780000,0xf80001e,0xf0,0x780,0x0,0x0,0x7ffff000,0x601c000,0x3,0xffff0000,0x0, 0xfff,0xf8007fff,0xc0000000,0x7e003c,0x1fe0000,0xc0003,0xc00fff00,0x601c0000,0xf800018,0x70000c0,0x38000001,0xe0007800,0x701e, 0x701e00,0x0,0x0,0x0,0x0,0x1e0,0x6,0x700f8,0xf00601c,0xf8,0x7f800,0x0,0x780000,0xf8180000,0xf000000f,0x87c00fff,0xffc0003c, 0xf01f,0xc0000000,0x6380000,0xc07ff780,0x1f03e03,0xfffffe00,0x303,0x81c06000,0x0,0x1ffff,0xfe001e00,0x180f8,0x0,0x3c003c0, 0x3ffe1c00,0x3f00000,0x0,0x3800003f,0xfe0007c0,0xf8000000,0x18000000,0xc0000006,0x1f000,0x1e03c00,0xf01e000,0x780f0003,0xc078001e, 0x3c000f0,0x1e001f07,0xff83c000,0x7ffff,0x803ffffc,0x1ffffe0,0xfffff00,0xf00000,0x7800000,0x3c000001,0xe000fff8,0x3c0f0f0, 0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x1f0f801e,0x3c3c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78001fe0,0x1e0007, 0x80f1e000,0x780,0x3c00,0x1e000,0xf0000,0x780000,0x3c0001e,0x3c07c00,0xf0007,0x8078003c,0x3c001e0,0x1e000f00,0x780000,0x3c00000, 0x1e000000,0xf0000f80,0x1f003e00,0x3c03c003,0xc01e001e,0xf000f0,0x7800780,0x3c003c00,0xf,0x3f003c,0x3c01e0,0x1e00f00,0xf007800, 0x7803c007,0x801f000f,0xf001e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1,0xe078003f,0xb0000000,0xfc003cf0,0x0,0x3c00,0x1e00,0x101c040,0x1e0000,0x0,0x0,0x1, 0xe0001e1f,0x83c0001e,0x7,0xe000fff0,0x3c0780,0x3c03f80,0x7fc0fc00,0x1e0000,0xfff80078,0xfe0007,0xe000003f,0x7fe0,0x1fffff, 0xf0000ffc,0xfc00,0x780f81f0,0xf01e003,0xffff003c,0x1e0,0x3c03ff,0xffc01fff,0xfe03c000,0x1fffff,0x80007800,0x780,0x3ffc0000, 0x7800001e,0x1ef0f078,0x3c1e03c0,0x780780,0x1fc0f000,0x1e07ffff,0x7ff00,0xf000,0xf0003c0,0xf00f007,0xc3b87c00,0x7c00001,0xfe000000, 0xf800003c,0x3c0,0x1e0,0x0,0x0,0x0,0x3c01,0xf000f007,0x800000f0,0xf80780,0x1e0003c,0x1e001,0xf0078007,0x80003c00,0xf000,0x78fc000, 0x1e0000f,0x3c0f01e,0x1e01e0,0x1e007c0,0x3c07800,0x7c003e00,0xf0000,0x3c000,0x3c003c0,0x1e007807,0x80003c00,0x7df0003c,0x780000, 0x1f00001e,0xf0,0x780,0x0,0x0,0x7800000,0xe7ce000,0x3,0xffff0000,0x0,0xfff,0xf8007fff,0xc0000000,0x1f0,0xffe000,0x1c0003, 0xc00fff00,0xe7ce0000,0xf800039,0xf38001cf,0x9c000000,0xe0007800,0x780e,0x701c00,0x0,0x0,0x0,0x0,0x1e0,0x7,0xf0078,0xf00e7ce, 0x1f0,0x7f800,0x0,0x780000,0xf0180000,0xf000000e,0x1c0001f,0xe000003c,0xf007,0xe0000000,0x6380000,0xc03fe780,0x3e07c03,0xfffffe00, 0x303,0xffc06000,0x0,0x1ffff,0xfe003ffe,0x1fff0,0x0,0x3c003c0,0x1ffe1c00,0x3f00000,0x7,0xffc0001f,0xfc0003e0,0x7c000001,0xfc00000f, 0xe000007f,0x1e000,0x1e03c00,0xf01e000,0x780f0003,0xc078001e,0x3c000f0,0x1e001e07,0xff83c000,0x7ffff,0x803ffffc,0x1ffffe0, 0xfffff00,0xf00000,0x7800000,0x3c000001,0xe000fff8,0x3c0f078,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0xf9f001e, 0x783c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78001fe0,0x1e0007,0x80f1e000,0x780,0x3c00,0x1e000,0xf0000,0x780000,0x3c0001e,0x3c07800, 0xf0003,0xc078001e,0x3c000f0,0x1e000780,0x780000,0x3c00000,0x1e000000,0xf0000f00,0xf003c00,0x3c03c003,0xc01e001e,0xf000f0, 0x7800780,0x3c003c00,0xf,0x7f003c,0x3c01e0,0x1e00f00,0xf007800,0x7803c007,0x801f000f,0xf001e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1,0xe070001f,0xf8000007, 0xf0007cf8,0x7800000,0x3c00,0x1e00,0x1c000,0x1e0000,0x0,0x0,0x1,0xe0001e1f,0x83c0001e,0xf,0xc000fff8,0x780780,0x2000f80,0x7f803e00, 0x3e0003,0xfffe007c,0x1fe0000,0x0,0x3ff00,0x0,0x1ff,0x8001f000,0x780f00f0,0x1f00f003,0xffffc03c,0x1e0,0x3c03ff,0xffc01fff, 0xfe03c00f,0xf81fffff,0x80007800,0x780,0x3ffe0000,0x7800001e,0xee0f078,0x3c1e03c0,0x7807ff,0xff80f000,0x1e07fffe,0x3ffe0, 0xf000,0xf0003c0,0xf00f003,0xc7bc7800,0xfc00000,0xfc000001,0xf000003c,0x3c0,0x1e0,0x0,0x0,0x0,0x3c01,0xe000f80f,0x800001e0, 0xf80f00,0x1e0003c,0x3c000,0xf0078007,0x80003c00,0xf000,0x79f8000,0x1e0000f,0x3c0f01e,0x1e03c0,0x1f00780,0x3e0f000,0x7c003e00, 0xf0000,0x3c000,0x3c003c0,0x1e007807,0x81e03c00,0x7df0003e,0xf80000,0x3e00003e,0xf0,0x7c0,0xfc000,0x80000000,0x7800000,0x1e7cf000, 0x3,0xffff0000,0x0,0x18,0xc0,0x0,0xf80,0x7ffc00,0x380003,0xc00fff01,0xe7cf0000,0x1f000079,0xf3c003cf,0x9e000000,0xe0007000, 0x380e,0xe01c00,0x0,0x0,0x0,0x0,0x1e0,0x3,0x800f0078,0xf01e7cf,0x3e0,0x3f000,0x0,0x780000,0xf018001f,0xfff8001e,0x1e0000f, 0xc000003c,0xf003,0xe0000000,0x6380000,0xc00fc780,0x7c0f803,0xfffffe00,0x303,0xfe006000,0x0,0x1ffff,0xfe003ffe,0x1ffe0,0x0, 0x3c003c0,0xffe1c00,0x3f00000,0x7,0xffc00007,0xf00001f0,0x3e00001f,0xfc0000ff,0xe00007ff,0x3e000,0x3e01e00,0x1f00f000,0xf8078007, 0xc03c003e,0x1e001e0,0xf001e07,0xff83c000,0x7ffff,0x803ffffc,0x1ffffe0,0xfffff00,0xf00000,0x7800000,0x3c000001,0xe000fff8, 0x3c0f078,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x7fe001e,0xf03c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78000fc0, 0x1e0007,0x80f1f000,0x780,0x3c00,0x1e000,0xf0000,0x780000,0x3c0001e,0x3c0f800,0x1e0003,0xc0f0001e,0x78000f0,0x3c000780,0x780000, 0x3c00000,0x1e000000,0xf0000f00,0xf003c00,0x3c078003,0xe03c001f,0x1e000f8,0xf0007c0,0x78003e00,0x1e,0xf7803c,0x3c01e0,0x1e00f00, 0xf007800,0x7803e00f,0x801e000f,0x80f803e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1,0xe0f0000f,0xff00001f,0x8000f87c,0x7800000,0x3c00,0x1e00,0x1c000,0x7fffff80, 0x0,0x0,0x3,0xc0001e1f,0x83c0001e,0x1f,0x800000fe,0xf00780,0x7c0,0x7f001e00,0x3c0007,0xe03f003f,0x3fe0000,0x0,0x3fc00,0x0, 0x7f,0x8001e000,0x781f00f0,0x1e00f003,0xc007e03c,0x1e0,0x3c03c0,0x1e00,0x3c00f,0xf81e0007,0x80007800,0x780,0x3f9f0000,0x7800001e, 0xfe0f078,0x3c1e03c0,0x7807ff,0xff00f000,0x1e07fff8,0xfff8,0xf000,0xf0003c0,0xf81f003,0xc7bc7800,0xfe00000,0x78000003,0xe000003c, 0x1e0,0x1e0,0x0,0x0,0x0,0x1fffc01,0xe000780f,0x1e0,0x780f00,0x1e0003c,0x3c000,0xf0078007,0x80003c00,0xf000,0x7bf0000,0x1e0000f, 0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0xf8000,0x3c000,0x3c003c0,0x1f00f807,0x81f03c00,0x3fe0001e,0xf00000,0x7c00007c, 0xf0,0x3e0,0x3ff801,0x80000000,0x7800000,0x3cfcf800,0x3,0xffff0000,0x0,0x18,0xc0,0x0,0x7c00,0x1fff00,0x700003,0xc00f0003, 0xcfcf8000,0x3e0000f3,0xf3e0079f,0x9f000000,0xf000,0x1000,0x0,0x0,0x0,0x0,0x0,0x1f0,0x1,0xc00f0078,0xf03cfcf,0x800007c0,0x1e000, 0x0,0x780001,0xe018001f,0xfff8001c,0xe00007,0x8000003c,0xf001,0xf0000000,0x6380000,0xc0000000,0xf81f003,0xfffffe00,0x303, 0x87006000,0x0,0x1ffff,0xfe003ffe,0x7f00,0x0,0x3c003c0,0x3fe1c00,0x3f00000,0x7,0xffc00000,0xf8,0x1f0001ff,0xf0000fff,0x80007ffc, 0xfc000,0x3c01e00,0x1e00f000,0xf0078007,0x803c003c,0x1e001e0,0xf001e07,0x8003c000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000, 0x7800000,0x3c000001,0xe000fff8,0x3c0f078,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x3fc001e,0x1e03c0f0,0x3c0780, 0x1e03c00,0xf01e000,0x78000780,0x1e0007,0x80f0fc00,0x3fff80,0x1fffc00,0xfffe000,0x7fff0003,0xfff8001f,0xffc0001e,0x3c0f000, 0x1e0003,0xc0f0001e,0x78000f0,0x3c000780,0x780000,0x3c00000,0x1e000000,0xf0001e00,0xf803c00,0x3c078001,0xe03c000f,0x1e00078, 0xf0003c0,0x78001e07,0xfffffe1e,0x1e7803c,0x3c01e0,0x1e00f00,0xf007800,0x7801e00f,0x1e0007,0x807803c0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x3,0xc0f00007, 0xffc0007e,0xf03e,0x7800000,0x3c00,0x1e00,0x1c000,0x7fffff80,0x0,0x0,0x3,0xc0001e1f,0x83c0001e,0x3f,0x3e,0xf00780,0x3c0,0x7e001e00, 0x7c000f,0x800f001f,0xffde0000,0x0,0x3e000,0x0,0xf,0x8003e000,0x781e0070,0x1e00f003,0xc001f03c,0x1e0,0x3c03c0,0x1e00,0x3c00f, 0xf81e0007,0x80007800,0x780,0x3f1f0000,0x7800001e,0x7c0f078,0x1e1e03c0,0x7807ff,0xfc00f000,0x1e07fffe,0xffc,0xf000,0xf0003c0, 0x781e003,0xc71c7800,0x1ff00000,0x78000003,0xe000003c,0x1e0,0x1e0,0x0,0x0,0x0,0xffffc01,0xe000780f,0x1e0,0x780fff,0xffe0003c, 0x3c000,0xf0078007,0x80003c00,0xf000,0x7ff0000,0x1e0000f,0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0x7f000,0x3c000, 0x3c003c0,0xf00f007,0xc1f07c00,0x1fc0001f,0x1f00000,0xfc000ff8,0xf0,0x1ff,0xfffe07,0x80000000,0x7800000,0x7ffcfc00,0x0,0xf000000, 0x0,0x18,0xc0,0x0,0x3e000,0x1ff80,0xe00003,0xc00f0007,0xffcfc000,0x3e0001ff,0xf3f00fff,0x9f800000,0x6000,0x0,0x0,0x7c000, 0x0,0x0,0x0,0xfe,0x0,0xe00f007f,0xff07ffcf,0xc0000fc0,0x1e000,0x0,0x780001,0xe018001f,0xfff8001c,0xe00007,0x80000000,0xf800, 0xf0000000,0x6380000,0xc0000000,0x1f03c000,0x1e00,0x303,0x83806000,0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xfe1c00,0x3f00000,0x0, 0x0,0x3c,0xf801fff,0xfff8,0x7ffc0,0x1f8000,0x3c01e00,0x1e00f000,0xf0078007,0x803c003c,0x1e001e0,0xf003c07,0x8003c000,0x78000, 0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x3c0f03c,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0, 0x78000f00,0x1f8001e,0x1e03c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1e000f,0x80f0ff00,0x1ffff80,0xffffc00,0x7fffe003, 0xffff001f,0xfff800ff,0xffc007ff,0xffc0f000,0x1fffff,0xc0fffffe,0x7fffff0,0x3fffff80,0x780000,0x3c00000,0x1e000000,0xf0001e00, 0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e07,0xfffffe1e,0x3c7803c,0x3c01e0,0x1e00f00,0xf007800,0x7801f01f, 0x1e0007,0x807c07c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x780000,0x3,0xc0f00000,0xfff003f0,0x1f00f03e,0x7800000,0x3c00,0x1e00,0x1c000,0x7fffff80,0x0,0x7ff80000,0x3, 0xc0001e0f,0x3c0001e,0x7e,0x1f,0x1e00780,0x3e0,0x7e000f00,0x78000f,0x7800f,0xff9e0000,0x0,0x3fc00,0x0,0x7f,0x8003c000,0x781e0070, 0x3e00f803,0xc000f03c,0x1e0,0x3c03c0,0x1e00,0x3c00f,0xf81e0007,0x80007800,0x780,0x3e0f8000,0x7800001e,0x7c0f078,0x1e1e03c0, 0x7807ff,0xf000f000,0x1e07807f,0xfe,0xf000,0xf0003c0,0x781e003,0xc71c7800,0x3ef00000,0x78000007,0xc000003c,0x1e0,0x1e0,0x0, 0x0,0x0,0x1ffffc01,0xe000780f,0x1e0,0x780fff,0xffe0003c,0x3c000,0xf0078007,0x80003c00,0xf000,0x7ff0000,0x1e0000f,0x3c0f01e, 0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0x7ff80,0x3c000,0x3c003c0,0xf00f003,0xc1f07800,0x1fc0000f,0x1e00000,0xf8000ff0,0xf0, 0xff,0xffffff,0x80000000,0x3fffc000,0xfff9fe00,0x0,0xf000000,0x0,0x18,0xc0,0x0,0x1f0000,0x1fc0,0x1c00003,0xc00f000f,0xff9fe000, 0x7c0003ff,0xe7f81fff,0x3fc00000,0x0,0x0,0x0,0xfe000,0x1ffffc0f,0xfffffc00,0x0,0xff,0xf0000000,0x700f007f,0xff0fff9f,0xe0000f80, 0x1e000,0x0,0x780001,0xe018001f,0xfff8001c,0xe00fff,0xffc00000,0xf800,0xf0000000,0x6380000,0xc0ffff80,0x3e078000,0x1e00,0x7ff80303, 0x83c06000,0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x3f00000,0x0,0x7f,0xff00001e,0x7c1fff0,0xfff80,0x7ffc00,0x3f0000,0x7c01f00, 0x3e00f801,0xf007c00f,0x803e007c,0x1f003e0,0xf803c07,0x8003c000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001, 0xe0001e00,0x3c0f03c,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x1f8001e,0x3c03c0f0,0x3c0780,0x1e03c00,0xf01e000, 0x78000780,0x1e001f,0xf07f80,0x3ffff80,0x1ffffc00,0xffffe007,0xffff003f,0xfff801ff,0xffc03fff,0xffc0f000,0x1fffff,0xc0fffffe, 0x7fffff0,0x3fffff80,0x780000,0x3c00000,0x1e000000,0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e07, 0xfffffe1e,0x787803c,0x3c01e0,0x1e00f00,0xf007800,0x7800f01e,0x1e0007,0x803c0780,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1ff,0xffff8000,0x3ff80fc0,0x7fc1e01f, 0x7800000,0x3c00,0x1e00,0x0,0x7fffff80,0x0,0x7ff80000,0x7,0x80001e00,0x3c0001e,0xfc,0xf,0x1e00780,0x1e0,0x7c000f00,0x78000f, 0x78007,0xff1e0000,0x0,0x3ff00,0x0,0x1ff,0x8003c000,0x781e0070,0x3c007803,0xc000f03c,0x1e0,0x3c03c0,0x1e00,0x3c000,0x781e0007, 0x80007800,0x780,0x3c07c000,0x7800001e,0x7c0f078,0xf1e03c0,0x780780,0xf000,0x1e07801f,0x3e,0xf000,0xf0003c0,0x781e003,0xcf1c7800, 0x3cf80000,0x7800000f,0x8000003c,0xf0,0x1e0,0x0,0x0,0x0,0x3ffffc01,0xe000780f,0x1e0,0x780fff,0xffe0003c,0x3c000,0xf0078007, 0x80003c00,0xf000,0x7ff8000,0x1e0000f,0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0x3fff0,0x3c000,0x3c003c0,0xf81f003, 0xc3b87800,0xf80000f,0x1e00001,0xf0000ff0,0xf0,0xff,0xf03fff,0x80000000,0x3fff8001,0xfff1ff00,0x0,0xf000000,0x0,0x18,0xc0, 0x0,0x380000,0x7c0,0x3c00003,0xc00f001f,0xff1ff000,0xf80007ff,0xc7fc3ffe,0x3fe00000,0x0,0x0,0x0,0x1ff000,0x7ffffe1f,0xffffff00, 0x0,0x7f,0xfe000000,0x780f007f,0xff1fff1f,0xf0001f00,0x1e000,0x0,0x780001,0xe0180000,0xf000001c,0xe00fff,0xffc00000,0x7c00, 0xf0000000,0x31c0001,0x80ffff80,0x3e078000,0x1e00,0x7ff80183,0x81c0c000,0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x3f00000, 0x0,0x7f,0xff00001e,0x7c7ff03,0xc03ff8fe,0x1ffc0f0,0x7e0000,0x7800f00,0x3c007801,0xe003c00f,0x1e0078,0xf003c0,0x7803c07,0x8003c000, 0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x3c0f01e,0x3c078000,0xf03c0007,0x81e0003c, 0xf0001e0,0x78000f00,0x3fc001e,0x7803c0f0,0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1e007f,0xf03fe0,0x7ffff80,0x3ffffc01, 0xffffe00f,0xffff007f,0xfff803ff,0xffc07fff,0xffc0f000,0x1fffff,0xc0fffffe,0x7fffff0,0x3fffff80,0x780000,0x3c00000,0x1e000000, 0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e07,0xfffffe1e,0x707803c,0x3c01e0,0x1e00f00,0xf007800, 0x7800f01e,0x1e0007,0x803c0780,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1ff,0xffff8000,0x30f81f00,0xffe1e00f,0x87800000,0x3c00,0x1e00,0x0,0x1e0000,0x0,0x7ff80000, 0x7,0x80001e00,0x3c0001e,0x1f8,0x7,0x83c00780,0x1e0,0x7c000f00,0xf8001e,0x3c001,0xfc1e0000,0x0,0x7fe0,0x0,0xffc,0x3c000,0x781e0070, 0x3ffff803,0xc000783c,0x1e0,0x3c03c0,0x1e00,0x3c000,0x781e0007,0x80007800,0x780,0x3c07c000,0x7800001e,0x380f078,0xf1e03c0, 0x780780,0xf000,0x1e07800f,0x8000001e,0xf000,0xf0003c0,0x3c3c003,0xcf1e7800,0x7c780000,0x7800000f,0x8000003c,0xf0,0x1e0,0x0, 0x0,0x0,0x7f003c01,0xe000780f,0x1e0,0x780fff,0xffe0003c,0x3c000,0xf0078007,0x80003c00,0xf000,0x7f7c000,0x1e0000f,0x3c0f01e, 0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0xfff8,0x3c000,0x3c003c0,0x781e003,0xc3b87800,0x1fc00007,0x83e00003,0xe0000ff8,0xf0, 0x1ff,0xc007fe,0x0,0x7fff8001,0xffe3ff00,0x0,0x1e000000,0x0,0x18,0xc0,0x0,0x0,0x3c0,0x7800003,0xc00f001f,0xfe3ff000,0xf80007ff, 0x8ffc3ffc,0x7fe00000,0x0,0x0,0x0,0x1ff000,0x0,0x0,0x0,0x1f,0xff000000,0x3c0f007f,0xff1ffe3f,0xf0003e00,0x1e000,0x0,0x780001, 0xe0180000,0xf000001e,0x1e00fff,0xffc00000,0x3f00,0xf0000000,0x31c0001,0x80ffff80,0x1f03c000,0x1e00,0x7ff80183,0x81c0c000, 0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x0,0x0,0x7f,0xff00003c,0xf87f007,0xc03f83ff,0x81fc01f0,0x7c0000,0x7ffff00,0x3ffff801, 0xffffc00f,0xfffe007f,0xfff003ff,0xff807fff,0x8003c000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001, 0xe0001e00,0x3c0f01e,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0x7fe001e,0xf003c0f0,0x3c0780,0x1e03c00,0xf01e000, 0x78000780,0x1ffffe,0xf00ff0,0xfe00780,0x7f003c03,0xf801e01f,0xc00f00fe,0x7807f0,0x3c0ffff,0xffc0f000,0x1fffff,0xc0fffffe, 0x7fffff0,0x3fffff80,0x780000,0x3c00000,0x1e000000,0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e00, 0x1e,0xf07803c,0x3c01e0,0x1e00f00,0xf007800,0x7800783e,0x1e0007,0x801e0f80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1ff,0xffff8000,0x307c0801,0xe1f1e00f,0x87000000, 0x3c00,0x1e00,0x0,0x1e0000,0x0,0x7ff80000,0xf,0x1e00,0x3c0001e,0x3f0,0x7,0x83fffffc,0x1e0,0x7c000f00,0xf0001e,0x3c000,0x3e0000, 0x0,0x1ffc,0x1fffff,0xf0007ff0,0x3c000,0x781e0070,0x7ffffc03,0xc000781e,0x1e0,0x7803c0,0x1e00,0x3c000,0x781e0007,0x80007800, 0x780,0x3c03e000,0x7800001e,0xf078,0x79e03c0,0x780780,0xf000,0x1e078007,0x8000000f,0xf000,0xf0003c0,0x3c3c001,0xee0ef000, 0xf87c0000,0x7800001f,0x3c,0x78,0x1e0,0x0,0x0,0x0,0x7c003c01,0xe000780f,0x1e0,0x780f00,0x3c,0x3c000,0xf0078007,0x80003c00, 0xf000,0x7e3e000,0x1e0000f,0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0x1ffc,0x3c000,0x3c003c0,0x781e003,0xe3b8f800, 0x1fc00007,0x83c00007,0xc00000fc,0xf0,0x3e0,0x8001f8,0x0,0x7800000,0xffc7fe00,0x0,0x1e000000,0x0,0x18,0xc0,0x0,0x0,0x1e0, 0xf000003,0xc00f000f,0xfc7fe001,0xf00003ff,0x1ff81ff8,0xffc00000,0x0,0x0,0x0,0x1ff000,0x0,0x0,0x0,0x3,0xff800000,0x1e0f0078, 0xffc7f,0xe0007c00,0x1e000,0x0,0x780001,0xe0180000,0xf000000e,0x1c00007,0x80000000,0x1f81,0xe0000000,0x38e0003,0x80000000, 0xf81f000,0x1e00,0x7ff801c3,0x80e1c000,0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x0,0x0,0x0,0xf8,0x1f070007,0xc03803ff,0xc1c001f0, 0xf80000,0xfffff00,0x7ffff803,0xffffc01f,0xfffe00ff,0xfff007ff,0xffc07fff,0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000, 0xf00000,0x7800000,0x3c000001,0xe0001e00,0x780f00f,0x3c078000,0xf03c0007,0x81e0003c,0xf0001e0,0x78000f00,0xf9f001e,0xf003c0f0, 0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1ffffc,0xf003f8,0xf800780,0x7c003c03,0xe001e01f,0xf00f8,0x7807c0,0x3c0fc1e,0xf000, 0x1e0000,0xf00000,0x7800000,0x3c000000,0x780000,0x3c00000,0x1e000000,0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078, 0xf0003c0,0x78001e00,0x1e,0x1e07803c,0x3c01e0,0x1e00f00,0xf007800,0x7800783c,0x1e0007,0x801e0f00,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ff,0xffff8000,0x303c0001, 0xc071e007,0xcf000000,0x3c00,0x1e00,0x0,0x1e0000,0x0,0x0,0xf,0xf00,0x780001e,0x7e0,0x7,0x83fffffc,0x1e0,0x7c000f00,0x1f0001e, 0x3c000,0x3c0000,0x0,0x3ff,0x801fffff,0xf003ff80,0x3c000,0x781e0070,0x7ffffc03,0xc000781e,0x1e0,0x7803c0,0x1e00,0x1e000,0x781e0007, 0x80007800,0x780,0x3c01f000,0x7800001e,0xf078,0x79e03c0,0xf00780,0xf000,0x3e078007,0xc000000f,0xf000,0xf0003c0,0x3c3c001, 0xee0ef000,0xf03e0000,0x7800003e,0x3c,0x78,0x1e0,0x0,0x0,0x0,0xf8003c01,0xe000780f,0x1e0,0x780f00,0x3c,0x3c000,0xf0078007, 0x80003c00,0xf000,0x7c3e000,0x1e0000f,0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0xfc,0x3c000,0x3c003c0,0x3c3e001,0xe7b8f000, 0x3fe00007,0xc7c0000f,0xc000003e,0xf0,0x7c0,0x0,0x0,0x7c00000,0x7fcffc00,0x0,0x1e000000,0x0,0x18,0xc0,0x0,0x0,0x1e0,0x1e000003, 0xc00f0007,0xfcffc003,0xe00001ff,0x3ff00ff9,0xff800000,0x0,0x0,0x0,0x1ff000,0x0,0x0,0x0,0x0,0x1f800000,0xf0f0078,0x7fcff, 0xc000fc00,0x1e000,0x0,0x780001,0xe0180000,0xf000000f,0x87c00007,0x80000000,0xfe3,0xe0000000,0x18780c3,0x0,0x7c0f800,0x1e00, 0xc3,0x80e18000,0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x0,0x0,0x0,0x1f0,0x3e00000f,0xc0000303,0xe00003f0,0xf00000,0xfffff80, 0x7ffffc03,0xffffe01f,0xffff00ff,0xfff807ff,0xffc07fff,0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000, 0x3c000001,0xe0001e00,0x780f00f,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e00,0x1f0f801f,0xe00780f0,0x3c0780,0x1e03c00, 0xf01e000,0x78000780,0x1ffff8,0xf000f8,0x1f000780,0xf8003c07,0xc001e03e,0xf01f0,0x780f80,0x3c1f01e,0xf000,0x1e0000,0xf00000, 0x7800000,0x3c000000,0x780000,0x3c00000,0x1e000000,0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e00, 0x1e,0x3c07803c,0x3c01e0,0x1e00f00,0xf007800,0x78007c7c,0x1e0007,0x801f1f00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x81c00000,0x303c0003,0x8039e003,0xef000000, 0x3c00,0x1e00,0x0,0x1e0000,0x0,0x0,0x1e,0xf00,0x780001e,0xfc0,0x7,0x83fffffc,0x1e0,0x3c000f00,0x1e0001e,0x3c000,0x3c0000, 0x0,0x7f,0xe01fffff,0xf00ffc00,0x3c000,0x781f00f0,0x7ffffc03,0xc000781e,0x1e0,0x7803c0,0x1e00,0x1e000,0x781e0007,0x80007800, 0x780,0x3c01f000,0x7800001e,0xf078,0x7de01e0,0xf00780,0x7800,0x3c078003,0xc000000f,0xf000,0xf0003c0,0x3e7c001,0xee0ef001, 0xf01e0000,0x7800003e,0x3c,0x3c,0x1e0,0x0,0x0,0x0,0xf0003c01,0xe000780f,0x1e0,0x780f00,0x3c,0x3c000,0xf0078007,0x80003c00, 0xf000,0x781f000,0x1e0000f,0x3c0f01e,0x1e03c0,0xf00780,0x1e0f000,0x3c003c00,0x3e,0x3c000,0x3c003c0,0x3c3c001,0xe71cf000,0x7df00003, 0xc780000f,0x8000003e,0xf0,0x780,0x0,0x0,0x3c00000,0x3fcff800,0x0,0x1e000000,0x0,0x18,0xc0,0x0,0x1f00fc,0x1e0,0x1e000001, 0xe00f0003,0xfcff8003,0xe00000ff,0x3fe007f9,0xff000000,0x0,0x0,0x0,0x1ff000,0x0,0x0,0x0,0x0,0x7c00000,0xf0f0078,0x3fcff,0x8000f800, 0x1e000,0x0,0x780001,0xe0180000,0xf000001f,0xffe00007,0x8000003c,0x7ff,0xc0000000,0x1c3ffc7,0x0,0x3e07c00,0x1e00,0xe3,0x80738000, 0x0,0x78,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x0,0x0,0x0,0x3e0,0x7c00001d,0xc0000001,0xe0000770,0x1f00000,0xfffff80,0x7ffffc03, 0xffffe01f,0xffff00ff,0xfff807ff,0xffc07fff,0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001, 0xe0001e00,0x780f00f,0x3c03c001,0xe01e000f,0xf00078,0x78003c0,0x3c001e00,0x3e07c01f,0xc00780f0,0x3c0780,0x1e03c00,0xf01e000, 0x78000780,0x1fffc0,0xf0007c,0x1e000780,0xf0003c07,0x8001e03c,0xf01e0,0x780f00,0x3c1e01e,0xf000,0x1e0000,0xf00000,0x7800000, 0x3c000000,0x780000,0x3c00000,0x1e000000,0xf0001e00,0x7803c00,0x3c078001,0xe03c000f,0x1e00078,0xf0003c0,0x78001e00,0x1e,0x7807803c, 0x3c01e0,0x1e00f00,0xf007800,0x78003c78,0x1e0007,0x800f1e00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x83c00000,0x303c0003,0x8039e001,0xee000000,0x1e00,0x3c00, 0x0,0x1e0000,0x0,0x0,0x1e,0xf00,0x780001e,0x1f80,0x7,0x83fffffc,0x1e0,0x3c000f00,0x1e0001e,0x3c000,0x3c0000,0x0,0x1f,0xfc1fffff, 0xf07ff000,0x0,0x780f00f0,0x78003c03,0xc000781e,0x1e0,0xf803c0,0x1e00,0x1e000,0x781e0007,0x80007800,0x780,0x3c00f800,0x7800001e, 0xf078,0x3de01e0,0xf00780,0x7800,0x3c078003,0xe000000f,0xf000,0xf0003c0,0x1e78001,0xfe0ff003,0xe01f0000,0x7800007c,0x3c,0x3c, 0x1e0,0x0,0x0,0x0,0xf0007c01,0xe000f80f,0x800001e0,0xf80f00,0x3c,0x1e001,0xf0078007,0x80003c00,0xf000,0x780f800,0x1e0000f, 0x3c0f01e,0x1e03c0,0x1f00780,0x3e0f000,0x7c003c00,0x1e,0x3c000,0x3c003c0,0x3c3c001,0xe71cf000,0xf8f80003,0xe780001f,0x1e, 0xf0,0x780,0x0,0x0,0x3c00000,0x1ffff000,0x0,0x1e000000,0x0,0x18,0xc0,0x0,0x3bc1de,0x1e0,0xf000001,0xe00f0001,0xffff0007,0xc000007f, 0xffc003ff,0xfe000000,0x0,0x0,0x0,0xfe000,0x0,0x0,0x0,0x0,0x3c00000,0x1e0f0078,0x1ffff,0x1f000,0x1e000,0x0,0x780000,0xf0180000, 0xf000001f,0xfff00007,0x8000003c,0x1ff,0x80000000,0xe0ff0e,0x0,0x1f03e00,0x1e00,0x70,0x70000,0x0,0x78,0x0,0x0,0x0,0x3c003c0, 0xe1c00,0x0,0x0,0x0,0x7c0,0xf8000019,0xc0000000,0xe0000670,0x1e00000,0xf000780,0x78003c03,0xc001e01e,0xf00f0,0x780780,0x3c0f807, 0x8001e000,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0xf80f007,0xbc03c001,0xe01e000f, 0xf00078,0x78003c0,0x3c001e00,0x7c03e00f,0x800780f0,0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1e0000,0xf0003c,0x1e000f80, 0xf0007c07,0x8003e03c,0x1f01e0,0xf80f00,0x7c1e01e,0xf800,0x1e0000,0xf00000,0x7800000,0x3c000000,0x780000,0x3c00000,0x1e000000, 0xf0001e00,0x7803c00,0x3c078003,0xe03c001f,0x1e000f8,0xf0007c0,0x78003e00,0x1f8001f,0xf00f803c,0x3c01e0,0x1e00f00,0xf007800, 0x78003e78,0x1e000f,0x800f9e00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf,0x3c00000,0x303c0003,0x8039f001,0xfe000000,0x1e00,0x3c00,0x0,0x1e0000,0x0,0x0,0x3c,0xf00, 0x780001e,0x3f00,0x7,0x80000780,0x3e0,0x3e000f00,0x3c0001e,0x3c000,0x7c0000,0x0,0x3,0xfe000000,0xff8000,0x0,0x3c0f81f0,0xf0001e03, 0xc000780f,0x1e0,0xf003c0,0x1e00,0xf000,0x781e0007,0x80007800,0x780,0x3c007c00,0x7800001e,0xf078,0x3de01e0,0xf00780,0x7800, 0x3c078001,0xe000000f,0xf000,0xf0003c0,0x1e78001,0xfc07f003,0xe00f0000,0x78000078,0x3c,0x1e,0x1e0,0x0,0x0,0x0,0xf0007c01, 0xf000f007,0x800000f0,0xf80780,0x3c,0x1e001,0xf0078007,0x80003c00,0xf000,0x7807c00,0x1e0000f,0x3c0f01e,0x1e01e0,0x1e007c0, 0x3c07800,0x7c003c00,0x1e,0x3c000,0x3c007c0,0x1e78001,0xe71df000,0xf8f80001,0xef80003e,0x1e,0xf0,0x780,0x0,0x0,0x3c00000, 0xfffe000,0x0,0x3e000000,0x0,0x18,0x7fff,0xc0000000,0x60c306,0x1e0,0x7800001,0xe00f0000,0xfffe0007,0x8000003f,0xff8001ff, 0xfc000000,0x0,0x0,0x0,0x7c000,0x0,0x0,0x0,0x0,0x3c00000,0x3c0f0078,0xfffe,0x3e000,0x1e000,0x0,0x780000,0xf0180000,0xf000003c, 0xfcf80007,0x8000003c,0x7f,0x0,0x70001c,0x0,0xf81f00,0x0,0x38,0xe0000,0x0,0x0,0x0,0x0,0x0,0x3c003c0,0xe1c00,0x0,0x0,0x0,0xf81, 0xf0000039,0xc0000000,0xe0000e70,0x1e00000,0x1e0003c0,0xf0001e07,0x8000f03c,0x781e0,0x3c0f00,0x1e0f007,0x8000f000,0x78000, 0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0xf00f007,0xbc03c001,0xe01e000f,0xf00078,0x78003c0, 0x3c001e00,0xf801f00f,0x800780f0,0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1e0000,0xf0003c,0x1e000f80,0xf0007c07,0x8003e03c, 0x1f01e0,0xf80f00,0x7c1e01e,0x7800,0xf0000,0x780000,0x3c00000,0x1e000000,0x780000,0x3c00000,0x1e000000,0xf0000f00,0xf003c00, 0x3c03c003,0xc01e001e,0xf000f0,0x7800780,0x3c003c00,0x1f8000f,0xe00f003c,0x7c01e0,0x3e00f00,0x1f007800,0xf8001ef8,0x1f000f, 0x7be00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0xf,0x3c00000,0x307c0003,0x8038f000,0xfc000000,0x1e00,0x3c00,0x0,0x1e0000,0xfc0000,0x0,0x7e00003c,0x780,0xf00001e, 0x7e00,0xf,0x80000780,0x3c0,0x3e001e00,0x3c0001f,0x7c000,0x780007,0xe000003f,0x0,0xfe000000,0xfe0000,0x0,0x3c07c3f0,0xf0001e03, 0xc000f80f,0x800001e0,0x1f003c0,0x1e00,0xf000,0x781e0007,0x80007800,0x4000f80,0x3c003c00,0x7800001e,0xf078,0x1fe01f0,0x1f00780, 0x7c00,0x7c078001,0xf000001f,0xf000,0xf0003c0,0x1e78001,0xfc07f007,0xc00f8000,0x780000f8,0x3c,0x1e,0x1e0,0x0,0x0,0x0,0xf0007c01, 0xf000f007,0xc00000f0,0xf80780,0x3c,0x1f003,0xf0078007,0x80003c00,0xf000,0x7807c00,0x1e0000f,0x3c0f01e,0x1e01e0,0x1e007c0, 0x3c07800,0x7c003c00,0x1e,0x3c000,0x3c007c0,0x1e78000,0xfe0fe001,0xf07c0001,0xef00007c,0x1e,0xf0,0x780,0x0,0x0,0x1e00000, 0x7cfc000,0xfc00000,0x3c00000f,0xc3f00000,0x18,0x7fff,0xc0000000,0x406303,0x3e0,0x3c00001,0xf00f0000,0x7cfc000f,0x8000001f, 0x3f0000f9,0xf8000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x780700f8,0x7cfc,0x7c000,0x1e000,0x0,0x780000,0xf8180000, 0xf0000070,0x3c0007,0x8000003c,0x3f,0x80000000,0x3c0078,0x0,0x780f00,0x0,0x1e,0x3c0000,0x0,0x0,0x0,0x0,0x0,0x3e007c0,0xe1c00, 0x0,0x0,0x0,0xf01,0xe0000071,0xc0000000,0xe0001c70,0x1e00000,0x1e0003c0,0xf0001e07,0x8000f03c,0x781e0,0x3c0f00,0x1e0f007, 0x8000f800,0x78000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x1f00f003,0xfc03e003,0xe01f001f, 0xf800f8,0x7c007c0,0x3e003e01,0xf000f80f,0xf00f0,0x3c0780,0x1e03c00,0xf01e000,0x78000780,0x1e0000,0xf0003c,0x1e000f80,0xf0007c07, 0x8003e03c,0x1f01e0,0xf80f00,0x7c1e01e,0x7c00,0xf0000,0x780000,0x3c00000,0x1e000000,0x780000,0x3c00000,0x1e000000,0xf0000f00, 0xf003c00,0x3c03c003,0xc01e001e,0xf000f0,0x7800780,0x3c003c00,0x1f8000f,0xc00f003c,0x7c01e0,0x3e00f00,0x1f007800,0xf8001ef0, 0x1f000f,0x7bc00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x780000,0xf,0x3800040,0x30780003,0x8038f800,0x78000000,0x1e00,0x3c00,0x0,0x1e0000,0xfc0000,0x0,0x7e000078, 0x780,0x1f00001e,0xfc00,0x20001f,0x780,0x80007c0,0x1f001e00,0x7c0000f,0x78000,0xf80007,0xe000003f,0x0,0x1e000000,0xf00000, 0x3c000,0x3c03fff0,0xf0001e03,0xc001f007,0x800101e0,0x7e003c0,0x1e00,0x7800,0x781e0007,0x80007800,0x6000f00,0x3c003e00,0x7800001e, 0xf078,0x1fe00f0,0x1e00780,0x3c00,0x78078000,0xf020001e,0xf000,0x7800780,0xff0001,0xfc07f00f,0x8007c000,0x780001f0,0x3c,0xf, 0x1e0,0x0,0x0,0x0,0xf800fc01,0xf801f007,0xc00100f8,0x1f807c0,0x40003c,0xf807,0xf0078007,0x80003c00,0xf000,0x7803e00,0x1f0000f, 0x3c0f01e,0x1e01f0,0x3e007e0,0x7c07c00,0xfc003c00,0x1e,0x3e000,0x3e007c0,0x1ff8000,0xfe0fe003,0xe03e0001,0xff0000fc,0x1e, 0xf0,0x780,0x0,0x0,0x1f00080,0x3cf8000,0xfc00000,0x3c00001f,0x83f00000,0x18,0xc0,0x0,0xc06203,0x40003c0,0x1c00000,0xf80f0000, 0x3cf8001f,0xf,0x3e000079,0xf0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x700780fc,0x3cf8,0xfc000,0x1e000,0x0,0x780000, 0x7c180000,0xf0000020,0x100007,0x8000003c,0xf,0x80000000,0x1f01f0,0x0,0x380700,0x0,0xf,0x80f80000,0x0,0x0,0x0,0x0,0x0,0x3e007c0, 0xe1c00,0x0,0x0,0x0,0xe01,0xc0000071,0xc0000001,0xc0001c70,0x1e00040,0x1e0003c0,0xf0001e07,0x8000f03c,0x781e0,0x3c0f00,0x1e0f007, 0x80007800,0x10078000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e00,0x7e00f003,0xfc01e003,0xc00f001e, 0x7800f0,0x3c00780,0x1e003c00,0xe000700f,0x800f0078,0x7803c0,0x3c01e00,0x1e00f000,0xf0000780,0x1e0000,0xf0003c,0x1f001f80, 0xf800fc07,0xc007e03e,0x3f01f0,0x1f80f80,0xfc1e01f,0x7c00,0x100f8000,0x807c0004,0x3e00020,0x1f000100,0x780000,0x3c00000,0x1e000000, 0xf0000f80,0x1f003c00,0x3c03e007,0xc01f003e,0xf801f0,0x7c00f80,0x3e007c00,0x1f8000f,0x801f003e,0x7c01f0,0x3e00f80,0x1f007c00, 0xf8001ff0,0x1f801f,0x7fc00,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0xf,0x7800078,0x31f80001,0xc070fc00,0xfc000000,0x1e00,0x7c00,0x0,0x1e0000,0xfc0000,0x0,0x7e000078, 0x7c0,0x1f00001e,0x1f000,0x38003f,0x780,0xe000f80,0x1f803e00,0x780000f,0x800f8000,0x1f00007,0xe000003f,0x0,0x2000000,0x800000, 0x3c000,0x3e01ff71,0xf0001f03,0xc007f007,0xc00301e0,0x1fc003c0,0x1e00,0x7c00,0x781e0007,0x80007800,0x7801f00,0x3c001f00,0x7800001e, 0xf078,0xfe00f8,0x3e00780,0x3e00,0xf8078000,0xf838003e,0xf000,0x7c00f80,0xff0000,0xfc07e00f,0x8003c000,0x780001e0,0x3c,0xf, 0x1e0,0x0,0x0,0x0,0xf801fc01,0xfc03e003,0xe003007c,0x3f803e0,0x1c0003c,0xfc0f,0xf0078007,0x80003c00,0xf000,0x7801f00,0xf8000f, 0x3c0f01e,0x1e00f8,0x7c007f0,0xf803e01,0xfc003c00,0x8003e,0x1f000,0x1e00fc0,0xff0000,0xfe0fe007,0xc01f0000,0xfe0000f8,0x1e, 0xf0,0x780,0x0,0x0,0xf80180,0x1cf0000,0x1f800000,0x3c00001f,0x83e00000,0x18,0xc0,0x0,0xc06203,0x70007c0,0xe00000,0x7e0f0000, 0x1cf0001e,0x7,0x3c000039,0xe0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x100,0x7c00000,0xe00780fc,0x2001cf0,0xf8000,0x1e000,0x0, 0x780000,0x7e182000,0xf0000000,0x7,0x8000003c,0x7,0xc0000000,0x7ffc0,0x0,0x180300,0x0,0x3,0xffe00000,0x0,0x0,0x0,0x0,0x0, 0x3f00fc0,0xe1c00,0x0,0x0,0x0,0xc01,0x800000e1,0xc0000003,0xc0003870,0x1f001c0,0x3e0003e1,0xf0001f0f,0x8000f87c,0x7c3e0,0x3e1f00, 0x1f1e007,0x80007c00,0x30078000,0x3c0000,0x1e00000,0xf000000,0xf00000,0x7800000,0x3c000001,0xe0001e03,0xfc00f001,0xfc01f007, 0xc00f803e,0x7c01f0,0x3e00f80,0x1f007c00,0x4000201f,0xc01f007c,0xf803e0,0x7c01f00,0x3e00f801,0xf0000780,0x1e0000,0xf0007c, 0x1f003f80,0xf801fc07,0xc00fe03e,0x7f01f0,0x3f80f80,0x1fc1f03f,0x803e00,0x3007c003,0x803e001c,0x1f000e0,0xf800700,0x780000, 0x3c00000,0x1e000000,0xf00007c0,0x3e003c00,0x3c01f00f,0x800f807c,0x7c03e0,0x3e01f00,0x1f00f800,0x1f80007,0xc03e001e,0xfc00f0, 0x7e00780,0x3f003c01,0xf8000fe0,0x1fc03e,0x3f800,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1e,0x780007f,0xfff00001,0xe0f07f03,0xfe000000,0xf00,0x7800,0x0, 0x1e0000,0xfc0000,0x0,0x7e0000f0,0x3f0,0x7e000fff,0xfc03ffff,0xf83f00fe,0x780,0xfc03f80,0xfc0fc00,0xf800007,0xe03f0018,0x7e00007, 0xe000003f,0x0,0x0,0x0,0x3c000,0x1e007c71,0xe0000f03,0xffffe003,0xf01f01ff,0xff8003ff,0xffe01e00,0x3f01,0xf81e0007,0x803ffff0, 0x7e03f00,0x3c000f00,0x7ffffe1e,0xf078,0xfe007e,0xfc00780,0x1f83,0xf0078000,0x783f00fe,0xf000,0x3f03f00,0xff0000,0xfc07e01f, 0x3e000,0x780003ff,0xfffc003c,0x7,0x800001e0,0x0,0x0,0x0,0x7e07fc01,0xfe07e001,0xf80f007e,0x7f801f8,0xfc0003c,0x7ffe,0xf0078007, 0x807ffffe,0xf000,0x7801f00,0xfff00f,0x3c0f01e,0x1e00fc,0xfc007f8,0x1f803f03,0xfc003c00,0xf80fc,0x1fff0,0x1f83fc0,0xff0000, 0xfc07e007,0xc01f0000,0xfe0001ff,0xffe0001e,0xf0,0x780,0x0,0x0,0xfe0780,0xfe0000,0x1f000000,0x3c00001f,0x7c00e03,0x81c00018, 0xc0,0x0,0x406203,0x7e01fc0,0x700000,0x7fffff80,0xfe0003f,0xffffc003,0xf800001f,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1f0, 0x1f800001,0xc007c1fe,0x6000fe0,0x1ffffe,0x1e000,0x0,0x780000,0x3f98e03f,0xffff8000,0x7,0x8000003c,0x7,0xc0000000,0xfe00, 0x0,0x80100,0x0,0x0,0x7f000000,0x0,0x1ffff,0xfe000000,0x0,0x0,0x3f83fe8,0xe1c00,0x0,0x0,0x0,0x801,0xc1,0xc0000007,0x80003070, 0xfc0fc0,0x3c0001e1,0xe0000f0f,0x7878,0x3c3c0,0x1e1e00,0xf1e007,0xffc03f01,0xf007ffff,0xc03ffffe,0x1fffff0,0xfffff80,0x7fffe003, 0xffff001f,0xfff800ff,0xffc01fff,0xf800f001,0xfc00fc1f,0x8007e0fc,0x3f07e0,0x1f83f00,0xfc1f800,0x1f,0xf07e003f,0x3f001f8, 0x1f800fc0,0xfc007e07,0xe0000780,0x1e0000,0xf301f8,0xfc0ff80,0x7e07fc03,0xf03fe01f,0x81ff00fc,0xff807e0,0x7fc0f87f,0x81801f80, 0xf003f01f,0x801f80fc,0xfc07e0,0x7e03f00,0xfffffc07,0xffffe03f,0xffff01ff,0xfff807e0,0x7e003c00,0x3c01f81f,0x800fc0fc,0x7e07e0, 0x3f03f00,0x1f81f800,0x1f8000f,0xe07e001f,0x83fc00fc,0x1fe007e0,0xff003f07,0xf8000fe0,0x1fe07e,0x3f800,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1e,0x780007f, 0xffe00000,0xffe03fff,0xdf000000,0xf00,0x7800,0x0,0x0,0xfc0000,0x0,0x7e0000f0,0x1ff,0xfc000fff,0xfc03ffff,0xf83ffffc,0x780, 0xfffff00,0x7fff800,0xf000007,0xffff001f,0xffe00007,0xe000003f,0x0,0x0,0x0,0x3c000,0x1e000001,0xe0000f03,0xffffc001,0xffff01ff, 0xff0003ff,0xffe01e00,0x1fff,0xf81e0007,0x803ffff0,0x7fffe00,0x3c000f80,0x7ffffe1e,0xf078,0xfe003f,0xff800780,0xfff,0xf0078000, 0x7c3ffffc,0xf000,0x3ffff00,0xff0000,0xf803e01e,0x1e000,0x780003ff,0xfffc003c,0x7,0x800001e0,0x0,0x0,0x0,0x7fffbc01,0xffffc000, 0xffff003f,0xfff800ff,0xffc0003c,0x3ffe,0xf0078007,0x807ffffe,0xf000,0x7800f80,0x7ff00f,0x3c0f01e,0x1e007f,0xff8007ff,0xff001fff, 0xbc003c00,0xffffc,0x1fff0,0x1fffbc0,0xff0000,0x7c07c00f,0x800f8000,0x7e0001ff,0xffe0001e,0xf0,0x780,0x0,0x0,0x7fff80,0x7c0000, 0x1f000000,0x3c00001e,0x7c00f07,0xc1e00018,0xc0,0x0,0x60e303,0x7ffff80,0x380000,0x3fffff80,0x7c0003f,0xffffc001,0xf000000f, 0x80000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ff,0xff800003,0x8003ffff,0xfe0007c0,0x1ffffe,0x1e000,0x0,0x780000,0x1fffe03f,0xffff8000, 0x7,0x8000003c,0x3,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ffff,0xfe000000,0x0,0x0,0x3fffdf8,0xe1c00,0x0,0x0,0x0,0x0,0x1c1, 0xc000000f,0x7070,0x7fffc0,0x3c0001e1,0xe0000f0f,0x7878,0x3c3c0,0x1e1e00,0xf1e007,0xffc01fff,0xf007ffff,0xc03ffffe,0x1fffff0, 0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01fff,0xf000f001,0xfc007fff,0x3fff8,0x1fffc0,0xfffe00,0x7fff000,0x3b,0xfffc003f, 0xfff001ff,0xff800fff,0xfc007fff,0xe0000780,0x1e0000,0xf3fff8,0xffff780,0x7fffbc03,0xfffde01f,0xffef00ff,0xff7807ff,0xfbc0ffff, 0xff800fff,0xf001ffff,0x800ffffc,0x7fffe0,0x3ffff00,0xfffffc07,0xffffe03f,0xffff01ff,0xfff803ff,0xfc003c00,0x3c00ffff,0x7fff8, 0x3fffc0,0x1fffe00,0xffff000,0x1f,0xfffc001f,0xffbc00ff,0xfde007ff,0xef003fff,0x780007e0,0x1ffffc,0x1f800,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1e,0x700003f, 0xffc00000,0x7fc01fff,0x9f800000,0xf80,0xf800,0x0,0x0,0xfc0000,0x0,0x7e0000f0,0xff,0xf8000fff,0xfc03ffff,0xf83ffff8,0x780, 0xffffe00,0x7fff000,0xf000003,0xfffe001f,0xffc00007,0xe000003f,0x0,0x0,0x0,0x3c000,0xf000003,0xe0000f83,0xffff0000,0xffff01ff, 0xfc0003ff,0xffe01e00,0xfff,0xf01e0007,0x803ffff0,0x7fffc00,0x3c0007c0,0x7ffffe1e,0xf078,0x7e003f,0xff000780,0x7ff,0xe0078000, 0x3c3ffff8,0xf000,0x1fffe00,0x7e0000,0xf803e03e,0x1f000,0x780003ff,0xfffc003c,0x7,0x800001e0,0x0,0x0,0x0,0x3fff3c01,0xefff8000, 0x7ffe001f,0xff78007f,0xff80003c,0x1ffc,0xf0078007,0x807ffffe,0xf000,0x78007c0,0x3ff00f,0x3c0f01e,0x1e003f,0xff0007bf,0xfe000fff, 0xbc003c00,0xffff8,0xfff0,0xfff3c0,0x7e0000,0x7c07c01f,0x7c000,0x7c0001ff,0xffe0001e,0xf0,0x780,0x0,0x0,0x3fff80,0x380000, 0x3e000000,0x7c00003e,0x7801f07,0xc1e00018,0xc0,0x0,0x39c1ce,0x7ffff00,0x1c0000,0xfffff80,0x380003f,0xffffc000,0xe0000007, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ff,0xff000007,0x1ffcf,0xfe000380,0x1ffffe,0x1e000,0x0,0x780000,0xfffe03f,0xffff8000,0x7, 0x8000003c,0x3,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ffff,0xfe000000,0x0,0x0,0x3dffdf8,0xe1c00,0x0,0x0,0x0,0x0,0x381, 0xc000001e,0xe070,0x7fff80,0x7c0001f3,0xe0000f9f,0x7cf8,0x3e7c0,0x1f3e00,0xfbe007,0xffc00fff,0xf007ffff,0xc03ffffe,0x1fffff0, 0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01fff,0xc000f000,0xfc007ffe,0x3fff0,0x1fff80,0xfffc00,0x7ffe000,0x79,0xfff8001f, 0xffe000ff,0xff0007ff,0xf8003fff,0xc0000780,0x1e0000,0xf3fff0,0x7ffe780,0x3fff3c01,0xfff9e00f,0xffcf007f,0xfe7803ff,0xf3c07ff3, 0xff8007ff,0xe000ffff,0x7fff8,0x3fffc0,0x1fffe00,0xfffffc07,0xffffe03f,0xffff01ff,0xfff801ff,0xf8003c00,0x3c007ffe,0x3fff0, 0x1fff80,0xfffc00,0x7ffe000,0x1d,0xfff8000f,0xff3c007f,0xf9e003ff,0xcf001ffe,0x780007c0,0x1efff8,0x1f000,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780000,0x1e,0xf000003, 0xfe000000,0x1f000fff,0xfc00000,0x780,0xf000,0x0,0x0,0xf80000,0x0,0x7e0001e0,0x7f,0xf0000fff,0xfc03ffff,0xf81ffff0,0x780, 0x7fff800,0x1ffe000,0x1f000000,0xfff8001f,0xff000007,0xe000003e,0x0,0x0,0x0,0x3c000,0xf800003,0xc0000783,0xfff80000,0x3ffe01ff, 0xe00003ff,0xffe01e00,0x7ff,0xc01e0007,0x803ffff0,0x3fff800,0x3c0003c0,0x7ffffe1e,0xf078,0x7e000f,0xfe000780,0x3ff,0xc0078000, 0x3e1fffe0,0xf000,0x7ff800,0x7e0000,0xf803e07c,0xf800,0x780003ff,0xfffc003c,0x3,0xc00001e0,0x0,0x0,0x0,0xffe3c01,0xe7ff0000, 0x3ffc000f,0xfe78003f,0xfe00003c,0x7f0,0xf0078007,0x807ffffe,0xf000,0x78003e0,0xff00f,0x3c0f01e,0x1e001f,0xfe00079f,0xfc0007ff, 0x3c003c00,0x7ffe0,0x1ff0,0x7fe3c0,0x7e0000,0x7c07c03e,0x3e000,0x7c0001ff,0xffe0001e,0xf0,0x780,0x0,0x0,0xfff00,0x100000, 0x3e000000,0x7800003c,0xf800f07,0xc1e00018,0xc0,0x0,0x1f80fc,0x3fffc00,0xc0000,0x3ffff80,0x100003f,0xffffc000,0x40000002, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xff,0xfc000006,0xff87,0xfc000100,0x1ffffe,0x1e000,0x0,0x780000,0x3ffc03f,0xffff8000,0x7, 0x8000003c,0x3,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ffff,0xfe000000,0x0,0x0,0x3dff9f8,0xe1c00,0x0,0x0,0x0,0x0,0x3ff, 0xf800003c,0xfffe,0x1ffe00,0x780000f3,0xc000079e,0x3cf0,0x1e780,0xf3c00,0x7bc007,0xffc003ff,0xe007ffff,0xc03ffffe,0x1fffff0, 0xfffff80,0x7fffe003,0xffff001f,0xfff800ff,0xffc01ffc,0xf000,0xfc001ffc,0xffe0,0x7ff00,0x3ff800,0x1ffc000,0x70,0xfff00007, 0xff80003f,0xfc0001ff,0xe0000fff,0x780,0x1e0000,0xf3ffe0,0x1ffc780,0xffe3c00,0x7ff1e003,0xff8f001f,0xfc7800ff,0xe3c03fe1, 0xff0003ff,0xc0007ffc,0x3ffe0,0x1fff00,0xfff800,0xfffffc07,0xffffe03f,0xffff01ff,0xfff800ff,0xf0003c00,0x3c003ffc,0x1ffe0, 0xfff00,0x7ff800,0x3ffc000,0x38,0xfff00007,0xfe3c003f,0xf1e001ff,0x8f000ffc,0x780007c0,0x1e7ff0,0x1f000,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000, 0x1fc,0x0,0x780,0xf000,0x0,0x0,0x1f80000,0x0,0x1e0,0x1f,0xc0000000,0x0,0x1ff80,0x0,0xffc000,0x7f8000,0x0,0x3fe00007,0xfc000000, 0x7e,0x0,0x0,0x0,0x0,0x7c00000,0x0,0x0,0xff00000,0x0,0x0,0xfe,0x0,0x0,0x3fc000,0x0,0x0,0x0,0x3,0xf8000000,0xff,0xc0000000, 0x1ff00,0x0,0x1fe000,0x0,0x0,0x0,0x0,0x3c,0x3,0xc00001e0,0x0,0x0,0x0,0x3f80000,0x1fc0000,0x7f00003,0xf8000007,0xf0000000, 0x0,0xf0000000,0x0,0xf000,0x0,0x0,0x0,0x7,0xf8000787,0xf00001fc,0x3c000000,0x7f80,0x0,0x1f8000,0x0,0x0,0x0,0x7c000000,0x1e, 0xf0,0x780,0x0,0x0,0x3fc00,0x0,0x3c000000,0x7800003c,0xf000601,0xc00018,0xc0,0x0,0x0,0x3fe000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0xf,0xf0000000,0x7e03,0xf0000000,0x0,0x0,0x0,0x0,0xfe0000,0x0,0x0,0x3c,0x2007,0x80000000,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c7e0f0,0xe1c00,0x0,0x3800000,0x0,0x0,0x3ff,0xf8000078,0xfffe,0x7f800,0x0,0x0,0x0,0x0, 0x0,0x0,0xff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7f0,0x3f80,0x1fc00,0xfe000,0x7f0000,0x70,0x3fc00001,0xfe00000f,0xf000007f, 0x800003fc,0x0,0x0,0xff00,0x7f0000,0x3f80000,0x1fc00000,0xfe000007,0xf000003f,0x80001f80,0xfc00007f,0xfe0,0x7f00,0x3f800, 0x1fc000,0x0,0x0,0x0,0x3f,0xc0000000,0xff0,0x7f80,0x3fc00,0x1fe000,0xff0000,0x78,0x3fc00001,0xf800000f,0xc000007e,0x3f0,0x7c0, 0x1e1fc0,0x1f000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000,0x0,0x0,0x3c0,0x1e000,0x0,0x0,0x1f00000,0x0,0x3c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x7c,0x0,0x0,0x0,0x0,0x3e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0xe0000000,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x3c,0x1,0xe00001e0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf0000000,0x0,0xf000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x78000000,0x1e,0xf0,0x780,0x0,0x0,0x0,0x0,0x3c000000,0x78000078,0xf000000,0x18,0xc0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x180000,0x0,0x0,0x3c,0x3c0f,0x80000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0xe1c00,0x0,0x1800000,0x0,0x0,0x3ff,0xf80000f0,0xfffe,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0xc,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30,0x0,0x0,0x0,0x0,0x780,0x1e0000,0x1e000,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000, 0x0,0x0,0x3c0,0x1e000,0x0,0x0,0x1f00000,0x0,0x3c0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7c,0x0,0x0,0x0,0x0,0x1f80000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0xf0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c,0x1,0xe00001e0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0xe0000000,0x0,0xf000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x0,0xf8000000, 0x1f,0xf0,0xf80,0x0,0x0,0x0,0x0,0x78000000,0xf8000078,0x1e000000,0x8,0x40,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x180000,0x0,0x0,0x3c,0x3fff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x3c00000,0xe1c00,0x0,0x1c00000,0x0,0x0,0x1,0xc00001e0,0x70,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xe,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf80,0x1e0000,0x3e000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000,0x0,0x0,0x1e0,0x3c000,0x0,0x0,0x1f00000, 0x0,0x780,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7c,0x0,0x0,0x0,0x0,0xfe0100,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xf8000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3f,0xf0000000,0xf0007fe0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0xe0000000, 0x0,0xf000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x0,0xf0000000,0x1f,0x800000f0,0x1f80,0x0,0x0,0x0,0x0, 0x78000000,0xf0000070,0x1c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x180000,0x0,0x0,0x3c,0x3ffe,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0xe1c00,0x0,0xe00000, 0x0,0x0,0x1,0xc00003ff,0xe0000070,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0xf00,0x1e0000,0x3c000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000,0x0,0x0,0x1e0,0x7c000,0x0,0x0,0x1e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x78,0x0,0x0,0x0,0x0,0x7fff80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x78000000, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3f,0xf0000000,0x7fe0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4003,0xe0000000,0x0,0x1f000,0x0,0x0, 0x0,0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x1,0xf0000000,0xf,0xfc0000f0,0x3ff00,0x0,0x0,0x0,0x0,0x70000001,0xf00000e0, 0x1c000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x180000, 0x0,0x0,0x3c,0xff8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0xe1c00,0x0,0xe00000,0x0,0x0,0x1,0xc00003ff, 0xe0000070,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1f00,0x1e0000, 0x7c000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x30000000,0x0,0x0,0xf0,0x78000,0x0,0x0,0x3e00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf8,0x0, 0x0,0x0,0x0,0x1fff80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3f, 0xf0000000,0x7fe0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x780f,0xc0000000,0x0,0x3e000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0, 0x0,0x0,0x0,0x0,0x3,0xe0000000,0xf,0xfc0000f0,0x3ff00,0x0,0x0,0x0,0x0,0xf0000103,0xe0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x180000,0x0,0x0,0x3c,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x0,0x0,0x21e00000,0x0,0x0,0x1,0xc00003ff,0xe0000070,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10f, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x10f,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3e00,0x1e0000,0xf8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x30000000,0x0,0x0, 0xf8,0xf8000,0x0,0x0,0x3c00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf0,0x0,0x0,0x0,0x0,0x1fe00,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3f,0xf0000000,0x7fe0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x7fff,0xc0000000,0x0,0x3ffe000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x7f,0xe0000000,0x7,0xfc0000f0, 0x3fe00,0x0,0x0,0x0,0x0,0x600001ff,0xe0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x180000,0x0,0x0,0x3c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x0,0x0, 0x3fe00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1ff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x7fe00,0x1e0000,0x1ff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x1fffffe0,0x0,0x0,0x0,0x0,0x0,0x0,0x7fff,0x80000000,0x0,0x3ffc000,0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0, 0x0,0x0,0x0,0x0,0x7f,0xc0000000,0x0,0xfc0000f0,0x3f000,0x0,0x0,0x0,0x0,0x1ff,0xc0000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x3c00000,0x0,0x0,0x3fc00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fe,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fe,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7fc00,0x1e0000,0x1ff0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fffffe0,0x0,0x0,0x0,0x0,0x0,0x0,0x3ffe,0x0,0x0,0x3ff8000,0x0,0x0,0x0, 0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x7f,0x80000000,0x0,0xf0,0x0,0x0,0x0,0x0,0x0,0x1ff,0x80000000,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x0,0x0,0x3f800000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fc,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fc,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7f800,0x1e0000,0x1fe0000,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fffffe0,0x0,0x0,0x0,0x0,0x0,0x0,0x7f8,0x0,0x0,0x3fe0000, 0x0,0x0,0x0,0x0,0x780,0x0,0x3c000000,0x0,0x0,0x0,0x0,0x0,0x7e,0x0,0x0,0xf0,0x0,0x0,0x0,0x0,0x0,0xfe,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3c00000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x7e000,0x1e0000,0x1f80000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1fffffe0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0 }; // Define a 40x38 'danger' color logo (used by cimg::dialog()). const unsigned char logo40x38[4576] = { 177,200,200,200,3,123,123,0,36,200,200,200,1,123,123,0,2,255,255,0,1,189,189,189,1,0,0,0,34,200,200,200, 1,123,123,0,4,255,255,0,1,189,189,189,1,0,0,0,1,123,123,123,32,200,200,200,1,123,123,0,5,255,255,0,1,0,0, 0,2,123,123,123,30,200,200,200,1,123,123,0,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,29,200,200,200, 1,123,123,0,7,255,255,0,1,0,0,0,2,123,123,123,28,200,200,200,1,123,123,0,8,255,255,0,1,189,189,189,1,0,0,0, 2,123,123,123,27,200,200,200,1,123,123,0,9,255,255,0,1,0,0,0,2,123,123,123,26,200,200,200,1,123,123,0,10,255, 255,0,1,189,189,189,1,0,0,0,2,123,123,123,25,200,200,200,1,123,123,0,3,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,3,255,255,0,1,0,0,0,2,123,123,123,24,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,3,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,23,200,200,200,1,123,123,0,4,255,255,0,5,0,0,0,4,255,255,0,1,0,0,0,2,123,123,123, 22,200,200,200,1,123,123,0,5,255,255,0,5,0,0,0,4,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,21,200,200,200, 1,123,123,0,5,255,255,0,5,0,0,0,5,255,255,0,1,0,0,0,2,123,123,123,20,200,200,200,1,123,123,0,6,255,255,0,5,0,0, 0,5,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,19,200,200,200,1,123,123,0,6,255,255,0,1,123,123,0,3,0,0,0,1, 123,123,0,6,255,255,0,1,0,0,0,2,123,123,123,18,200,200,200,1,123,123,0,7,255,255,0,1,189,189,189,3,0,0,0,1,189, 189,189,6,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,17,200,200,200,1,123,123,0,8,255,255,0,3,0,0,0,8,255,255, 0,1,0,0,0,2,123,123,123,16,200,200,200,1,123,123,0,9,255,255,0,1,123,123,0,1,0,0,0,1,123,123,0,8,255,255,0,1,189, 189,189,1,0,0,0,2,123,123,123,15,200,200,200,1,123,123,0,9,255,255,0,1,189,189,189,1,0,0,0,1,189,189,189,9,255,255, 0,1,0,0,0,2,123,123,123,14,200,200,200,1,123,123,0,11,255,255,0,1,0,0,0,10,255,255,0,1,189,189,189,1,0,0,0,2,123, 123,123,13,200,200,200,1,123,123,0,23,255,255,0,1,0,0,0,2,123,123,123,12,200,200,200,1,123,123,0,11,255,255,0,1,189, 189,189,2,0,0,0,1,189,189,189,9,255,255,0,1,189,189,189,1,0,0,0,2,123,123,123,11,200,200,200,1,123,123,0,11,255,255, 0,4,0,0,0,10,255,255,0,1,0,0,0,2,123,123,123,10,200,200,200,1,123,123,0,12,255,255,0,4,0,0,0,10,255,255,0,1,189,189, 189,1,0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,12,255,255,0,1,189,189,189,2,0,0,0,1,189,189,189,11,255,255,0,1, 0,0,0,2,123,123,123,9,200,200,200,1,123,123,0,27,255,255,0,1,0,0,0,3,123,123,123,8,200,200,200,1,123,123,0,26,255, 255,0,1,189,189,189,1,0,0,0,3,123,123,123,9,200,200,200,1,123,123,0,24,255,255,0,1,189,189,189,1,0,0,0,4,123,123, 123,10,200,200,200,1,123,123,0,24,0,0,0,5,123,123,123,12,200,200,200,27,123,123,123,14,200,200,200,25,123,123,123,86, 200,200,200,91,49,124,118,124,71,32,124,95,49,56,114,52,82,121,0}; //! Get/set default output stream for the \CImg library messages. /** \param file Desired output stream. Set to \c 0 to get the currently used output stream only. \return Currently used output stream. **/ inline std::FILE* output(std::FILE *file) { static std::FILE *res = stderr; if (file) res = file; return res; } //! Display a warning message on the default output stream. /** \param format C-string containing the format of the message, as with <tt>std::printf()</tt>. \note If configuration macro \c cimg_strict_warnings is set, this function throws a \c CImgWarningException instead. \warning As the first argument is a format string, it is highly recommended to write \code cimg::warn("%s",warning_message); \endcode instead of \code cimg::warn(warning_message); \endcode if \c warning_message can be arbitrary, to prevent nasty memory access. **/ inline void warn(const char *const format, ...) { if (cimg::exception_mode()>=1) { char message[16384] = { 0 }; std::va_list ap; va_start(ap,format); cimg_vsnprintf(message,sizeof(message),format,ap); va_end(ap); #ifdef cimg_strict_warnings throw CImgWarningException(message); #else std::fprintf(cimg::output(),"\n%s[CImg] *** Warning ***%s%s",cimg::t_red,cimg::t_normal,message); #endif } } // Execute an external system command. /** \param command C-string containing the command line to execute. \param module_name Module name. \return Status value of the executed command, whose meaning is OS-dependent. \note This function is similar to <tt>std::system()</tt> but it does not open an extra console windows on Windows-based systems. **/ inline int system(const char *const command, const char *const module_name=0) { #if cimg_OS==2 PROCESS_INFORMATION pi; STARTUPINFO si; std::memset(&pi,0,sizeof(PROCESS_INFORMATION)); std::memset(&si,0,sizeof(STARTUPINFO)); GetStartupInfo(&si); si.cb = sizeof(si); si.wShowWindow = SW_HIDE; si.dwFlags |= SW_HIDE | STARTF_USESHOWWINDOW; const BOOL res = CreateProcess((LPCTSTR)module_name,(LPTSTR)command,0,0,FALSE,0,0,0,&si,&pi); if (res) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); return 0; } else #endif return std::system(command); return module_name?0:1; } //! Return a reference to a temporary variable of type T. template<typename T> inline T& temporary(const T&) { static T temp; return temp; } //! Exchange values of variables \c a and \c b. template<typename T> inline void swap(T& a, T& b) { T t = a; a = b; b = t; } //! Exchange values of variables (\c a1,\c a2) and (\c b1,\c b2). template<typename T1, typename T2> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2) { cimg::swap(a1,b1); cimg::swap(a2,b2); } //! Exchange values of variables (\c a1,\c a2,\c a3) and (\c b1,\c b2,\c b3). template<typename T1, typename T2, typename T3> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3) { cimg::swap(a1,b1,a2,b2); cimg::swap(a3,b3); } //! Exchange values of variables (\c a1,\c a2,...,\c a4) and (\c b1,\c b2,...,\c b4). template<typename T1, typename T2, typename T3, typename T4> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4) { cimg::swap(a1,b1,a2,b2,a3,b3); cimg::swap(a4,b4); } //! Exchange values of variables (\c a1,\c a2,...,\c a5) and (\c b1,\c b2,...,\c b5). template<typename T1, typename T2, typename T3, typename T4, typename T5> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4); cimg::swap(a5,b5); } //! Exchange values of variables (\c a1,\c a2,...,\c a6) and (\c b1,\c b2,...,\c b6). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5); cimg::swap(a6,b6); } //! Exchange values of variables (\c a1,\c a2,...,\c a7) and (\c b1,\c b2,...,\c b7). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6); cimg::swap(a7,b7); } //! Exchange values of variables (\c a1,\c a2,...,\c a8) and (\c b1,\c b2,...,\c b8). template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3, T4& a4, T4& b4, T5& a5, T5& b5, T6& a6, T6& b6, T7& a7, T7& b7, T8& a8, T8& b8) { cimg::swap(a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6,a7,b7); cimg::swap(a8,b8); } //! Return the endianness of the current architecture. /** \return \c false for <i>Little Endian</i> or \c true for <i>Big Endian</i>. **/ inline bool endianness() { const int x = 1; return ((unsigned char*)&x)[0]?false:true; } //! Reverse endianness of all elements in a memory buffer. /** \param[in,out] buffer Memory buffer whose endianness must be reversed. \param size Number of buffer elements to reverse. **/ template<typename T> inline void invert_endianness(T* const buffer, const unsigned long size) { if (size) switch (sizeof(T)) { case 1 : break; case 2 : { for (unsigned short *ptr = (unsigned short*)buffer+size; ptr>(unsigned short*)buffer; ) { const unsigned short val = *(--ptr); *ptr = (unsigned short)((val>>8)|((val<<8))); } } break; case 4 : { for (unsigned int *ptr = (unsigned int*)buffer+size; ptr>(unsigned int*)buffer; ) { const unsigned int val = *(--ptr); *ptr = (val>>24)|((val>>8)&0xff00)|((val<<8)&0xff0000)|(val<<24); } } break; default : { for (T* ptr = buffer+size; ptr>buffer; ) { unsigned char *pb = (unsigned char*)(--ptr), *pe = pb + sizeof(T); for (int i = 0; i<(int)sizeof(T)/2; ++i) swap(*(pb++),*(--pe)); } } } } //! Reverse endianness of a single variable. /** \param[in,out] a Variable to reverse. \return Reference to reversed variable. **/ template<typename T> inline T& invert_endianness(T& a) { invert_endianness(&a,1); return a; } // Conversion functions to get more precision when trying to store unsigned ints values as floats. inline unsigned int float2uint(const float f) { int tmp = 0; std::memcpy(&tmp,&f,sizeof(float)); if (tmp>=0) return (unsigned int)f; unsigned int u; std::memcpy(&u,&f,sizeof(float)); // use memcpy instead of assignment to avoid undesired optimizations by C++-compiler. return ((u)<<1)>>1; // set sign bit to 0. } inline float uint2float(const unsigned int u) { if (u<(1U<<19)) return (float)u; // Consider safe storage of unsigned int as floats until 19bits (i.e 524287). float f; const unsigned int v = u|(1U<<(8*sizeof(unsigned int)-1)); // set sign bit to 1. std::memcpy(&f,&v,sizeof(float)); // use memcpy instead of simple assignment to avoid undesired optimizations by C++-compiler. return f; } //! Return the value of a system timer, with a millisecond precision. /** \note The timer does not necessarily starts from \c 0. **/ inline unsigned long time() { #if cimg_OS==1 struct timeval st_time; gettimeofday(&st_time,0); return (unsigned long)(st_time.tv_usec/1000 + st_time.tv_sec*1000); #elif cimg_OS==2 SYSTEMTIME st_time; GetSystemTime(&st_time); return (unsigned long)(st_time.wMilliseconds + 1000*(st_time.wSecond + 60*(st_time.wMinute + 60*st_time.wHour))); #else return 0; #endif } // Implement a tic/toc mechanism to display elapsed time of algorithms. inline unsigned long tictoc(const bool is_tic) { static unsigned long t0 = 0; const unsigned long t = cimg::time(); if (is_tic) return (t0 = t); const unsigned long dt = t>=t0?(t - t0):cimg::type<unsigned long>::max(); const unsigned int edays = (unsigned int)(dt/86400000.0), ehours = (unsigned int)((dt - edays*86400000.0)/3600000.0), emin = (unsigned int)((dt - edays*86400000.0 - ehours*3600000.0)/60000.0), esec = (unsigned int)((dt - edays*86400000.0 - ehours*3600000.0 - emin*60000.0)/1000.0), ems = (unsigned int)(dt - edays*86400000.0 - ehours*3600000.0 - emin*60000.0 - esec*1000.0); if (!edays && !ehours && !emin && !esec) std::fprintf(cimg::output(),"%s[CImg] Elapsed time: %u ms%s\n",cimg::t_red,ems,cimg::t_normal); else { if (!edays && !ehours && !emin) std::fprintf(cimg::output(),"%s[CImg] Elapsed time: %u sec %u ms%s\n",cimg::t_red,esec,ems,cimg::t_normal); else { if (!edays && !ehours) std::fprintf(cimg::output(),"%s[CImg] Elapsed time: %u min %u sec %u ms%s\n",cimg::t_red,emin,esec,ems,cimg::t_normal); else{ if (!edays) std::fprintf(cimg::output(),"%s[CImg] Elapsed time: %u hours %u min %u sec %u ms%s\n",cimg::t_red,ehours,emin,esec,ems,cimg::t_normal); else{ std::fprintf(cimg::output(),"%s[CImg] Elapsed time: %u days %u hours %u min %u sec %u ms%s\n",cimg::t_red,edays,ehours,emin,esec,ems,cimg::t_normal); } } } } return t; } //! Start tic/toc timer for time measurement between code instructions. /** \return Current value of the timer (same value as time()). **/ inline unsigned long tic() { return cimg::tictoc(true); } //! End tic/toc timer and displays elapsed time from last call to tic(). /** \return Time elapsed (in ms) since last call to tic(). **/ inline unsigned long toc() { return cimg::tictoc(false); } //! Sleep for a given numbers of milliseconds. /** \param milliseconds Number of milliseconds to wait for. \note This function frees the CPU ressources during the sleeping time. It can be used to temporize your program properly, without wasting CPU time. **/ inline void sleep(const unsigned int milliseconds) { #if cimg_OS==1 struct timespec tv; tv.tv_sec = milliseconds/1000; tv.tv_nsec = (milliseconds%1000)*1000000; nanosleep(&tv,0); #elif cimg_OS==2 Sleep(milliseconds); #endif } inline unsigned int _wait(const unsigned int milliseconds, unsigned long& timer) { if (!timer) timer = cimg::time(); const unsigned long current_time = cimg::time(); if (current_time>=timer+milliseconds) { timer = current_time; return 0; } const unsigned long time_diff = timer + milliseconds - current_time; timer = current_time + time_diff; cimg::sleep(time_diff); return (unsigned int)time_diff; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \return Number of milliseconds elapsed since the last call to wait(). \note Same as sleep() with a waiting time computed with regard to the last call of wait(). It may be used to temporize your program properly, without wasting CPU time. **/ inline unsigned int wait(const unsigned int milliseconds) { static unsigned long timer = 0; if (!timer) timer = cimg::time(); return _wait(milliseconds,timer); } // Random number generators. // CImg may use its own Random Number Generator (RNG) if configuration macro 'cimg_use_rng' is set. // Use it for instance when you have to deal with concurrent threads trying to call std::srand() // at the same time! #ifdef cimg_use_rng // Use a custom RNG. inline unsigned int _rand(const unsigned long seed=0, const bool set_seed=false) { static unsigned long next = 1; if (set_seed) next = seed; next = next*1103515245 + 12345; return (unsigned int)((next>>16)&0x7FFF); } inline void srand() { static bool is_first_time = true; if (is_first_time) { const unsigned long t = cimg::time(); #if cimg_OS==1 cimg::_rand(t+(unsigned long)getpid(),true); #elif cimg_OS==2 cimg::_rand(t+(unsigned long)_getpid(),true); #else cimg::_rand(t,true); #endif is_first_time = false; } } inline double rand() { cimg::srand(); return cimg::_rand()/32767.; } #else // Use the system RNG. inline void srand() { static bool is_first_time = true; if (is_first_time) { const unsigned int t = (unsigned int)cimg::time(); #if cimg_OS==1 std::srand(t+(unsigned int)getpid()); #elif cimg_OS==2 std::srand(t+(unsigned int)_getpid()); #else std::srand(t); #endif is_first_time = false; } } //! Return a random variable between [0,1] with respect to an uniform distribution. /** **/ inline double rand() { cimg::srand(); return (double)std::rand()/RAND_MAX; } #endif //! Return a random variable between [-1,1] with respect to an uniform distribution. /** **/ inline double crand() { return 1-2*cimg::rand(); } //! Return a random variable following a gaussian distribution and a standard deviation of 1. /** **/ inline double grand() { double x1, w; do { const double x2 = 2*cimg::rand() - 1.0; x1 = 2*cimg::rand()-1.0; w = x1*x1 + x2*x2; } while (w<=0 || w>=1.0); return x1*std::sqrt((-2*std::log(w))/w); } //! Return a random variable following a Poisson distribution of parameter z. /** **/ inline unsigned int prand(const double z) { if (z<=1.0e-10) return 0; if (z>100) return (unsigned int)((std::sqrt(z) * cimg::grand()) + z); unsigned int k = 0; const double y = std::exp(-z); for (double s = 1.0; s>=y; ++k) s*=cimg::rand(); return k-1; } //! Bitwise-rotate value on the left. template<typename T> inline T rol(const T a, const unsigned int n=1) { return n?(T)((a<<n)|(a>>((sizeof(T)<<3)-n))):a; } inline float rol(const float a, const unsigned int n=1) { return (float)rol((int)a,n); } inline double rol(const double a, const unsigned int n=1) { return (double)rol((long)a,n); } //! Bitwise-rotate value on the right. template<typename T> inline T ror(const T a, const unsigned int n=1) { return n?(T)((a>>n)|(a<<((sizeof(T)<<3)-n))):a; } inline float ror(const float a, const unsigned int n=1) { return (float)ror((int)a,n); } inline double ror(const double a, const unsigned int n=1) { return (double)ror((long)a,n); } //! Return absolute value of a value. template<typename T> inline T abs(const T a) { return a>=0?a:-a; } inline bool abs(const bool a) { return a; } inline unsigned char abs(const unsigned char a) { return a; } inline unsigned short abs(const unsigned short a) { return a; } inline unsigned int abs(const unsigned int a) { return a; } inline unsigned long abs(const unsigned long a) { return a; } inline double abs(const double a) { return std::fabs(a); } inline float abs(const float a) { return (float)std::fabs((double)a); } inline int abs(const int a) { return std::abs(a); } //! Return square of a value. template<typename T> inline T sqr(const T val) { return val*val; } //! Return <tt>1 + log_10(x)</tt> of a value \c x. inline int xln(const int x) { return x>0?(int)(1+std::log10((double)x)):1; } //! Return the minimum between two values. template<typename t1, typename t2> inline typename cimg::superset<t1,t2>::type min(const t1& a, const t2& b) { typedef typename cimg::superset<t1,t2>::type t1t2; return (t1t2)(a<=b?a:b); } //! Return the minimum between three values. template<typename t1, typename t2, typename t3> inline typename cimg::superset2<t1,t2,t3>::type min(const t1& a, const t2& b, const t3& c) { typedef typename cimg::superset2<t1,t2,t3>::type t1t2t3; return (t1t2t3)cimg::min(cimg::min(a,b),c); } //! Return the minimum between four values. template<typename t1, typename t2, typename t3, typename t4> inline typename cimg::superset3<t1,t2,t3,t4>::type min(const t1& a, const t2& b, const t3& c, const t4& d) { typedef typename cimg::superset3<t1,t2,t3,t4>::type t1t2t3t4; return (t1t2t3t4)cimg::min(cimg::min(a,b,c),d); } //! Return the maximum between two values. template<typename t1, typename t2> inline typename cimg::superset<t1,t2>::type max(const t1& a, const t2& b) { typedef typename cimg::superset<t1,t2>::type t1t2; return (t1t2)(a>=b?a:b); } //! Return the maximum between three values. template<typename t1, typename t2, typename t3> inline typename cimg::superset2<t1,t2,t3>::type max(const t1& a, const t2& b, const t3& c) { typedef typename cimg::superset2<t1,t2,t3>::type t1t2t3; return (t1t2t3)cimg::max(cimg::max(a,b),c); } //! Return the maximum between four values. template<typename t1, typename t2, typename t3, typename t4> inline typename cimg::superset3<t1,t2,t3,t4>::type max(const t1& a, const t2& b, const t3& c, const t4& d) { typedef typename cimg::superset3<t1,t2,t3,t4>::type t1t2t3t4; return (t1t2t3t4)cimg::max(cimg::max(a,b,c),d); } //! Return the sign of a value. template<typename T> inline T sign(const T x) { return (x<0)?(T)(-1):(x==0?(T)0:(T)1); } //! Return the nearest power of 2 higher than given value. template<typename T> inline unsigned long nearest_pow2(const T x) { unsigned long i = 1; while (x>i) i<<=1; return i; } //! Return the sinc of a given value. inline double sinc(const double x) { return x?std::sin(x)/x:1; } //! Return the modulo of a value. /** \param x Input value. \param m Modulo value. \note This modulo function accepts negative and floating-points modulo numbers, as well as variables of any type. **/ template<typename T> inline T mod(const T& x, const T& m) { const double dx = (double)x, dm = (double)m; return (T)(dx - dm * std::floor(dx / dm)); } inline int mod(const bool x, const bool m) { return m?(x?1:0):0; } inline int mod(const char x, const char m) { return x>=0?x%m:(x%m?m+x%m:0); } inline int mod(const short x, const short m) { return x>=0?x%m:(x%m?m+x%m:0); } inline int mod(const int x, const int m) { return x>=0?x%m:(x%m?m+x%m:0); } inline int mod(const long x, const long m) { return x>=0?x%m:(x%m?m+x%m:0); } inline int mod(const unsigned char x, const unsigned char m) { return x%m; } inline int mod(const unsigned short x, const unsigned short m) { return x%m; } inline int mod(const unsigned int x, const unsigned int m) { return x%m; } inline int mod(const unsigned long x, const unsigned long m) { return x%m; } //! Return the min-mod of two values. /** \note <i>minmod(\p a,\p b)</i> is defined to be: - <i>minmod(\p a,\p b) = min(\p a,\p b)</i>, if \p a and \p b have the same sign. - <i>minmod(\p a,\p b) = 0</i>, if \p a and \p b have different signs. **/ template<typename T> inline T minmod(const T a, const T b) { return a*b<=0?0:(a>0?(a<b?a:b):(a<b?b:a)); } //! Return base-2 logarithm of a value. inline double log2(const double x) { static const double base = std::log(2.0); return std::log(x)/base; } //! Return rounded value. /** \param x Value to be rounded. \param y Rounding precision. \param rounding_type Type of rounding operation (\c 0 = nearest, \c -1 = backward, \c 1 = forward). \return Rounded value, having the same type as input value \c x. **/ template<typename T> inline T round(const T x, const double y=1, const int rounding_type=0) { if (y<=0) return x; const double sx = (double)x/y, floor = std::floor(sx), delta = sx - floor; return (T)(y*(rounding_type<0?floor:rounding_type>0?std::ceil(sx):delta<0.5?floor:std::ceil(sx))); } inline double _pythagore(double a, double b) { const double absa = cimg::abs(a), absb = cimg::abs(b); if (absa>absb) { const double tmp = absb/absa; return absa*std::sqrt(1.0+tmp*tmp); } else { const double tmp = absa/absb; return absb==0?0:absb*std::sqrt(1.0+tmp*tmp); } } //! Convert ascii character to lower case. inline char uncase(const char x) { return (char)((x<'A'||x>'Z')?x:x-'A'+'a'); } //! Convert C-string to lower case. inline void uncase(char *const str) { if (str) for (char *ptr = str; *ptr; ++ptr) *ptr = uncase(*ptr); } //! Read value in a C-string. /** \param str C-string containing the float value to read. \return Read value. \note Same as <tt>std::atof()</tt> extended to manage the retrieval of fractions from C-strings, as in <em>"1/2"</em>. **/ inline double atof(const char *const str) { double x = 0, y = 1; if (!str) return 0; else { std::sscanf(str,"%lf/%lf",&x,&y); return x/y; } } //! Compare the first \p l characters of two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \param l Number of characters to compare. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strncasecmp(const char *const str1, const char *const str2, const int l) { if (!l) return 0; if (!str1) return str2?-1:0; const char *nstr1 = str1, *nstr2 = str2; int k, diff = 0; for (k = 0; k<l && !(diff = uncase(*nstr1)-uncase(*nstr2)); ++k) { ++nstr1; ++nstr2; } return k!=l?diff:0; } //! Compare two C-strings, ignoring the case. /** \param str1 C-string. \param str2 C-string. \return \c 0 if the two strings are equal, something else otherwise. \note This function has to be defined since it is not provided by all C++-compilers (not ANSI). **/ inline int strcasecmp(const char *const str1, const char *const str2) { if (!str1) return str2?-1:0; const unsigned int l1 = (unsigned int)std::strlen(str1), l2 = (unsigned int)std::strlen(str2); return cimg::strncasecmp(str1,str2,1+(l1<l2?l1:l2)); } //! Remove delimiters on the start and/or end of a C-string. /** \param[in,out] str C-string to work with (modified at output). \param delimiter Delimiter character code to remove. \param is_symmetric Tells if the removal is done only if delimiters are symmetric (both at the beginning and the end of \c s). \param is_iterative Tells if the removal is done if several iterations are possible. \return \c true if delimiters have been removed, \c false otherwise. **/ inline bool strpare(char *const str, const char delimiter=' ', const bool is_symmetric=false, const bool is_iterative=false) { if (!str) return false; const int l = (int)std::strlen(str); int p, q; if (is_symmetric) for (p = 0, q = l-1; p<q && str[p]==delimiter && str[q]==delimiter; ) { --q; ++p; if (!is_iterative) break; } else { for (p = 0; p<l && str[p]==delimiter; ) { ++p; if (!is_iterative) break; } for (q = l-1; q>p && str[q]==delimiter; ) { --q; if (!is_iterative) break; } } const int n = q - p + 1; if (n!=l) { std::memmove(str,str+p,n); str[n] = 0; return true; } return false; } //! Replace escape sequences in C-strings by their binary ascii values. /** \param[in,out] str C-string to work with (modified at output). **/ inline void strescape(char *const str) { #define cimg_strescape(ci,co) case ci: *nd = co; ++ns; break; static unsigned int val = 0; for (char *ns = str, *nd = str; *ns || (bool)(*nd=0); ++nd) if (*ns=='\\') switch (*(++ns)) { cimg_strescape('n','\n'); cimg_strescape('t','\t'); cimg_strescape('v','\v'); cimg_strescape('b','\b'); cimg_strescape('r','\r'); cimg_strescape('f','\f'); cimg_strescape('a','\a'); cimg_strescape('\\','\\'); cimg_strescape('\?','\?'); cimg_strescape('\'','\''); cimg_strescape('\"','\"'); case 0 : *nd = 0; break; case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : std::sscanf(ns,"%o",&val); while (*ns>='0' && *ns<='7') ++ns; *nd = val; break; case 'x': std::sscanf(++ns,"%x",&val); while ((*ns>='0' && *ns<='7') || (*ns>='a' && *ns<='f') || (*ns>='A' && *ns<='F')) ++ns; *nd = val; break; default : *nd = *(ns++); } else *nd = *(ns++); } // Return a temporary string describing the size of a memory buffer. inline const char *strbuffersize(const unsigned long size) { static char res[256] = { 0 }; if (size<1024LU) cimg_snprintf(res,sizeof(res),"%lu byte%s",size,size>1?"s":""); else if (size<1024*1024LU) { const float nsize = size/1024.0f; cimg_snprintf(res,sizeof(res),"%.1f Kio",nsize); } else if (size<1024*1024*1024LU) { const float nsize = size/(1024*1024.0f); cimg_snprintf(res,sizeof(res),"%.1f Mio",nsize); } else { const float nsize = size/(1024*1024*1024.0f); cimg_snprintf(res,sizeof(res),"%.1f Gio",nsize); } return res; } //! Return the basename of a filename. inline const char* basename(const char *const str) { const char *p = 0; for (const char *np = str; np>=str && (p=np); np = std::strchr(np,cimg_file_separator)+1) {} return p; } // Return a random filename. inline const char* filenamerand() { static char randomid[9] = { 0,0,0,0,0,0,0,0,0 }; cimg::srand(); for (unsigned int k = 0; k<8; ++k) { const int v = (int)std::rand()%3; randomid[k] = (char)(v==0?('0'+(std::rand()%10)):(v==1?('a'+(std::rand()%26)):('A'+(std::rand()%26)))); } return randomid; } // Convert filename as a Windows-style filename (short path name). inline void winformat_string(char *const str) { if (str && *str) { #if cimg_OS==2 char *const nstr = new char[MAX_PATH]; if (GetShortPathNameA(str,nstr,MAX_PATH)) std::strcpy(str,nstr); #endif } } //! Open a file. /** \param path Path of the filename to open. \param mode C-string describing the opening mode. \return Opened file. \note Same as <tt>std::fopen()</tt> but throw a \c CImgIOException when the specified file cannot be opened, instead of returning \c 0. **/ inline std::FILE *fopen(const char *const path, const char *const mode) { if (!path) throw CImgArgumentException("cimg::fopen(): Specified file path is (null)."); if (!mode) throw CImgArgumentException("cimg::fopen(): File '%s', specified mode is (null).", path); std::FILE *res = 0; if (*path=='-' && (!path[1] || path[1]=='.')) { res = (*mode=='r')?stdin:stdout; #if cimg_OS==2 if (*mode && mode[1]=='b') { // Force stdin/stdout to be in binary mode. if (_setmode(_fileno(res),0x8000)==-1) res = 0; } #endif } else res = std::fopen(path,mode); if (!res) throw CImgIOException("cimg::fopen(): Failed to open file '%s' with mode '%s'.", path,mode); return res; } //! Close a file. /** \param file File to close. \return \c 0 if file has been closed properly, something else otherwise. \note Same as <tt>std::fclose()</tt> but display a warning message if the file has not been closed properly. **/ inline int fclose(std::FILE *file) { if (!file) warn("cimg::fclose(): Specified file is (null)."); if (!file || file==stdin || file==stdout) return 0; const int errn = std::fclose(file); if (errn!=0) warn("cimg::fclose(): Error code %d returned during file closing.", errn); return errn; } //! Get/set path to store temporary files. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path where temporary files can be saved. **/ inline const char* temporary_path(const char *const user_path=0, const bool reinit_path=false) { #define _cimg_test_temporary_path(p) \ if (!path_found) { \ cimg_snprintf(st_path,1024,"%s",p); \ cimg_snprintf(tmp,sizeof(tmp),"%s%c%s",st_path,cimg_file_separator,filetmp); \ if ((file=std::fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } \ } static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; char tmp[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file = 0; cimg_snprintf(filetmp,sizeof(filetmp),"%s.tmp",cimg::filenamerand()); char *tmpPath = std::getenv("TMP"); if (!tmpPath) { tmpPath = std::getenv("TEMP"); winformat_string(tmpPath); } if (tmpPath) _cimg_test_temporary_path(tmpPath); #if cimg_OS==2 _cimg_test_temporary_path("C:\\WINNT\\Temp"); _cimg_test_temporary_path("C:\\WINDOWS\\Temp"); _cimg_test_temporary_path("C:\\Temp"); _cimg_test_temporary_path("C:"); _cimg_test_temporary_path("D:\\WINNT\\Temp"); _cimg_test_temporary_path("D:\\WINDOWS\\Temp"); _cimg_test_temporary_path("D:\\Temp"); _cimg_test_temporary_path("D:"); #else _cimg_test_temporary_path("/tmp"); _cimg_test_temporary_path("/var/tmp"); #endif if (!path_found) { *st_path = 0; std::strncpy(tmp,filetmp,sizeof(tmp)-1); if ((file=std::fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } } if (!path_found) throw CImgIOException("cimg::temporary_path(): Failed to locate path for writing temporary files.\n"); } return st_path; } //! Get/set path to the <i>Program Files/</i> directory (Windows only). /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the program files. **/ #if cimg_OS==2 inline const char* programfiles_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[MAX_PATH]; std::memset(st_path,0,MAX_PATH); // Note: in the following line, 0x26 = CSIDL_PROGRAM_FILES (not defined on every compiler). #if !defined(__INTEL_COMPILER) if (!SHGetSpecialFolderPathA(0,st_path,0x0026,false)) { const char *const pfPath = std::getenv("PROGRAMFILES"); if (pfPath) std::strncpy(st_path,pfPath,MAX_PATH-1); else std::strcpy(st_path,"C:\\PROGRA~1"); } #else std::strcpy(st_path,"C:\\PROGRA~1"); #endif } return st_path; } #endif //! Get/set path to the ImageMagick's \c convert binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c convert binary. **/ inline const char* imagemagick_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(st_path,".\\convert.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%.2d-\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%d-Q\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%d\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\IMAGEM~1.%d\\VISUA~1\\BIN\\convert.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%.2d-\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%d-Q\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%d\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\IMAGEM~1.%d\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%.2d-\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%d-Q\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%d\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%.2d-\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%d-Q\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\IMAGEM~1.%d\\VISUA~1\\BIN\\convert.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"convert.exe"); #else if (!path_found) { std::strcpy(st_path,"./convert"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"convert"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the GraphicsMagick's \c gm binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gm binary. **/ inline const char* graphicsmagick_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(st_path,".\\gm.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%.2d-\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%d-Q\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%d\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"%s\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",pf_path,k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%d\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"C:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%.2d-\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%d-Q\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%d\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=10 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 9; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } for (int k = 32; k>=0 && !path_found; --k) { cimg_snprintf(st_path,sizeof(st_path),"D:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gm.exe"); #else if (!path_found) { std::strcpy(st_path,"./gm"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gm"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the XMedcon's \c medcon binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c medcon binary. **/ inline const char* medcon_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 const char *const pf_path = programfiles_path(); if (!path_found) { std::strcpy(st_path,".\\medcon.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(st_path,sizeof(st_path),"%s\\XMedCon\\bin\\medcon.bat",pf_path); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) { cimg_snprintf(st_path,sizeof(st_path),"%s\\XMedCon\\bin\\medcon.exe",pf_path); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"medcon.exe"); #else if (!path_found) { std::strcpy(st_path,"./medcon"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"medcon"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the FFMPEG's \c ffmpeg binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c ffmpeg binary. **/ inline const char *ffmpeg_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\ffmpeg.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"ffmpeg.exe"); #else if (!path_found) { std::strcpy(st_path,"./ffmpeg"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"ffmpeg"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the \c gzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gzip binary. **/ inline const char *gzip_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\gzip.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gzip.exe"); #else if (!path_found) { std::strcpy(st_path,"./gzip"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gzip"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the \c gzip binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c gunzip binary. **/ inline const char *gunzip_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\gunzip.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gunzip.exe"); #else if (!path_found) { std::strcpy(st_path,"./gunzip"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"gunzip"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the \c dcraw binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c dcraw binary. **/ inline const char *dcraw_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\dcraw.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"dcraw.exe"); #else if (!path_found) { std::strcpy(st_path,"./dcraw"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"dcraw"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the \c wget binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c wget binary. **/ inline const char *wget_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\wget.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"wget.exe"); #else if (!path_found) { std::strcpy(st_path,"./wget"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"wget"); #endif winformat_string(st_path); } return st_path; } //! Get/set path to the \c curl binary. /** \param user_path Specified path, or \c 0 to get the path currently used. \param reinit_path Force path to be recalculated (may take some time). \return Path containing the \c curl binary. **/ inline const char *curl_path(const char *const user_path=0, const bool reinit_path=false) { static char *st_path = 0; if (reinit_path) { delete[] st_path; st_path = 0; } if (user_path) { if (!st_path) st_path = new char[1024]; std::memset(st_path,0,1024); std::strncpy(st_path,user_path,1023); } else if (!st_path) { st_path = new char[1024]; std::memset(st_path,0,1024); bool path_found = false; std::FILE *file = 0; #if cimg_OS==2 if (!path_found) { std::strcpy(st_path,".\\curl.exe"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"curl.exe"); #else if (!path_found) { std::strcpy(st_path,"./curl"); if ((file=std::fopen(st_path,"r"))!=0) { cimg::fclose(file); path_found = true; } } if (!path_found) std::strcpy(st_path,"curl"); #endif winformat_string(st_path); } return st_path; } //! Split filename into two C-strings \c body and \c extension. inline const char *split_filename(const char *const filename, char *const body=0) { if (!filename) { if (body) *body = 0; return 0; } const char *p = 0; for (const char *np = filename; np>=filename && (p=np); np = std::strchr(np,'.')+1) {} if (p==filename) { if (body) std::strcpy(body,filename); return filename + std::strlen(filename); } const unsigned int l = (unsigned int)(p - filename - 1); if (body) { std::memcpy(body,filename,l); body[l] = 0; } return p; } //! Generate a numbered version of a filename. inline char* number_filename(const char *const filename, const int number, const unsigned int n, char *const str) { if (!filename) { if (str) *str = 0; return 0; } char format[1024] = { 0 }, body[1024] = { 0 }; const char *const ext = cimg::split_filename(filename,body); if (n>0) cimg_snprintf(format,sizeof(format),"%s_%%.%ud.%s",body,n,ext); else cimg_snprintf(format,sizeof(format),"%s_%%d.%s",body,ext); std::sprintf(str,format,number); return str; } //! Try to guess format from an image file. /** \param file Input file (can be \c 0 if \c filename is set). \param filename Filename, as a C-string (can be \c 0 if \c file is set). \return C-string containing the guessed file format, or \c 0 if nothing has been guessed. **/ inline const char *file_type(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException("cimg::file_type(): Specified filename is (null)."); static const char *const _pnm = "pnm", *const _pfm = "pfm", *const _bmp = "bmp", *const _gif = "gif", *const _jpg = "jpg", *const _off = "off", *const _pan = "pan", *const _png = "png", *const _tif = "tif", *const _inr = "inr", *const _dcm = "dcm"; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); const char *f_type = 0, *head; char header[2048] = { 0 }, item[1024] = { 0 }; const unsigned char *const uheader = (unsigned char*)header; int err; char cerr; const unsigned int siz = (unsigned int)std::fread(header,2048,1,nfile); // Read first 2048 bytes. if (!file) cimg::fclose(nfile); if (!std::strncmp(header,"OFF\n",4)) f_type = _off; // Check for OFF format. else if (!std::strncmp(header,"#INRIMAGE",9)) f_type = _inr; // Check for INRIMAGE format. else if (!std::strncmp(header,"PANDORE",7)) f_type = _pan; // Check for PANDORE format. else if (!std::strncmp(header+128,"DICM",4)) f_type = _dcm; // Check for DICOM format. else if (uheader[0]==0xFF && uheader[1]==0xD8 && uheader[2]==0xFF) f_type = _jpg; // Check for JPEG format. else if (header[0]=='B' && header[1]=='M') f_type = _bmp; // Check for BMP format. else if (header[0]=='G' && header[1]=='I' && header[2]=='F' && header[3]=='8' && header[5]=='a' && // Check for GIF format. (header[4]=='7' || header[4]=='9')) f_type = _gif; else if (uheader[0]==0x89 && uheader[1]==0x50 && uheader[2]==0x4E && uheader[3]==0x47 && // Check for PNG format. uheader[4]==0x0D && uheader[5]==0x0A && uheader[6]==0x1A && uheader[7]==0x0A) f_type = _png; else if ((uheader[0]==0x49 && uheader[1]==0x49) || (uheader[0]==0x4D && uheader[1]==0x4D)) f_type = _tif; // Check for TIFF format. else { // Check for PNM or PFM format. head = header; while (head<header+siz && (err=std::sscanf(head,"%1023[^\n]",item))!=EOF && (*item=='#' || !err)) head+=1+(err?std::strlen(item):0); if (std::sscanf(item," P%d",&err)==1) f_type = _pnm; else if (std::sscanf(item," P%c",&cerr)==1 && (cerr=='f' || cerr=='F')) f_type = _pfm; } return f_type; } //! Read data from file. /** \param[out] ptr Pointer to memory buffer that will contain the binary data read from file. \param nmemb Number of elements to read. \param stream File to read data from. \return Number of read elements. \note Same as <tt>std::fread()</tt> but may display warning message if all elements could not be read. **/ template<typename T> inline int fread(T *const ptr, const unsigned long nmemb, std::FILE *stream) { if (!ptr || nmemb<=0 || !stream) throw CImgArgumentException("cimg::fread(): Invalid reading request of %u %s%s from file %p to buffer %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",stream,ptr); const unsigned long wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); unsigned long to_read = nmemb, al_read = 0, l_to_read = 0, l_al_read = 0; do { l_to_read = (to_read*sizeof(T))<wlimitT?to_read:wlimit; l_al_read = (unsigned long)std::fread((void*)(ptr+al_read),sizeof(T),l_to_read,stream); al_read+=l_al_read; to_read-=l_al_read; } while (l_to_read==l_al_read && to_read>0); if (to_read>0) warn("cimg::fread(): Only %u/%u elements could be read from file.", al_read,nmemb); return al_read; } //! Write data to file. /** \param ptr Pointer to memory buffer containing the binary data to write on file. \param nmemb Number of elements to write. \param[out] stream File to write data on. \return Number of written elements. \note Similar to <tt>std::fwrite</tt> but may display warning messages if all elements could not be written. **/ template<typename T> inline int fwrite(const T *ptr, const unsigned long nmemb, std::FILE *stream) { if (!ptr || !stream) throw CImgArgumentException("cimg::fwrite(): Invalid writing request of %u %s%s from buffer %p to file %p.", nmemb,cimg::type<T>::string(),nmemb>1?"s":"",ptr,stream); if (nmemb<=0) return 0; const unsigned long wlimitT = 63*1024*1024, wlimit = wlimitT/sizeof(T); unsigned long to_write = nmemb, al_write = 0, l_to_write = 0, l_al_write = 0; do { l_to_write = (to_write*sizeof(T))<wlimitT?to_write:wlimit; l_al_write = (unsigned long)std::fwrite((void*)(ptr+al_write),sizeof(T),l_to_write,stream); al_write+=l_al_write; to_write-=l_al_write; } while (l_to_write==l_al_write && to_write>0); if (to_write>0) warn("cimg::fwrite(): Only %u/%u elements could be written in file.", al_write,nmemb); return al_write; } //! Load file from network as a local temporary file. /** \param filename Filename, as a C-string. \param[out] filename_local C-string containing the path to a local copy of \c filename. \return Value of \c filename_local. \note Use external binaries \c wget or \c curl to perform. You must have one of these tools installed to be able to use this function. **/ inline char *load_network_external(const char *const filename, char *const filename_local) { if (!filename) throw CImgArgumentException("cimg::load_network_external(): Specified filename is (null)."); if (!filename_local) throw CImgArgumentException("cimg::load_network_external(): Specified destination string is (null)."); const char *const _ext = cimg::split_filename(filename), *const ext = (*_ext && _ext>filename)?_ext-1:_ext; char command[1024] = { 0 }; std::FILE *file = 0; *filename_local = 0; do { cimg_snprintf(filename_local,512,"%s%c%s%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); if ((file=std::fopen(filename_local,"rb"))!=0) cimg::fclose(file); } while (file); // Try with 'curl' first. cimg_snprintf(command,sizeof(command),"%s -f --silent --compressed -o \"%s\" \"%s\"",cimg::curl_path(),filename_local,filename); cimg::system(command); if (!(file = std::fopen(filename_local,"rb"))) { // Try with 'wget' else. cimg_snprintf(command,sizeof(command),"%s -q -r -l 0 --no-cache -O \"%s\" \"%s\"",cimg::wget_path(),filename_local,filename); cimg::system(command); if (!(file = std::fopen(filename_local,"rb"))) throw CImgIOException("cimg::load_network_external(): Failed to load file '%s' with external tools 'wget' or 'curl'.",filename); cimg::fclose(file); // Try gunzip it. cimg_snprintf(command,sizeof(command),"%s.gz",filename_local); std::rename(filename_local,command); cimg_snprintf(command,sizeof(command),"%s --quiet %s.gz",gunzip_path(),filename_local); cimg::system(command); file = std::fopen(filename_local,"rb"); if (!file) { cimg_snprintf(command,sizeof(command),"%s.gz",filename_local); std::rename(command,filename_local); file = std::fopen(filename_local,"rb"); } } std::fseek(file,0,SEEK_END); // Check if file size is 0. if (std::ftell(file)<=0) throw CImgIOException("cimg::load_network_external(): Failed to load file '%s' with external commands 'wget' or 'curl'.",filename); cimg::fclose(file); return filename_local; } //! Return options specified on the command line. inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage, const bool reset_static) { static bool first = true, visu = false; if (reset_static) { first = true; return 0; } const char *res = 0; if (first) { first = false; visu = cimg::option("-h",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("-help",argc,argv,(char*)0,(char*)0,false)!=0; visu |= cimg::option("--help",argc,argv,(char*)0,(char*)0,false)!=0; } if (!name && visu) { if (usage) { std::fprintf(cimg::output(),"\n %s%s%s",cimg::t_red,cimg::basename(argv[0]),cimg::t_normal); std::fprintf(cimg::output(),": %s",usage); std::fprintf(cimg::output()," (%s, %s)\n\n",__DATE__,__TIME__); } if (defaut) std::fprintf(cimg::output(),"%s\n",defaut); } if (name) { if (argc>0) { int k = 0; while (k<argc && std::strcmp(argv[k],name)) ++k; res = (k++==argc?defaut:(k==argc?argv[--k]:argv[k])); } else res = defaut; if (visu && usage) std::fprintf(cimg::output()," %s%-16s%s %-24s %s%s%s\n", cimg::t_bold,name,cimg::t_normal,res?res:"0",cimg::t_green,usage,cimg::t_normal); } return res; } inline const char* option(const char *const name, const int argc, const char *const *const argv, const char *const defaut, const char *const usage=0) { return option(name,argc,argv,defaut,usage,false); } inline bool option(const char *const name, const int argc, const char *const *const argv, const bool defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const bool res = s?(cimg::strcasecmp(s,"false") && cimg::strcasecmp(s,"off") && cimg::strcasecmp(s,"0")):defaut; cimg::option(name,0,0,res?"true":"false",usage); return res; } inline int option(const char *const name, const int argc, const char *const *const argv, const int defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const int res = s?std::atoi(s):defaut; char tmp[256] = { 0 }; cimg_snprintf(tmp,sizeof(tmp),"%d",res); cimg::option(name,0,0,tmp,usage); return res; } inline char option(const char *const name, const int argc, const char *const *const argv, const char defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const char res = s?*s:defaut; char tmp[8] = { 0 }; *tmp = res; cimg::option(name,0,0,tmp,usage); return res; } inline float option(const char *const name, const int argc, const char *const *const argv, const float defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const float res = s?(float)cimg::atof(s):defaut; char tmp[256] = { 0 }; cimg_snprintf(tmp,sizeof(tmp),"%g",res); cimg::option(name,0,0,tmp,usage); return res; } inline double option(const char *const name, const int argc, const char *const *const argv, const double defaut, const char *const usage=0) { const char *const s = cimg::option(name,argc,argv,(char*)0); const double res = s?cimg::atof(s):defaut; char tmp[256] = { 0 }; cimg_snprintf(tmp,sizeof(tmp),"%g",res); cimg::option(name,0,0,tmp,usage); return res; } inline const char* argument(const unsigned int nb, const int argc, const char *const *const argv, const unsigned int nb_singles=0, ...) { for (int k = 1, pos = 0; k<argc;) { const char *const item = argv[k]; bool option = (*item=='-'), single_option = false; if (option) { va_list ap; va_start(ap,nb_singles); for (unsigned int i = 0; i<nb_singles; ++i) if (!cimg::strcasecmp(item,va_arg(ap,char*))) { single_option = true; break; } va_end(ap); } if (option) { ++k; if (!single_option) ++k; } else { if (pos++==(int)nb) return item; else ++k; } } return 0; } //! Print informations about \CImg environement variables. /** \note Output is done on the default output stream. **/ inline void info() { char tmp[1024] = { 0 }; std::fprintf(cimg::output(),"\n %s%sCImg Library %u.%u.%u%s, compiled %s ( %s ) with the following flags:\n\n", cimg::t_red,cimg::t_bold,cimg_version/100,(cimg_version/10)%10,cimg_version%10, cimg::t_normal,__DATE__,__TIME__); std::fprintf(cimg::output()," > Operating System: %s%-13s%s %s('cimg_OS'=%d)%s\n", cimg::t_bold, cimg_OS==1?"Unix":(cimg_OS==2?"Windows":"Unknow"), cimg::t_normal,cimg::t_green, cimg_OS, cimg::t_normal); std::fprintf(cimg::output()," > CPU endianness: %s%s Endian%s\n", cimg::t_bold, cimg::endianness()?"Big":"Little", cimg::t_normal); std::fprintf(cimg::output()," > Verbosity mode: %s%-13s%s %s('cimg_verbosity'=%d)%s\n", cimg::t_bold, cimg_verbosity==0?"Quiet":(cimg_verbosity==1?"Console":(cimg_verbosity==2?"Dialog":(cimg_verbosity==3?"Console+Warnings":"Dialog+Warnings"))), cimg::t_normal,cimg::t_green, cimg_verbosity, cimg::t_normal); std::fprintf(cimg::output()," > Stricts warnings: %s%-13s%s %s('cimg_strict_warnings' %s)%s\n", cimg::t_bold, #ifdef cimg_strict_warnings "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using VT100 messages: %s%-13s%s %s('cimg_use_vt100' %s)%s\n", cimg::t_bold, #ifdef cimg_use_vt100 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Display type: %s%-13s%s %s('cimg_display'=%d)%s\n", cimg::t_bold, cimg_display==0?"No display":cimg_display==1?"X11":cimg_display==2?"Windows GDI":"Unknown", cimg::t_normal,cimg::t_green, cimg_display, cimg::t_normal); #if cimg_display==1 std::fprintf(cimg::output()," > Using XShm for X11: %s%-13s%s %s('cimg_use_xshm' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xshm "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using XRand for X11: %s%-13s%s %s('cimg_use_xrandr' %s)%s\n", cimg::t_bold, #ifdef cimg_use_xrandr "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); #endif std::fprintf(cimg::output()," > Using OpenMP: %s%-13s%s %s('cimg_use_openmp' %s)%s\n", cimg::t_bold, #ifdef cimg_use_openmp "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using PNG library: %s%-13s%s %s('cimg_use_png' %s)%s\n", cimg::t_bold, #ifdef cimg_use_png "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using JPEG library: %s%-13s%s %s('cimg_use_jpeg' %s)%s\n", cimg::t_bold, #ifdef cimg_use_jpeg "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using TIFF library: %s%-13s%s %s('cimg_use_tiff' %s)%s\n", cimg::t_bold, #ifdef cimg_use_tiff "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using Magick++ library: %s%-13s%s %s('cimg_use_magick' %s)%s\n", cimg::t_bold, #ifdef cimg_use_magick "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using FFTW3 library: %s%-13s%s %s('cimg_use_fftw3' %s)%s\n", cimg::t_bold, #ifdef cimg_use_fftw3 "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); std::fprintf(cimg::output()," > Using LAPACK library: %s%-13s%s %s('cimg_use_lapack' %s)%s\n", cimg::t_bold, #ifdef cimg_use_lapack "Yes",cimg::t_normal,cimg::t_green,"defined", #else "No",cimg::t_normal,cimg::t_green,"undefined", #endif cimg::t_normal); cimg_snprintf(tmp,sizeof(tmp),"\"%.1020s\"",cimg::imagemagick_path()); std::fprintf(cimg::output()," > Path of ImageMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,sizeof(tmp),"\"%.1020s\"",cimg::graphicsmagick_path()); std::fprintf(cimg::output()," > Path of GraphicsMagick: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,sizeof(tmp),"\"%.1020s\"",cimg::medcon_path()); std::fprintf(cimg::output()," > Path of 'medcon': %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); cimg_snprintf(tmp,sizeof(tmp),"\"%.1020s\"",cimg::temporary_path()); std::fprintf(cimg::output()," > Temporary path: %s%-13s%s\n", cimg::t_bold, tmp, cimg::t_normal); std::fprintf(cimg::output(),"\n"); } // Declare LAPACK function signatures if LAPACK support is enabled. #ifdef cimg_use_lapack template<typename T> inline void getrf(int &N, T *lapA, int *IPIV, int &INFO) { dgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } inline void getrf(int &N, float *lapA, int *IPIV, int &INFO) { sgetrf_(&N,&N,lapA,&N,IPIV,&INFO); } template<typename T> inline void getri(int &N, T *lapA, int *IPIV, T* WORK, int &LWORK, int &INFO) { dgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } inline void getri(int &N, float *lapA, int *IPIV, float* WORK, int &LWORK, int &INFO) { sgetri_(&N,lapA,&N,IPIV,WORK,&LWORK,&INFO); } template<typename T> inline void gesvd(char &JOB, int &M, int &N, T *lapA, int &MN, T *lapS, T *lapU, T *lapV, T *WORK, int &LWORK, int &INFO) { dgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } inline void gesvd(char &JOB, int &M, int &N, float *lapA, int &MN, float *lapS, float *lapU, float *lapV, float *WORK, int &LWORK, int &INFO) { sgesvd_(&JOB,&JOB,&M,&N,lapA,&MN,lapS,lapU,&M,lapV,&N,WORK,&LWORK,&INFO); } template<typename T> inline void getrs(char &TRANS, int &N, T *lapA, int *IPIV, T *lapB, int &INFO) { int one = 1; dgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } inline void getrs(char &TRANS, int &N, float *lapA, int *IPIV, float *lapB, int &INFO) { int one = 1; sgetrs_(&TRANS,&N,&one,lapA,&N,IPIV,lapB,&N,&INFO); } template<typename T> inline void syev(char &JOB, char &UPLO, int &N, T *lapA, T *lapW, T *WORK, int &LWORK, int &INFO) { dsyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } inline void syev(char &JOB, char &UPLO, int &N, float *lapA, float *lapW, float *WORK, int &LWORK, int &INFO) { ssyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO); } template<typename T> inline void sgels(char & TRANS, int &M, int &N, int &NRHS, T* lapA, int &LDA, T* lapB, int &LDB, T* WORK, int &LWORK, int &INFO){ dgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } inline void sgels(char & TRANS, int &M, int &N, int &NRHS, float* lapA, int &LDA, float* lapB, int &LDB, float* WORK, int &LWORK, int &INFO){ sgels_(&TRANS, &M, &N, &NRHS, lapA, &LDA, lapB, &LDB, WORK, &LWORK, &INFO); } #endif // End of the 'cimg' namespace } /*------------------------------------------------ # # # Definition of mathematical operators and # external functions. # # -------------------------------------------------*/ #define _cimg_create_ext_operators(typ) \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator+(const typ val, const CImg<T>& img) { \ return img + val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator-(const typ val, const CImg<T>& img) { \ typedef typename cimg::superset<T,typ>::type Tt; \ return CImg<Tt>(img._width,img._height,img._depth,img._spectrum,val)-=img; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator*(const typ val, const CImg<T>& img) { \ return img*val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator/(const typ val, const CImg<T>& img) { \ return val*img.get_invert(); \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator&(const typ val, const CImg<T>& img) { \ return img & val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator|(const typ val, const CImg<T>& img) { \ return img | val; \ } \ template<typename T> \ inline CImg<typename cimg::superset<T,typ>::type> operator^(const typ val, const CImg<T>& img) { \ return img ^ val; \ } \ template<typename T> \ inline bool operator==(const typ val, const CImg<T>& img) { \ return img == val; \ } \ template<typename T> \ inline bool operator!=(const typ val, const CImg<T>& img) { \ return img != val; \ } _cimg_create_ext_operators(bool) _cimg_create_ext_operators(unsigned char) _cimg_create_ext_operators(char) _cimg_create_ext_operators(signed char) _cimg_create_ext_operators(unsigned short) _cimg_create_ext_operators(short) _cimg_create_ext_operators(unsigned int) _cimg_create_ext_operators(int) _cimg_create_ext_operators(unsigned long) _cimg_create_ext_operators(long) _cimg_create_ext_operators(float) _cimg_create_ext_operators(double) template<typename T> inline CImg<_cimg_Tfloat> operator+(const char *const expression, const CImg<T>& img) { return img + expression; } template<typename T> inline CImg<_cimg_Tfloat> operator-(const char *const expression, const CImg<T>& img) { return CImg<_cimg_Tfloat>(img._width,img._height,img._depth,img._spectrum,expression,true)-=img; } template<typename T> inline CImg<_cimg_Tfloat> operator*(const char *const expression, const CImg<T>& img) { return img*expression; } template<typename T> inline CImg<_cimg_Tfloat> operator/(const char *const expression, const CImg<T>& img) { return expression*img.get_invert(); } template<typename T> inline CImg<T> operator&(const char *const expression, const CImg<T>& img) { return img & expression; } template<typename T> inline CImg<T> operator|(const char *const expression, const CImg<T>& img) { return img | expression; } template<typename T> inline CImg<T> operator^(const char *const expression, const CImg<T>& img) { return img ^ expression; } template<typename T> inline bool operator==(const char *const expression, const CImg<T>& img) { return img == expression; } template<typename T> inline bool operator!=(const char *const expression, const CImg<T>& img) { return img != expression; } template<typename T> inline CImg<_cimg_Tfloat> sqr(const CImg<T>& instance) { return instance.get_sqr(); } template<typename T> inline CImg<_cimg_Tfloat> sqrt(const CImg<T>& instance) { return instance.get_sqrt(); } template<typename T> inline CImg<_cimg_Tfloat> exp(const CImg<T>& instance) { return instance.get_exp(); } template<typename T> inline CImg<_cimg_Tfloat> log(const CImg<T>& instance) { return instance.get_log(); } template<typename T> inline CImg<_cimg_Tfloat> log2(const CImg<T>& instance) { return instance.get_log2(); } template<typename T> inline CImg<_cimg_Tfloat> log10(const CImg<T>& instance) { return instance.get_log10(); } template<typename T> inline CImg<_cimg_Tfloat> abs(const CImg<T>& instance) { return instance.get_abs(); } template<typename T> inline CImg<_cimg_Tfloat> sign(const CImg<T>& instance) { return instance.get_sign(); } template<typename T> inline CImg<_cimg_Tfloat> cos(const CImg<T>& instance) { return instance.get_cos(); } template<typename T> inline CImg<_cimg_Tfloat> sin(const CImg<T>& instance) { return instance.get_sin(); } template<typename T> inline CImg<_cimg_Tfloat> sinc(const CImg<T>& instance) { return instance.get_sinc(); } template<typename T> inline CImg<_cimg_Tfloat> tan(const CImg<T>& instance) { return instance.get_tan(); } template<typename T> inline CImg<_cimg_Tfloat> acos(const CImg<T>& instance) { return instance.get_acos(); } template<typename T> inline CImg<_cimg_Tfloat> asin(const CImg<T>& instance) { return instance.get_asin(); } template<typename T> inline CImg<_cimg_Tfloat> atan(const CImg<T>& instance) { return instance.get_atan(); } template<typename T> inline CImg<_cimg_Tfloat> cosh(const CImg<T>& instance) { return instance.get_cosh(); } template<typename T> inline CImg<_cimg_Tfloat> sinh(const CImg<T>& instance) { return instance.get_sinh(); } template<typename T> inline CImg<_cimg_Tfloat> tanh(const CImg<T>& instance) { return instance.get_tanh(); } template<typename T> inline CImg<T> transpose(const CImg<T>& instance) { return instance.get_transpose(); } template<typename T> inline CImg<_cimg_Tfloat> invert(const CImg<T>& instance) { return instance.get_invert(); } template<typename T> inline CImg<_cimg_Tfloat> pseudoinvert(const CImg<T>& instance) { return instance.get_pseudoinvert(); } /*----------------------------------- # # Define the CImgDisplay structure # ----------------------------------*/ //! Allow to create windows, display images on them and manage user events (keyboard, mouse and windows events). /** CImgDisplay methods rely on a low-level graphic library to perform: it can be either \b X-Window (X11, for Unix-based systems) or \b GDI32 (for Windows-based systems). If both libraries are missing, CImgDisplay will not be able to display images on screen, and will enter a minimal mode where warning messages will be outputed each time the program is trying to call one of the CImgDisplay method. The configuration variable \c cimg_display tells about the graphic library used. It is set automatically by \CImg when one of these graphic libraries has been detected. But, you can override its value if necessary. Valid choices are: - 0: Disable display capabilities. - 1: Use \b X-Window (X11) library. - 2: Use \b GDI32 library. Remember to link your program against \b X11 or \b GDI32 libraries if you use CImgDisplay. **/ struct CImgDisplay { unsigned long _timer, _fps_frames, _fps_timer; unsigned int _width, _height, _normalization; float _fps_fps, _min, _max; bool _is_fullscreen; char *_title; volatile unsigned int _window_width, _window_height, _button, _keys[128], _released_keys[128]; volatile int _window_x, _window_y, _mouse_x, _mouse_y, _wheel; volatile bool _is_closed, _is_resized, _is_moved, _is_event, _is_keyESC, _is_keyF1, _is_keyF2, _is_keyF3, _is_keyF4, _is_keyF5, _is_keyF6, _is_keyF7, _is_keyF8, _is_keyF9, _is_keyF10, _is_keyF11, _is_keyF12, _is_keyPAUSE, _is_key1, _is_key2, _is_key3, _is_key4, _is_key5, _is_key6, _is_key7, _is_key8, _is_key9, _is_key0, _is_keyBACKSPACE, _is_keyINSERT, _is_keyHOME, _is_keyPAGEUP, _is_keyTAB, _is_keyQ, _is_keyW, _is_keyE, _is_keyR, _is_keyT, _is_keyY, _is_keyU, _is_keyI, _is_keyO, _is_keyP, _is_keyDELETE, _is_keyEND, _is_keyPAGEDOWN, _is_keyCAPSLOCK, _is_keyA, _is_keyS, _is_keyD, _is_keyF, _is_keyG, _is_keyH, _is_keyJ, _is_keyK, _is_keyL, _is_keyENTER, _is_keySHIFTLEFT, _is_keyZ, _is_keyX, _is_keyC, _is_keyV, _is_keyB, _is_keyN, _is_keyM, _is_keySHIFTRIGHT, _is_keyARROWUP, _is_keyCTRLLEFT, _is_keyAPPLEFT, _is_keyALT, _is_keySPACE, _is_keyALTGR, _is_keyAPPRIGHT, _is_keyMENU, _is_keyCTRLRIGHT, _is_keyARROWLEFT, _is_keyARROWDOWN, _is_keyARROWRIGHT, _is_keyPAD0, _is_keyPAD1, _is_keyPAD2, _is_keyPAD3, _is_keyPAD4, _is_keyPAD5, _is_keyPAD6, _is_keyPAD7, _is_keyPAD8, _is_keyPAD9, _is_keyPADADD, _is_keyPADSUB, _is_keyPADMUL, _is_keyPADDIV; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimgdisplay_plugin #include cimgdisplay_plugin #endif #ifdef cimgdisplay_plugin1 #include cimgdisplay_plugin1 #endif #ifdef cimgdisplay_plugin2 #include cimgdisplay_plugin2 #endif #ifdef cimgdisplay_plugin3 #include cimgdisplay_plugin3 #endif #ifdef cimgdisplay_plugin4 #include cimgdisplay_plugin4 #endif #ifdef cimgdisplay_plugin5 #include cimgdisplay_plugin5 #endif #ifdef cimgdisplay_plugin6 #include cimgdisplay_plugin6 #endif #ifdef cimgdisplay_plugin7 #include cimgdisplay_plugin7 #endif #ifdef cimgdisplay_plugin8 #include cimgdisplay_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** \note If the associated window is visible on the screen, it is closed by the call to the destructor. **/ ~CImgDisplay() { assign(); } //! Construct an empty display. /** \note Constructing an empty CImgDisplay instance does not make a window appearing on the screen, until display of valid data is performed. \par Example \code CImgDisplay disp; // Does actually nothing. ... disp.display(img); // Construct new window and display image in it. \endcode **/ CImgDisplay(): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(); } //! Construct a display with specified dimensions. /** \param width Window width. \param height Window height. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note A black background is initially displayed on the associated window. **/ CImgDisplay(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(width,height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image. /** \param img Image used as a model to create the window. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note The pixels of the input image are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(img,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list. /** \param list The images list to display. \param title Window title. \param normalization Normalization type (<tt>0</tt>=none, <tt>1</tt>=always, <tt>2</tt>=once, <tt>3</tt>=pixel type-dependent, see normalization()). \param is_fullscreen Tells if fullscreen mode is enabled. \param is_closed Tells if associated window is initially visible or not. \note All images of the list, appended along the X-axis, are initially displayed on the associated window. **/ template<typename T> explicit CImgDisplay(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(list,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of an existing one. /** \param disp Display instance to copy. \note The pixel buffer of the input window is initially displayed on the associated window. **/ CImgDisplay(const CImgDisplay& disp): _width(0),_height(0),_normalization(0), _min(0),_max(0), _is_fullscreen(false), _title(0), _window_width(0),_window_height(0),_button(0), _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0), _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) { assign(disp); } #if cimg_display==0 static void _no_display_exception() { throw CImgDisplayException("CImgDisplay(): No display available."); } //! Destructor - Empty constructor \inplace. /** \note Replace the current instance by an empty display. **/ CImgDisplay& assign() { return flush(); } //! Construct a display with specified dimensions \inplace. /** **/ CImgDisplay& assign(const unsigned int width, const unsigned int height, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { cimg::unused(width,height,title,normalization,is_fullscreen,is_closed); _no_display_exception(); return assign(); } //! Construct a display from an image \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(img._width,img._height,title,normalization,is_fullscreen,is_closed); } //! Construct a display from an image list \inplace. /** **/ template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization=3, const bool is_fullscreen=false, const bool is_closed=false) { _no_display_exception(); return assign(list._width,list._width,title,normalization,is_fullscreen,is_closed); } //! Construct a display as a copy of another one \inplace. /** **/ CImgDisplay& assign(const CImgDisplay &disp) { _no_display_exception(); return assign(disp._width,disp._height); } #endif //! Return a reference to an empty display. /** \note Can be useful for writing function prototypes where one of the argument (of type CImgDisplay&) must have a default value. \par Example \code void foo(CImgDisplay& disp=CImgDisplay::empty()); \endcode **/ static CImgDisplay& empty() { static CImgDisplay _empty; return _empty.assign(); } #define cimg_fitscreen(dx,dy,dz) CImgDisplay::_fitscreen(dx,dy,dz,128,-85,false),CImgDisplay::_fitscreen(dx,dy,dz,128,-85,true) static unsigned int _fitscreen(const unsigned int dx, const unsigned int dy, const unsigned int dz, const int dmin, const int dmax,const bool return_y) { const unsigned int _nw = dx + (dz>1?dz:0), _nh = dy + (dz>1?dz:0); unsigned int nw = _nw?_nw:1, nh = _nh?_nh:1; const unsigned int sw = CImgDisplay::screen_width(), sh = CImgDisplay::screen_height(), mw = dmin<0?(unsigned int)(sw*-dmin/100):(unsigned int)dmin, mh = dmin<0?(unsigned int)(sh*-dmin/100):(unsigned int)dmin, Mw = dmax<0?(unsigned int)(sw*-dmax/100):(unsigned int)dmax, Mh = dmax<0?(unsigned int)(sh*-dmax/100):(unsigned int)dmax; if (nw<mw) { nh = nh*mw/nw; nh+=(nh==0?1:0); nw = mw; } if (nh<mh) { nw = nw*mh/nh; nw+=(nw==0?1:0); nh = mh; } if (nw>Mw) { nh = nh*Mw/nw; nh+=(nh==0?1:0); nw = Mw; } if (nh>Mh) { nw = nw*Mh/nh; nw+=(nw==0?1:0); nh = Mh; } if (nw<mw) nw = mw; if (nh<mh) nh = mh; return return_y?nh:nw; } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Display image on associated window. /** \note <tt>disp = img</tt> is equivalent to <tt>disp.display(img)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImg<t>& img) { return display(img); } //! Display list of images on associated window. /** \note <tt>disp = list</tt> is equivalent to <tt>disp.display(list)</tt>. **/ template<typename t> CImgDisplay& operator=(const CImgList<t>& list) { return display(list); } //! Construct a display as a copy of another one \inplace. /** \note Equivalent to assign(const CImgDisplay&). **/ CImgDisplay& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return \c false if display is empty, \c true otherwise. /** \note <tt>if (disp) { ... }</tt> is equivalent to <tt>if (!disp.is_empty()) { ... }</tt>. **/ operator bool() const { return !is_empty(); } //@} //------------------------------------------ // //! \name Instance Checking //@{ //------------------------------------------ //! Return \c true if display is empty, \c false otherwise. /** **/ bool is_empty() const { return !(_width && _height); } //! Return \c true if display is closed (i.e. not visible on the screen), \c false otherwise. /** \note - When a user physically closes the associated window, the display is set to closed. - A closed display is not destroyed. Its associated window can be show again on the screen using show(). **/ bool is_closed() const { return _is_closed; } //! Return \c true if associated window has been resized on the screen, \c false otherwise. /** **/ bool is_resized() const { return _is_resized; } //! Return \c true if associated window has been moved on the screen, \c false otherwise. /** **/ bool is_moved() const { return _is_moved; } //! Return \c true if any event has occured on the associated window, \c false otherwise. /** **/ bool is_event() const { return _is_event; } //! Return \c true if current display is in fullscreen mode, \c false otherwise. /** **/ bool is_fullscreen() const { return _is_fullscreen; } //! Return \c true if any key is being pressed on the associated window, \c false otherwise. /** \note The methods below do the same only for specific keys. **/ bool is_key() const { return _is_keyESC || _is_keyF1 || _is_keyF2 || _is_keyF3 || _is_keyF4 || _is_keyF5 || _is_keyF6 || _is_keyF7 || _is_keyF8 || _is_keyF9 || _is_keyF10 || _is_keyF11 || _is_keyF12 || _is_keyPAUSE || _is_key1 || _is_key2 || _is_key3 || _is_key4 || _is_key5 || _is_key6 || _is_key7 || _is_key8 || _is_key9 || _is_key0 || _is_keyBACKSPACE || _is_keyINSERT || _is_keyHOME || _is_keyPAGEUP || _is_keyTAB || _is_keyQ || _is_keyW || _is_keyE || _is_keyR || _is_keyT || _is_keyY || _is_keyU || _is_keyI || _is_keyO || _is_keyP || _is_keyDELETE || _is_keyEND || _is_keyPAGEDOWN || _is_keyCAPSLOCK || _is_keyA || _is_keyS || _is_keyD || _is_keyF || _is_keyG || _is_keyH || _is_keyJ || _is_keyK || _is_keyL || _is_keyENTER || _is_keySHIFTLEFT || _is_keyZ || _is_keyX || _is_keyC || _is_keyV || _is_keyB || _is_keyN || _is_keyM || _is_keySHIFTRIGHT || _is_keyARROWUP || _is_keyCTRLLEFT || _is_keyAPPLEFT || _is_keyALT || _is_keySPACE || _is_keyALTGR || _is_keyAPPRIGHT || _is_keyMENU || _is_keyCTRLRIGHT || _is_keyARROWLEFT || _is_keyARROWDOWN || _is_keyARROWRIGHT || _is_keyPAD0 || _is_keyPAD1 || _is_keyPAD2 || _is_keyPAD3 || _is_keyPAD4 || _is_keyPAD5 || _is_keyPAD6 || _is_keyPAD7 || _is_keyPAD8 || _is_keyPAD9 || _is_keyPADADD || _is_keyPADSUB || _is_keyPADMUL || _is_keyPADDIV; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode Keycode to test. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.key(cimg::keyTAB)) { ... } // Equivalent to 'if (disp.is_keyTAB())'. disp.wait(); } \endcode **/ bool is_key(const unsigned int keycode) const { #define _cimg_iskey_test(k) if (keycode==cimg::key##k) return _is_key##k; _cimg_iskey_test(ESC); _cimg_iskey_test(F1); _cimg_iskey_test(F2); _cimg_iskey_test(F3); _cimg_iskey_test(F4); _cimg_iskey_test(F5); _cimg_iskey_test(F6); _cimg_iskey_test(F7); _cimg_iskey_test(F8); _cimg_iskey_test(F9); _cimg_iskey_test(F10); _cimg_iskey_test(F11); _cimg_iskey_test(F12); _cimg_iskey_test(PAUSE); _cimg_iskey_test(1); _cimg_iskey_test(2); _cimg_iskey_test(3); _cimg_iskey_test(4); _cimg_iskey_test(5); _cimg_iskey_test(6); _cimg_iskey_test(7); _cimg_iskey_test(8); _cimg_iskey_test(9); _cimg_iskey_test(0); _cimg_iskey_test(BACKSPACE); _cimg_iskey_test(INSERT); _cimg_iskey_test(HOME); _cimg_iskey_test(PAGEUP); _cimg_iskey_test(TAB); _cimg_iskey_test(Q); _cimg_iskey_test(W); _cimg_iskey_test(E); _cimg_iskey_test(R); _cimg_iskey_test(T); _cimg_iskey_test(Y); _cimg_iskey_test(U); _cimg_iskey_test(I); _cimg_iskey_test(O); _cimg_iskey_test(P); _cimg_iskey_test(DELETE); _cimg_iskey_test(END); _cimg_iskey_test(PAGEDOWN); _cimg_iskey_test(CAPSLOCK); _cimg_iskey_test(A); _cimg_iskey_test(S); _cimg_iskey_test(D); _cimg_iskey_test(F); _cimg_iskey_test(G); _cimg_iskey_test(H); _cimg_iskey_test(J); _cimg_iskey_test(K); _cimg_iskey_test(L); _cimg_iskey_test(ENTER); _cimg_iskey_test(SHIFTLEFT); _cimg_iskey_test(Z); _cimg_iskey_test(X); _cimg_iskey_test(C); _cimg_iskey_test(V); _cimg_iskey_test(B); _cimg_iskey_test(N); _cimg_iskey_test(M); _cimg_iskey_test(SHIFTRIGHT); _cimg_iskey_test(ARROWUP); _cimg_iskey_test(CTRLLEFT); _cimg_iskey_test(APPLEFT); _cimg_iskey_test(ALT); _cimg_iskey_test(SPACE); _cimg_iskey_test(ALTGR); _cimg_iskey_test(APPRIGHT); _cimg_iskey_test(MENU); _cimg_iskey_test(CTRLRIGHT); _cimg_iskey_test(ARROWLEFT); _cimg_iskey_test(ARROWDOWN); _cimg_iskey_test(ARROWRIGHT); _cimg_iskey_test(PAD0); _cimg_iskey_test(PAD1); _cimg_iskey_test(PAD2); _cimg_iskey_test(PAD3); _cimg_iskey_test(PAD4); _cimg_iskey_test(PAD5); _cimg_iskey_test(PAD6); _cimg_iskey_test(PAD7); _cimg_iskey_test(PAD8); _cimg_iskey_test(PAD9); _cimg_iskey_test(PADADD); _cimg_iskey_test(PADSUB); _cimg_iskey_test(PADMUL); _cimg_iskey_test(PADDIV); return false; } //! Return \c true if key specified by given keycode is being pressed on the associated window, \c false otherwise. /** \param keycode C-string containing the keycode label of the key to test. \note Use it when the key you want to test can be dynamically set by the user. \par Example \code CImgDisplay disp(400,400); const char *const keycode = "TAB"; while (!disp.is_closed()) { if (disp.is_key(keycode)) { ... } // Equivalent to 'if (disp.is_keyTAB())'. disp.wait(); } \endcode **/ bool is_key(const char *const keycode) const { #define _cimg_iskey_test2(k) if (!cimg::strcasecmp(keycode,#k)) return _is_key##k; _cimg_iskey_test2(ESC); _cimg_iskey_test2(F1); _cimg_iskey_test2(F2); _cimg_iskey_test2(F3); _cimg_iskey_test2(F4); _cimg_iskey_test2(F5); _cimg_iskey_test2(F6); _cimg_iskey_test2(F7); _cimg_iskey_test2(F8); _cimg_iskey_test2(F9); _cimg_iskey_test2(F10); _cimg_iskey_test2(F11); _cimg_iskey_test2(F12); _cimg_iskey_test2(PAUSE); _cimg_iskey_test2(1); _cimg_iskey_test2(2); _cimg_iskey_test2(3); _cimg_iskey_test2(4); _cimg_iskey_test2(5); _cimg_iskey_test2(6); _cimg_iskey_test2(7); _cimg_iskey_test2(8); _cimg_iskey_test2(9); _cimg_iskey_test2(0); _cimg_iskey_test2(BACKSPACE); _cimg_iskey_test2(INSERT); _cimg_iskey_test2(HOME); _cimg_iskey_test2(PAGEUP); _cimg_iskey_test2(TAB); _cimg_iskey_test2(Q); _cimg_iskey_test2(W); _cimg_iskey_test2(E); _cimg_iskey_test2(R); _cimg_iskey_test2(T); _cimg_iskey_test2(Y); _cimg_iskey_test2(U); _cimg_iskey_test2(I); _cimg_iskey_test2(O); _cimg_iskey_test2(P); _cimg_iskey_test2(DELETE); _cimg_iskey_test2(END); _cimg_iskey_test2(PAGEDOWN); _cimg_iskey_test2(CAPSLOCK); _cimg_iskey_test2(A); _cimg_iskey_test2(S); _cimg_iskey_test2(D); _cimg_iskey_test2(F); _cimg_iskey_test2(G); _cimg_iskey_test2(H); _cimg_iskey_test2(J); _cimg_iskey_test2(K); _cimg_iskey_test2(L); _cimg_iskey_test2(ENTER); _cimg_iskey_test2(SHIFTLEFT); _cimg_iskey_test2(Z); _cimg_iskey_test2(X); _cimg_iskey_test2(C); _cimg_iskey_test2(V); _cimg_iskey_test2(B); _cimg_iskey_test2(N); _cimg_iskey_test2(M); _cimg_iskey_test2(SHIFTRIGHT); _cimg_iskey_test2(ARROWUP); _cimg_iskey_test2(CTRLLEFT); _cimg_iskey_test2(APPLEFT); _cimg_iskey_test2(ALT); _cimg_iskey_test2(SPACE); _cimg_iskey_test2(ALTGR); _cimg_iskey_test2(APPRIGHT); _cimg_iskey_test2(MENU); _cimg_iskey_test2(CTRLRIGHT); _cimg_iskey_test2(ARROWLEFT); _cimg_iskey_test2(ARROWDOWN); _cimg_iskey_test2(ARROWRIGHT); _cimg_iskey_test2(PAD0); _cimg_iskey_test2(PAD1); _cimg_iskey_test2(PAD2); _cimg_iskey_test2(PAD3); _cimg_iskey_test2(PAD4); _cimg_iskey_test2(PAD5); _cimg_iskey_test2(PAD6); _cimg_iskey_test2(PAD7); _cimg_iskey_test2(PAD8); _cimg_iskey_test2(PAD9); _cimg_iskey_test2(PADADD); _cimg_iskey_test2(PADSUB); _cimg_iskey_test2(PADMUL); _cimg_iskey_test2(PADDIV); return false; } //! Return \c true if specified key sequence has been typed on the associated window, \c false otherwise. /** \param keycodes_sequence Buffer of keycodes to test. \param length Number of keys in the \c keycodes_sequence buffer. \param remove_sequence Tells if the key sequence must be removed from the key history, if found. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code CImgDisplay disp(400,400); const unsigned int key_seq[] = { cimg::keyCTRLLEFT, cimg::keyD }; while (!disp.is_closed()) { if (disp.is_key_sequence(key_seq,2)) { ... } // Test for the 'CTRL+D' keyboard event. disp.wait(); } \endcode **/ bool is_key_sequence(const unsigned int *const keycodes_sequence, const unsigned int length, const bool remove_sequence=false) { if (keycodes_sequence && length) { const unsigned int *const ps_end = keycodes_sequence + length - 1, *const pk_end = (unsigned int*)_keys + 1 + sizeof(_keys)/sizeof(unsigned int) - length, k = *ps_end; for (unsigned int *pk = (unsigned int*)_keys; pk<pk_end; ) { if (*(pk++)==k) { bool res = true; const unsigned int *ps = ps_end, *pk2 = pk; for (unsigned int i = 1; i<length; ++i) res = (*(--ps)==*(pk2++)); if (res) { if (remove_sequence) std::memset((void*)(pk-1),0,sizeof(unsigned int)*length); return true; } } } } return false; } #define _cimg_iskey_def(k) \ bool is_key##k() const { \ return _is_key##k; \ } //! Return \c true if the \c ESC key is being pressed on the associated window, \c false otherwise. /** \note Similar methods exist for all keys managed by \CImg (see cimg::keyESC). **/ _cimg_iskey_def(ESC); _cimg_iskey_def(F1); _cimg_iskey_def(F2); _cimg_iskey_def(F3); _cimg_iskey_def(F4); _cimg_iskey_def(F5); _cimg_iskey_def(F6); _cimg_iskey_def(F7); _cimg_iskey_def(F8); _cimg_iskey_def(F9); _cimg_iskey_def(F10); _cimg_iskey_def(F11); _cimg_iskey_def(F12); _cimg_iskey_def(PAUSE); _cimg_iskey_def(1); _cimg_iskey_def(2); _cimg_iskey_def(3); _cimg_iskey_def(4); _cimg_iskey_def(5); _cimg_iskey_def(6); _cimg_iskey_def(7); _cimg_iskey_def(8); _cimg_iskey_def(9); _cimg_iskey_def(0); _cimg_iskey_def(BACKSPACE); _cimg_iskey_def(INSERT); _cimg_iskey_def(HOME); _cimg_iskey_def(PAGEUP); _cimg_iskey_def(TAB); _cimg_iskey_def(Q); _cimg_iskey_def(W); _cimg_iskey_def(E); _cimg_iskey_def(R); _cimg_iskey_def(T); _cimg_iskey_def(Y); _cimg_iskey_def(U); _cimg_iskey_def(I); _cimg_iskey_def(O); _cimg_iskey_def(P); _cimg_iskey_def(DELETE); _cimg_iskey_def(END); _cimg_iskey_def(PAGEDOWN); _cimg_iskey_def(CAPSLOCK); _cimg_iskey_def(A); _cimg_iskey_def(S); _cimg_iskey_def(D); _cimg_iskey_def(F); _cimg_iskey_def(G); _cimg_iskey_def(H); _cimg_iskey_def(J); _cimg_iskey_def(K); _cimg_iskey_def(L); _cimg_iskey_def(ENTER); _cimg_iskey_def(SHIFTLEFT); _cimg_iskey_def(Z); _cimg_iskey_def(X); _cimg_iskey_def(C); _cimg_iskey_def(V); _cimg_iskey_def(B); _cimg_iskey_def(N); _cimg_iskey_def(M); _cimg_iskey_def(SHIFTRIGHT); _cimg_iskey_def(ARROWUP); _cimg_iskey_def(CTRLLEFT); _cimg_iskey_def(APPLEFT); _cimg_iskey_def(ALT); _cimg_iskey_def(SPACE); _cimg_iskey_def(ALTGR); _cimg_iskey_def(APPRIGHT); _cimg_iskey_def(MENU); _cimg_iskey_def(CTRLRIGHT); _cimg_iskey_def(ARROWLEFT); _cimg_iskey_def(ARROWDOWN); _cimg_iskey_def(ARROWRIGHT); _cimg_iskey_def(PAD0); _cimg_iskey_def(PAD1); _cimg_iskey_def(PAD2); _cimg_iskey_def(PAD3); _cimg_iskey_def(PAD4); _cimg_iskey_def(PAD5); _cimg_iskey_def(PAD6); _cimg_iskey_def(PAD7); _cimg_iskey_def(PAD8); _cimg_iskey_def(PAD9); _cimg_iskey_def(PADADD); _cimg_iskey_def(PADSUB); _cimg_iskey_def(PADMUL); _cimg_iskey_def(PADDIV); //@} //------------------------------------------ // //! \name Instance Characteristics //@{ //------------------------------------------ #if cimg_display==0 //! Return width of the screen (current resolution along the X-axis). /** **/ static int screen_width() { _no_display_exception(); return 0; } //! Return height of the screen (current resolution along the Y-axis). /** **/ static int screen_height() { _no_display_exception(); return 0; } #endif //! Return display width. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int width() const { return (int)_width; } //! Return display height. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int height() const { return (int)_height; } //! Return normalization type of the display. /** The normalization type tells about how the values of an input image are normalized by the CImgDisplay to be correctly displayed. The range of values for pixels displayed on screen is <tt>[0,255]</tt>. If the range of values of the data to display is different, a normalization may be required for displaying the data in a correct way. The normalization type can be one of: - \c 0: Value normalization is disabled. It is then assumed that all input data to be displayed by the CImgDisplay instance have values in range <tt>[0,255]</tt>. - \c 1: Value normalization is always performed (this is the default behavior). Before displaying an input image, its values will be (virtually) stretched in range <tt>[0,255]</tt>, so that the contrast of the displayed pixels will be maximum. Use this mode for images whose minimum and maximum values are not prescribed to known values (e.g. float-valued images). Note that when normalized versions of images are computed for display purposes, the actual values of these images are not modified. - \c 2: Value normalization is performed once (on the first image display), then the same normalization coefficients are kept for next displayed frames. - \c 3: Value normalization depends on the pixel type of the data to display. For integer pixel types, the normalization is done regarding the minimum/maximum values of the type (no normalization occurs then for <tt>unsigned char</tt>). For float-valued pixel types, the normalization is done regarding the minimum/maximum value of the image data instead. **/ unsigned int normalization() const { return _normalization; } //! Return title of the associated window as a C-string. /** \note Window title may be not visible, depending on the used window manager or if the current display is in fullscreen mode. **/ const char *title() const { return _title; } //! Return width of the associated window. /** \note The width of the display (i.e. the width of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual width of the associated window. **/ int window_width() const { return (int)_window_width; } //! Return height of the associated window. /** \note The height of the display (i.e. the height of the pixel data buffer associated to the CImgDisplay instance) may be different from the actual height of the associated window. **/ int window_height() const { return (int)_window_height; } //! Return X-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_x() const { return _window_x; } //! Return Y-coordinate of the associated window. /** \note The returned coordinate corresponds to the location of the upper-left corner of the associated window. **/ int window_y() const { return _window_y; } //! Return X-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,width()-1]. **/ int mouse_x() const { return _mouse_x; } //! Return Y-coordinate of the mouse pointer. /** \note - If the mouse pointer is outside window area, \c -1 is returned. - Otherwise, the returned value is in the range [0,height()-1]. **/ int mouse_y() const { return _mouse_y; } //! Return current state of the mouse buttons. /** \note Three mouse buttons can be managed. If one button is pressed, its corresponding bit in the returned value is set: - bit \c 0 (value \c 0x1): State of the left mouse button. - bit \c 1 (value \c 0x2): State of the right mouse button. - bit \c 2 (value \c 0x4): State of the middle mouse button. Several bits can be activated if more than one button are pressed at the same time. \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.button()&1) { // Left button clicked. ... } if (disp.button()&2) { // Right button clicked. ... } if (disp.button()&4) { // Middle button clicked. ... } disp.wait(); } \endcode **/ unsigned int button() const { return _button; } //! Return current state of the mouse wheel. /** \note - The returned value can be positive or negative depending on whether the mouse wheel has been scrolled forward or backward. - Scrolling the wheel forward add \c 1 to the wheel value. - Scrolling the wheel backward substract \c 1 to the wheel value. - The returned value cumulates the number of forward of backward scrolls since the creation of the display, or since the last reset of the wheel value (using set_wheel()). It is strongly recommended to quickly reset the wheel counter when an action has been performed regarding the current wheel value. Otherwise, the returned wheel value may be for instance \c 0 despite the fact that many scrolls have been done (as many in forward as in backward directions). \par Example \code CImgDisplay disp(400,400); while (!disp.is_closed()) { if (disp.wheel()) { int counter = disp.wheel(); // Read the state of the mouse wheel. ... // Do what you want with 'counter'. disp.set_wheel(); // Reset the wheel value to 0. } disp.wait(); } \endcode **/ int wheel() const { return _wheel; } //! Return one entry from the pressed keys history. /** \param pos Indice to read from the pressed keys history (indice \c 0 corresponds to latest entry). \return Keycode of a pressed key or \c 0 for a released key. \note - Each CImgDisplay stores a history of the pressed keys in a buffer of size \c 128. When a new key is pressed, its keycode is stored in the pressed keys history. When a key is released, \c 0 is put instead. This means that up to the 64 last pressed keys may be read from the pressed keys history. When a new value is stored, the pressed keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int key(const unsigned int pos=0) const { return pos<(sizeof(_keys)/sizeof(unsigned int))?_keys[pos]:0; } //! Return one entry from the released keys history. /** \param pos Indice to read from the released keys history (indice \c 0 corresponds to latest entry). \return Keycode of a released key or \c 0 for a pressed key. \note - Each CImgDisplay stores a history of the released keys in a buffer of size \c 128. When a new key is released, its keycode is stored in the pressed keys history. When a key is pressed, \c 0 is put instead. This means that up to the 64 last released keys may be read from the released keys history. When a new value is stored, the released keys history is shifted so that the latest entry is always stored at position \c 0. - Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ unsigned int released_key(const unsigned int pos=0) const { return pos<(sizeof(_released_keys)/sizeof(unsigned int))?_released_keys[pos]:0; } //! Return keycode corresponding to the specified string. /** \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). \par Example \code const unsigned int keyTAB = CImgDisplay::keycode("TAB"); // Return cimg::keyTAB. \endcode **/ static unsigned int keycode(const char *const keycode) { #define _cimg_keycode(k) if (!cimg::strcasecmp(keycode,#k)) return cimg::key##k; _cimg_keycode(ESC); _cimg_keycode(F1); _cimg_keycode(F2); _cimg_keycode(F3); _cimg_keycode(F4); _cimg_keycode(F5); _cimg_keycode(F6); _cimg_keycode(F7); _cimg_keycode(F8); _cimg_keycode(F9); _cimg_keycode(F10); _cimg_keycode(F11); _cimg_keycode(F12); _cimg_keycode(PAUSE); _cimg_keycode(1); _cimg_keycode(2); _cimg_keycode(3); _cimg_keycode(4); _cimg_keycode(5); _cimg_keycode(6); _cimg_keycode(7); _cimg_keycode(8); _cimg_keycode(9); _cimg_keycode(0); _cimg_keycode(BACKSPACE); _cimg_keycode(INSERT); _cimg_keycode(HOME); _cimg_keycode(PAGEUP); _cimg_keycode(TAB); _cimg_keycode(Q); _cimg_keycode(W); _cimg_keycode(E); _cimg_keycode(R); _cimg_keycode(T); _cimg_keycode(Y); _cimg_keycode(U); _cimg_keycode(I); _cimg_keycode(O); _cimg_keycode(P); _cimg_keycode(DELETE); _cimg_keycode(END); _cimg_keycode(PAGEDOWN); _cimg_keycode(CAPSLOCK); _cimg_keycode(A); _cimg_keycode(S); _cimg_keycode(D); _cimg_keycode(F); _cimg_keycode(G); _cimg_keycode(H); _cimg_keycode(J); _cimg_keycode(K); _cimg_keycode(L); _cimg_keycode(ENTER); _cimg_keycode(SHIFTLEFT); _cimg_keycode(Z); _cimg_keycode(X); _cimg_keycode(C); _cimg_keycode(V); _cimg_keycode(B); _cimg_keycode(N); _cimg_keycode(M); _cimg_keycode(SHIFTRIGHT); _cimg_keycode(ARROWUP); _cimg_keycode(CTRLLEFT); _cimg_keycode(APPLEFT); _cimg_keycode(ALT); _cimg_keycode(SPACE); _cimg_keycode(ALTGR); _cimg_keycode(APPRIGHT); _cimg_keycode(MENU); _cimg_keycode(CTRLRIGHT); _cimg_keycode(ARROWLEFT); _cimg_keycode(ARROWDOWN); _cimg_keycode(ARROWRIGHT); _cimg_keycode(PAD0); _cimg_keycode(PAD1); _cimg_keycode(PAD2); _cimg_keycode(PAD3); _cimg_keycode(PAD4); _cimg_keycode(PAD5); _cimg_keycode(PAD6); _cimg_keycode(PAD7); _cimg_keycode(PAD8); _cimg_keycode(PAD9); _cimg_keycode(PADADD); _cimg_keycode(PADSUB); _cimg_keycode(PADMUL); _cimg_keycode(PADDIV); return 0; } //! Return the current refresh rate, in frames per second. /** \note Returns a significant value when the current instance is used to display successive frames. It measures the delay between successive calls to frames_per_second(). **/ float frames_per_second() { if (!_fps_timer) _fps_timer = cimg::time(); const float delta = (cimg::time()-_fps_timer)/1000.0f; ++_fps_frames; if (delta>=1) { _fps_fps = _fps_frames/delta; _fps_frames = 0; _fps_timer = cimg::time(); } return _fps_fps; } //@} //--------------------------------------- // //! \name Window Manipulation //@{ //--------------------------------------- #if cimg_display==0 //! Display image on associated window. /** \param img Input image to display. \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImg<T>& img) { return assign(img); } #endif //! Display list of images on associated window. /** \param list List of images to display. \param axis Axis used to append the images along, for the visualization (can be \c x, \c y, \c z or \c c). \param align Relative position of aligned images when displaying lists with images of different sizes (\c 0 for upper-left, \c 0.5 for centering and \c 1 for lower-right). \note This method returns immediately. **/ template<typename T> CImgDisplay& display(const CImgList<T>& list, const char axis='x', const float align=0) { return display(list.get_append(axis,align)); } #if cimg_display==0 //! Show (closed) associated window on the screen. /** \note - Force the associated window of a display to be visible on the screen, even if it has been closed before. - Using show() on a visible display does nothing. **/ CImgDisplay& show() { return assign(); } //! Close (visible) associated window and make it disappear from the screen. /** \note - A closed display only means the associated window is not visible anymore. This does not mean the display has been destroyed. Use show() to make the associated window reappear. - Using close() on a closed display does nothing. **/ CImgDisplay& close() { return assign(); } //! Move associated window to a new location. /** \param pos_x X-coordinate of the new window location. \param pos_y Y-coordinate of the new window location. \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& move(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Resize display to the size of the associated window. /** \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note - Calling this method ensures that width() and window_width() become equal, as well as height() and window_height(). - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const bool force_redraw=true) { resize(_window_width,_window_height,force_redraw); return *this; } #if cimg_display==0 //! Resize display to the specified size. /** \param width Requested display width. \param height Requested display height. \param force_redraw Tells if the previous window content must be updated and refreshed as well. \note The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const int width, const int height, const bool force_redraw=true) { return assign(width,height,0,3,force_redraw); } #endif //! Resize display to the size of an input image. /** \param img Input image to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>img.width()</tt> become equal, as well as height() and <tt>img.height()</tt>. - The associated window is also resized to specified dimensions. **/ template<typename T> CImgDisplay& resize(const CImg<T>& img, const bool force_redraw=true) { return resize(img._width,img._height,force_redraw); } //! Resize display to the size of another CImgDisplay instance. /** \param disp Input display to take size from. \param force_redraw Tells if the previous window content must be resized and updated as well. \note - Calling this method ensures that width() and <tt>disp.width()</tt> become equal, as well as height() and <tt>disp.height()</tt>. - The associated window is also resized to specified dimensions. **/ CImgDisplay& resize(const CImgDisplay& disp, const bool force_redraw=true) { return resize(disp._width,disp._height,force_redraw); } // [internal] Render pixel buffer with size (wd,hd) from source buffer of size (ws,hs). template<typename t, typename T> static void _render_resize(const T *ptrs, const unsigned int ws, const unsigned int hs, t *ptrd, const unsigned int wd, const unsigned int hd) { unsigned int *const offx = new unsigned int[wd], *const offy = new unsigned int[hd+1], *poffx, *poffy; float s, curr, old; s = (float)ws/wd; poffx = offx; curr = 0; for (unsigned int x = 0; x<wd; ++x) { old = curr; curr+=s; *(poffx++) = (unsigned int)curr - (unsigned int)old; } s = (float)hs/hd; poffy = offy; curr = 0; for (unsigned int y = 0; y<hd; ++y) { old = curr; curr+=s; *(poffy++) = ws*((unsigned int)curr - (unsigned int)old); } *poffy = 0; poffy = offy; for (unsigned int y = 0; y<hd; ) { const T *ptr = ptrs; poffx = offx; for (unsigned int x = 0; x<wd; ++x) { *(ptrd++) = *ptr; ptr+=*(poffx++); } ++y; unsigned int dy = *(poffy++); for ( ; !dy && y<hd; std::memcpy(ptrd,ptrd - wd,sizeof(t)*wd), ++y, ptrd+=wd, dy = *(poffy++)) {} ptrs+=dy; } delete[] offx; delete[] offy; } //! Set normalization type. /** \param normalization New normalization mode. **/ CImgDisplay& set_normalization(const unsigned int normalization) { _normalization = normalization; _min = _max = 0; return *this; } #if cimg_display==0 //! Set title of the associated window. /** \param format C-string containing the format of the title, as with <tt>std::printf()</tt>. \warning As the first argument is a format string, it is highly recommended to write \code disp.set_title("%s",window_title); \endcode instead of \code disp.set_title(window_title); \endcode if \c window_title can be arbitrary, to prevent nasty memory access. **/ CImgDisplay& set_title(const char *const format, ...) { return assign(0,0,format); } #endif //! Enable or disable fullscreen mode. /** \param is_fullscreen Tells is the fullscreen mode must be activated or not. \param force_redraw Tells if the previous window content must be displayed as well. \note - When the fullscreen mode is enabled, the associated window fills the entire screen but the size of the current display is not modified. - The screen resolution may be switched to fit the associated window size and ensure it appears the largest as possible. For X-Window (X11) users, the configuration flag \c cimg_use_xrandr has to be set to allow the screen resolution change (requires the X11 extensions to be enabled). **/ CImgDisplay& set_fullscreen(const bool is_fullscreen, const bool force_redraw=true) { if (is_empty() || _is_fullscreen==is_fullscreen) return *this; return toggle_fullscreen(force_redraw); } #if cimg_display==0 //! Toggle fullscreen mode. /** \param force_redraw Tells if the previous window content must be displayed as well. \note Enable fullscreen mode if it was not enabled, and disable it otherwise. **/ CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { return assign(_width,_height,0,3,force_redraw); } //! Show mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& show_mouse() { return assign(); } //! Hide mouse pointer. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& hide_mouse() { return assign(); } //! Move mouse pointer to a specified location. /** \note Depending on the window manager behavior, this method may not succeed (no exceptions are thrown nevertheless). **/ CImgDisplay& set_mouse(const int pos_x, const int pos_y) { return assign(pos_x,pos_y); } #endif //! Simulate a mouse button release event. /** \note All mouse buttons are considered released at the same time. **/ CImgDisplay& set_button() { _button = 0; _is_event = true; return *this; } //! Simulate a mouse button press or release event. /** \param button Buttons event code, where each button is associated to a single bit. \param is_pressed Tells if the mouse button is considered as pressed or released. **/ CImgDisplay& set_button(const unsigned int button, const bool is_pressed=true) { const unsigned int buttoncode = button==1?1:button==2?2:button==3?4:0; if (is_pressed) _button |= buttoncode; else _button &= ~buttoncode; _is_event = buttoncode?true:false; return *this; } //! Flush all mouse wheel events. /** \note Make wheel() to return \c 0, if called afterwards. **/ CImgDisplay& set_wheel() { _wheel = 0; _is_event = true; return *this; } //! Simulate a wheel event. /** \param amplitude Amplitude of the wheel scrolling to simulate. \note Make wheel() to return \c amplitude, if called afterwards. **/ CImgDisplay& set_wheel(const int amplitude) { _wheel+=amplitude; _is_event = amplitude?true:false; return *this; } //! Flush all key events. /** \note Make key() to return \c 0, if called afterwards. **/ CImgDisplay& set_key() { std::memset((void*)_keys,0,sizeof(_keys)); std::memset((void*)_released_keys,0,sizeof(_released_keys)); _is_keyESC = _is_keyF1 = _is_keyF2 = _is_keyF3 = _is_keyF4 = _is_keyF5 = _is_keyF6 = _is_keyF7 = _is_keyF8 = _is_keyF9 = _is_keyF10 = _is_keyF11 = _is_keyF12 = _is_keyPAUSE = _is_key1 = _is_key2 = _is_key3 = _is_key4 = _is_key5 = _is_key6 = _is_key7 = _is_key8 = _is_key9 = _is_key0 = _is_keyBACKSPACE = _is_keyINSERT = _is_keyHOME = _is_keyPAGEUP = _is_keyTAB = _is_keyQ = _is_keyW = _is_keyE = _is_keyR = _is_keyT = _is_keyY = _is_keyU = _is_keyI = _is_keyO = _is_keyP = _is_keyDELETE = _is_keyEND = _is_keyPAGEDOWN = _is_keyCAPSLOCK = _is_keyA = _is_keyS = _is_keyD = _is_keyF = _is_keyG = _is_keyH = _is_keyJ = _is_keyK = _is_keyL = _is_keyENTER = _is_keySHIFTLEFT = _is_keyZ = _is_keyX = _is_keyC = _is_keyV = _is_keyB = _is_keyN = _is_keyM = _is_keySHIFTRIGHT = _is_keyARROWUP = _is_keyCTRLLEFT = _is_keyAPPLEFT = _is_keyALT = _is_keySPACE = _is_keyALTGR = _is_keyAPPRIGHT = _is_keyMENU = _is_keyCTRLRIGHT = _is_keyARROWLEFT = _is_keyARROWDOWN = _is_keyARROWRIGHT = _is_keyPAD0 = _is_keyPAD1 = _is_keyPAD2 = _is_keyPAD3 = _is_keyPAD4 = _is_keyPAD5 = _is_keyPAD6 = _is_keyPAD7 = _is_keyPAD8 = _is_keyPAD9 = _is_keyPADADD = _is_keyPADSUB = _is_keyPADMUL = _is_keyPADDIV = false; _is_event = true; return *this; } //! Simulate a keyboard press/release event. /** \param keycode Keycode of the associated key. \param is_pressed Tells if the key is considered as pressed or released. \note Keycode constants are defined in the cimg namespace and are architecture-dependent. Use them to ensure your code stay portable (see cimg::keyESC). **/ CImgDisplay& set_key(const unsigned int keycode, const bool is_pressed=true) { #define _cimg_set_key(k) if (keycode==cimg::key##k) _is_key##k = is_pressed; _cimg_set_key(ESC); _cimg_set_key(F1); _cimg_set_key(F2); _cimg_set_key(F3); _cimg_set_key(F4); _cimg_set_key(F5); _cimg_set_key(F6); _cimg_set_key(F7); _cimg_set_key(F8); _cimg_set_key(F9); _cimg_set_key(F10); _cimg_set_key(F11); _cimg_set_key(F12); _cimg_set_key(PAUSE); _cimg_set_key(1); _cimg_set_key(2); _cimg_set_key(3); _cimg_set_key(4); _cimg_set_key(5); _cimg_set_key(6); _cimg_set_key(7); _cimg_set_key(8); _cimg_set_key(9); _cimg_set_key(0); _cimg_set_key(BACKSPACE); _cimg_set_key(INSERT); _cimg_set_key(HOME); _cimg_set_key(PAGEUP); _cimg_set_key(TAB); _cimg_set_key(Q); _cimg_set_key(W); _cimg_set_key(E); _cimg_set_key(R); _cimg_set_key(T); _cimg_set_key(Y); _cimg_set_key(U); _cimg_set_key(I); _cimg_set_key(O); _cimg_set_key(P); _cimg_set_key(DELETE); _cimg_set_key(END); _cimg_set_key(PAGEDOWN); _cimg_set_key(CAPSLOCK); _cimg_set_key(A); _cimg_set_key(S); _cimg_set_key(D); _cimg_set_key(F); _cimg_set_key(G); _cimg_set_key(H); _cimg_set_key(J); _cimg_set_key(K); _cimg_set_key(L); _cimg_set_key(ENTER); _cimg_set_key(SHIFTLEFT); _cimg_set_key(Z); _cimg_set_key(X); _cimg_set_key(C); _cimg_set_key(V); _cimg_set_key(B); _cimg_set_key(N); _cimg_set_key(M); _cimg_set_key(SHIFTRIGHT); _cimg_set_key(ARROWUP); _cimg_set_key(CTRLLEFT); _cimg_set_key(APPLEFT); _cimg_set_key(ALT); _cimg_set_key(SPACE); _cimg_set_key(ALTGR); _cimg_set_key(APPRIGHT); _cimg_set_key(MENU); _cimg_set_key(CTRLRIGHT); _cimg_set_key(ARROWLEFT); _cimg_set_key(ARROWDOWN); _cimg_set_key(ARROWRIGHT); _cimg_set_key(PAD0); _cimg_set_key(PAD1); _cimg_set_key(PAD2); _cimg_set_key(PAD3); _cimg_set_key(PAD4); _cimg_set_key(PAD5); _cimg_set_key(PAD6); _cimg_set_key(PAD7); _cimg_set_key(PAD8); _cimg_set_key(PAD9); _cimg_set_key(PADADD); _cimg_set_key(PADSUB); _cimg_set_key(PADMUL); _cimg_set_key(PADDIV); if (is_pressed) { if (*_keys) std::memmove((void*)(_keys+1),(void*)_keys,sizeof(_keys) - sizeof(unsigned int)); *_keys = keycode; if (*_released_keys) { std::memmove((void*)(_released_keys+1),(void*)_released_keys,sizeof(_released_keys) - sizeof(unsigned int)); *_released_keys = 0; } } else { if (*_keys) { std::memmove((void*)(_keys+1),(void*)_keys,sizeof(_keys) - sizeof(unsigned int)); *_keys = 0; } if (*_released_keys) std::memmove((void*)(_released_keys+1),(void*)_released_keys,sizeof(_released_keys) - sizeof(unsigned int)); *_released_keys = keycode; } _is_event = keycode?true:false; return *this; } //! Flush all display events. /** \note Remove all passed events from the current display. **/ CImgDisplay& flush() { set_key().set_button().set_wheel(); _is_resized = _is_moved = _is_event = false; _fps_timer = _fps_frames = _timer = 0; _fps_fps = 0; return *this; } //! Wait for any user event occuring on the current display. CImgDisplay& wait() { wait(*this); return *this; } //! Wait for a given number of milliseconds since the last call to wait(). /** \param milliseconds Number of milliseconds to wait for. \note Similar to cimg::wait(). **/ CImgDisplay& wait(const unsigned int milliseconds) { cimg::_wait(milliseconds,_timer); return *this; } //! Wait for any event occuring on the display \c disp1. static void wait(CImgDisplay& disp1) { disp1._is_event = 0; while (!disp1._is_closed && !disp1._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1 or \c disp2. static void wait(CImgDisplay& disp1, CImgDisplay& disp2) { disp1._is_event = disp2._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed) && !disp1._is_event && !disp2._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2 or \c disp3. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3) { disp1._is_event = disp2._is_event = disp3._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3 or \c disp4. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4 or \c disp5. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp6. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp7. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp8. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp9. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event) wait_all(); } //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp10. static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5, CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9, CImgDisplay& disp10) { disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event = disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = disp10._is_event = 0; while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed || !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed || !disp10._is_closed) && !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event && !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event && !disp10._is_event) wait_all(); } #if cimg_display==0 //! Wait for any window event occuring in any opened CImgDisplay. static void wait_all() { return _no_display_exception(); } //! Render image into internal display buffer. /** \param img Input image data to render. \note - Convert image data representation into the internal display buffer (architecture-dependent structure). - The content of the associated window is not modified, until paint() is called. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ template<typename T> CImgDisplay& render(const CImg<T>& img) { return assign(img); } //! Paint internal display buffer on associated window. /** \note - Update the content of the associated window with the internal display buffer, e.g. after a render() call. - Should not be used for common CImgDisplay uses, since display() is more useful. **/ CImgDisplay& paint() { return assign(); } //! Take a snapshot of the associated window content. /** \param[out] img Output snapshot. Can be empty on input. **/ template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { cimg::unused(img); _no_display_exception(); return *this; } #endif // X11-based implementation //-------------------------- #if cimg_display==1 Atom _wm_window_atom, _wm_protocol_atom; Window _window, _background_window; Colormap _colormap; XImage *_image; void *_data; #ifdef cimg_use_xshm XShmSegmentInfo *_shminfo; #endif static int screen_width() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_width(): Failed to open X11 display."); res = DisplayWidth(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width; else res = DisplayWidth(dpy,DefaultScreen(dpy)); #else res = DisplayWidth(dpy,DefaultScreen(dpy)); #endif } return res; } static int screen_height() { Display *const dpy = cimg::X11_attr().display; int res = 0; if (!dpy) { Display *const _dpy = XOpenDisplay(0); if (!_dpy) throw CImgDisplayException("CImgDisplay::screen_height(): Failed to open X11 display."); res = DisplayHeight(_dpy,DefaultScreen(_dpy)); XCloseDisplay(_dpy); } else { #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) res = cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height; else res = DisplayHeight(dpy,DefaultScreen(dpy)); #else res = DisplayHeight(dpy,DefaultScreen(dpy)); #endif } return res; } static void wait_all() { Display *const dpy = cimg::X11_attr().display; if (!dpy) return; XLockDisplay(dpy); bool flag = true; XEvent event; while (flag) { XNextEvent(dpy,&event); for (unsigned int i = 0; i<cimg::X11_attr().nb_wins; ++i) if (!cimg::X11_attr().wins[i]->_is_closed && event.xany.window==cimg::X11_attr().wins[i]->_window) { cimg::X11_attr().wins[i]->_handle_events(&event); if (cimg::X11_attr().wins[i]->_is_event) flag = false; } } XUnlockDisplay(dpy); } void _handle_events(const XEvent *const pevent) { Display *const dpy = cimg::X11_attr().display; XEvent event = *pevent; switch (event.type) { case ClientMessage : { if ((int)event.xclient.message_type==(int)_wm_protocol_atom && (int)event.xclient.data.l[0]==(int)_wm_window_atom) { XUnmapWindow(cimg::X11_attr().display,_window); _is_closed = _is_event = true; } } break; case ConfigureNotify : { while (XCheckWindowEvent(dpy,_window,StructureNotifyMask,&event)) {} const unsigned int nw = event.xconfigure.width, nh = event.xconfigure.height; const int nx = event.xconfigure.x, ny = event.xconfigure.y; if (nw && nh && (nw!=_window_width || nh!=_window_height)) { _window_width = nw; _window_height = nh; _mouse_x = _mouse_y = -1; XResizeWindow(dpy,_window,_window_width,_window_height); _is_resized = _is_event = true; } if (nx!=_window_x || ny!=_window_y) { _window_x = nx; _window_y = ny; _is_moved = _is_event = true; } } break; case Expose : { while (XCheckWindowEvent(dpy,_window,ExposureMask,&event)) {} _paint(false); if (_is_fullscreen) { XWindowAttributes attr; XGetWindowAttributes(dpy,_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XSetInputFocus(dpy,_window,RevertToParent,CurrentTime); } } break; case ButtonPress : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1); break; case 3 : set_button(2); break; case 2 : set_button(3); break; } } while (XCheckWindowEvent(dpy,_window,ButtonPressMask,&event)); } break; case ButtonRelease : { do { _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; switch (event.xbutton.button) { case 1 : set_button(1,false); break; case 3 : set_button(2,false); break; case 2 : set_button(3,false); break; case 4 : set_wheel(1); break; case 5 : set_wheel(-1); break; } } while (XCheckWindowEvent(dpy,_window,ButtonReleaseMask,&event)); } break; case KeyPress : { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,true); } break; case KeyRelease : { char keys_return[32]; // Check that the key has been physically unpressed. XQueryKeymap(dpy,keys_return); const unsigned int kc = event.xkey.keycode, kc1 = kc/8, kc2 = kc%8; const bool is_key_pressed = kc1>=32?false:(keys_return[kc1]>>kc2)&1; if (!is_key_pressed) { char tmp = 0; KeySym ksym; XLookupString(&event.xkey,&tmp,1,&ksym,0); set_key((unsigned int)ksym,false); } } break; case EnterNotify: { while (XCheckWindowEvent(dpy,_window,EnterWindowMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; } break; case LeaveNotify : { while (XCheckWindowEvent(dpy,_window,LeaveWindowMask,&event)) {} _mouse_x = _mouse_y =-1; _is_event = true; } break; case MotionNotify : { while (XCheckWindowEvent(dpy,_window,PointerMotionMask,&event)) {} _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y; if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1; _is_event = true; } break; } } static void* _events_thread(void *) { // Only one thread to handle events for all opened display windows. Display *const dpy = cimg::X11_attr().display; XEvent event; pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,0); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0); for (;;) { XLockDisplay(dpy); bool event_flag = XCheckTypedEvent(dpy,ClientMessage,&event); if (!event_flag) event_flag = XCheckMaskEvent(dpy, ExposureMask | StructureNotifyMask | ButtonPressMask| KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask| ButtonReleaseMask | KeyReleaseMask,&event); if (event_flag) for (unsigned int i = 0; i<cimg::X11_attr().nb_wins; ++i) if (!cimg::X11_attr().wins[i]->_is_closed && event.xany.window==cimg::X11_attr().wins[i]->_window) cimg::X11_attr().wins[i]->_handle_events(&event); XUnlockDisplay(dpy); pthread_testcancel(); cimg::sleep(8); } return 0; } void _set_colormap(Colormap& _colormap, const unsigned int dim) { XColor colormap[256]; switch (dim) { case 1 : { // colormap for greyscale images for (unsigned int index = 0; index<256; ++index) { colormap[index].pixel = index; colormap[index].red = colormap[index].green = colormap[index].blue = (unsigned short)(index<<8); colormap[index].flags = DoRed | DoGreen | DoBlue; } } break; case 2 : { // colormap for RG images for (unsigned int index = 0, r = 8; r<256; r+=16) for (unsigned int g = 8; g<256; g+=16) { colormap[index].pixel = index; colormap[index].red = colormap[index].blue = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } break; default : { // colormap for RGB images for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap[index].pixel = index; colormap[index].red = (unsigned short)(r<<8); colormap[index].green = (unsigned short)(g<<8); colormap[index].blue = (unsigned short)(b<<8); colormap[index++].flags = DoRed | DoGreen | DoBlue; } } } XStoreColors(cimg::X11_attr().display,_colormap,colormap,256); } void _map_window() { Display *const dpy = cimg::X11_attr().display; bool is_exposed = false, is_mapped = false; XWindowAttributes attr; XEvent event; XMapRaised(dpy,_window); do { // Wait for the window to be mapped. XWindowEvent(dpy,_window,StructureNotifyMask | ExposureMask,&event); switch (event.type) { case MapNotify : is_mapped = true; break; case Expose : is_exposed = true; break; } } while (!is_exposed || !is_mapped); do { // Wait for the window to be visible. XGetWindowAttributes(dpy,_window,&attr); if (attr.map_state!=IsViewable) { XSync(dpy,0); cimg::sleep(10); } } while (attr.map_state!=IsViewable); _window_x = attr.x; _window_y = attr.y; } void _paint(const bool wait_expose=true) { if (_is_closed || !_image) return; Display *const dpy = cimg::X11_attr().display; if (wait_expose) { // Send an expose event sticked to display window to force repaint. static XEvent event; event.xexpose.type = Expose; event.xexpose.serial = 0; event.xexpose.send_event = 1; event.xexpose.display = dpy; event.xexpose.window = _window; event.xexpose.x = 0; event.xexpose.y = 0; event.xexpose.width = width(); event.xexpose.height = height(); event.xexpose.count = 0; XSendEvent(dpy,_window,0,0,&event); } else { // Repaint directly (may be called from the expose event). GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) { const int completion_type = XShmGetEventBase(dpy) + ShmCompletion; XEvent event; XShmPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height,1); do { XNextEvent(dpy,&event); } while (event.type!=completion_type); // Wait for the image drawing to be completed. } else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #else XPutImage(dpy,_window,gc,_image,0,0,0,0,_width,_height); #endif } } template<typename T> void _resize(T pixel_type, const unsigned int ndimx, const unsigned int ndimy, const bool force_redraw) { Display *const dpy = cimg::X11_attr().display; cimg::unused(pixel_type); #ifdef cimg_use_xshm if (_shminfo) { XShmSegmentInfo *const nshminfo = new XShmSegmentInfo; XImage *const nimage = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,nshminfo,ndimx,ndimy); if (!nimage) { delete nshminfo; return; } else { nshminfo->shmid = shmget(IPC_PRIVATE,ndimx*ndimy*sizeof(T),IPC_CREAT | 0777); if (nshminfo->shmid==-1) { XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->shmaddr = nimage->data = (char*)shmat(nshminfo->shmid,0,0); if (nshminfo->shmaddr==(char*)-1) { shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { nshminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,nshminfo); XFlush(dpy); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(nshminfo->shmaddr); shmctl(nshminfo->shmid,IPC_RMID,0); XDestroyImage(nimage); delete nshminfo; return; } else { T *const ndata = (T*)nimage->data; if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = nshminfo; _image = nimage; _data = (void*)ndata; } } } } } else #endif { T *ndata = (T*)std::malloc(ndimx*ndimy*sizeof(T)); if (force_redraw) _render_resize((T*)_data,_width,_height,ndata,ndimx,ndimy); else std::memset(ndata,0,sizeof(T)*ndimx*ndimy); _data = (void*)ndata; XDestroyImage(_image); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)), cimg::X11_attr().nb_bits,ZPixmap,0,(char*)_data,ndimx,ndimy,8,0); } } void _init_fullscreen() { if (!_is_fullscreen || _is_closed) return; Display *const dpy = cimg::X11_attr().display; _background_window = 0; #ifdef cimg_use_xrandr int foo; if (XRRQueryExtension(dpy,&foo,&foo)) { XRRRotations(dpy,DefaultScreen(dpy),&cimg::X11_attr().curr_rotation); if (!cimg::X11_attr().resolutions) { cimg::X11_attr().resolutions = XRRSizes(dpy,DefaultScreen(dpy),&foo); cimg::X11_attr().nb_resolutions = (unsigned int)foo; } if (cimg::X11_attr().resolutions) { cimg::X11_attr().curr_resolution = 0; for (unsigned int i = 0; i<cimg::X11_attr().nb_resolutions; ++i) { const unsigned int nw = (unsigned int)(cimg::X11_attr().resolutions[i].width), nh = (unsigned int)(cimg::X11_attr().resolutions[i].height); if (nw>=_width && nh>=_height && nw<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].width) && nh<=(unsigned int)(cimg::X11_attr().resolutions[cimg::X11_attr().curr_resolution].height)) cimg::X11_attr().curr_resolution = i; } if (cimg::X11_attr().curr_resolution>0) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy), cimg::X11_attr().curr_resolution,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); } } } if (!cimg::X11_attr().resolutions) cimg::warn(_cimgdisplay_instance "init_fullscreen(): Xrandr extension not supported by the X server.", cimgdisplay_instance); #endif const unsigned int sx = screen_width(), sy = screen_height(); if (sx==_width && sy==_height) return; XSetWindowAttributes winattr; winattr.override_redirect = 1; _background_window = XCreateWindow(dpy,DefaultRootWindow(dpy),0,0,sx,sy,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); const unsigned long buf_size = (unsigned long)sx*sy*(cimg::X11_attr().nb_bits==8?1:(cimg::X11_attr().nb_bits==16?2:4)); void *background_data = std::malloc(buf_size); std::memset(background_data,0,buf_size); XImage *background_image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits, ZPixmap,0,(char*)background_data,sx,sy,8,0); XEvent event; XSelectInput(dpy,_background_window,StructureNotifyMask); XMapRaised(dpy,_background_window); do XWindowEvent(dpy,_background_window,StructureNotifyMask,&event); while (event.type!=MapNotify); GC gc = DefaultGC(dpy,DefaultScreen(dpy)); #ifdef cimg_use_xshm if (_shminfo) XShmPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy,0); else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #else XPutImage(dpy,_background_window,gc,background_image,0,0,0,0,sx,sy); #endif XWindowAttributes attr; XGetWindowAttributes(dpy,_background_window,&attr); while (attr.map_state!=IsViewable) XSync(dpy,0); XDestroyImage(background_image); } void _desinit_fullscreen() { if (!_is_fullscreen) return; Display *const dpy = cimg::X11_attr().display; XUngrabKeyboard(dpy,CurrentTime); #ifdef cimg_use_xrandr if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) { XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy)); XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy),0,cimg::X11_attr().curr_rotation,CurrentTime); XRRFreeScreenConfigInfo(config); XSync(dpy,0); cimg::X11_attr().curr_resolution = 0; } #endif if (_background_window) XDestroyWindow(dpy,_background_window); _background_window = 0; _is_fullscreen = false; } static int _assign_xshm(Display *dpy, XErrorEvent *error) { cimg::unused(dpy,error); cimg::X11_attr().is_shm_enabled = false; return 0; } void _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous display window if existing if (!is_empty()) assign(); // Open X11 display and retrieve graphical properties. Display* &dpy = cimg::X11_attr().display; if (!dpy) { static const int xinit_status = XInitThreads(); cimg::unused(xinit_status); dpy = XOpenDisplay(0); if (!dpy) throw CImgDisplayException(_cimgdisplay_instance "assign(): Failed to open X11 display.", cimgdisplay_instance); cimg::X11_attr().nb_bits = DefaultDepth(dpy,DefaultScreen(dpy)); if (cimg::X11_attr().nb_bits!=8 && cimg::X11_attr().nb_bits!=16 && cimg::X11_attr().nb_bits!=24 && cimg::X11_attr().nb_bits!=32) throw CImgDisplayException(_cimgdisplay_instance "assign(): Invalid %u bits screen mode detected " "(only 8, 16, 24 and 32 bits modes are managed).", cimgdisplay_instance, cimg::X11_attr().nb_bits); XVisualInfo vtemplate; vtemplate.visualid = XVisualIDFromVisual(DefaultVisual(dpy,DefaultScreen(dpy))); int nb_visuals; XVisualInfo *vinfo = XGetVisualInfo(dpy,VisualIDMask,&vtemplate,&nb_visuals); if (vinfo && vinfo->red_mask<vinfo->blue_mask) cimg::X11_attr().is_blue_first = true; cimg::X11_attr().byte_order = ImageByteOrder(dpy); XFree(vinfo); XLockDisplay(dpy); cimg::X11_attr().event_thread = new pthread_t; pthread_create(cimg::X11_attr().event_thread,0,_events_thread,0); } else XLockDisplay(dpy); // Set display variables. _width = cimg::min(dimw,(unsigned int)screen_width()); _height = cimg::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _title = tmp_title; flush(); // Create X11 window (and LUT, if 8bits display) if (_is_fullscreen) { if (!_is_closed) _init_fullscreen(); const unsigned int sx = screen_width(), sy = screen_height(); XSetWindowAttributes winattr; winattr.override_redirect = 1; _window = XCreateWindow(dpy,DefaultRootWindow(dpy),(sx-_width)/2,(sy-_height)/2,_width,_height,0,0, InputOutput,CopyFromParent,CWOverrideRedirect,&winattr); } else _window = XCreateSimpleWindow(dpy,DefaultRootWindow(dpy),0,0,_width,_height,0,0L,0L); XSelectInput(dpy,_window, ExposureMask | StructureNotifyMask | ButtonPressMask | KeyPressMask | PointerMotionMask | EnterWindowMask | LeaveWindowMask | ButtonReleaseMask | KeyReleaseMask); XStoreName(dpy,_window,_title?_title:" "); if (cimg::X11_attr().nb_bits==8) { _colormap = XCreateColormap(dpy,_window,DefaultVisual(dpy,DefaultScreen(dpy)),AllocAll); _set_colormap(_colormap,3); XSetWindowColormap(dpy,_window,_colormap); } static const char *const _window_class = cimg_appname; XClassHint *const window_class = XAllocClassHint(); window_class->res_name = (char*)_window_class; window_class->res_class = (char*)_window_class; XSetClassHint(dpy,_window,window_class); XFree(window_class); _window_width = _width; _window_height = _height; // Create XImage #ifdef cimg_use_xshm _shminfo = 0; if (XShmQueryExtension(dpy)) { _shminfo = new XShmSegmentInfo; _image = XShmCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits,ZPixmap,0,_shminfo,_width,_height); if (!_image) { delete _shminfo; _shminfo = 0; } else { _shminfo->shmid = shmget(IPC_PRIVATE,_image->bytes_per_line*_image->height,IPC_CREAT|0777); if (_shminfo->shmid==-1) { XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->shmaddr = _image->data = (char*)(_data = shmat(_shminfo->shmid,0,0)); if (_shminfo->shmaddr==(char*)-1) { shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } else { _shminfo->readOnly = 0; cimg::X11_attr().is_shm_enabled = true; XErrorHandler oldXErrorHandler = XSetErrorHandler(_assign_xshm); XShmAttach(dpy,_shminfo); XSync(dpy,0); XSetErrorHandler(oldXErrorHandler); if (!cimg::X11_attr().is_shm_enabled) { shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); XDestroyImage(_image); delete _shminfo; _shminfo = 0; } } } } } if (!_shminfo) #endif { const unsigned long buf_size = (unsigned long)_width*_height*(cimg::X11_attr().nb_bits==8?1:(cimg::X11_attr().nb_bits==16?2:4)); _data = std::malloc(buf_size); _image = XCreateImage(dpy,DefaultVisual(dpy,DefaultScreen(dpy)),cimg::X11_attr().nb_bits,ZPixmap,0,(char*)_data,_width,_height,8,0); } _wm_window_atom = XInternAtom(dpy,"WM_DELETE_WINDOW",0); _wm_protocol_atom = XInternAtom(dpy,"WM_PROTOCOLS",0); XSetWMProtocols(dpy,_window,&_wm_window_atom,1); if (_is_fullscreen) XGrabKeyboard(dpy,_window,1,GrabModeAsync,GrabModeAsync,CurrentTime); cimg::X11_attr().wins[cimg::X11_attr().nb_wins++]=this; if (!_is_closed) _map_window(); else { _window_x = _window_y = cimg::type<int>::min(); } XUnlockDisplay(dpy); } CImgDisplay& assign() { if (is_empty()) return flush(); Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); // Remove display window from event thread list. unsigned int i; for (i = 0; i<cimg::X11_attr().nb_wins && cimg::X11_attr().wins[i]!=this; ++i) {} for (; i<cimg::X11_attr().nb_wins-1; ++i) cimg::X11_attr().wins[i] = cimg::X11_attr().wins[i+1]; --cimg::X11_attr().nb_wins; // Destroy window, image, colormap and title. if (_is_fullscreen && !_is_closed) _desinit_fullscreen(); XDestroyWindow(dpy,_window); _window = 0; #ifdef cimg_use_xshm if (_shminfo) { XShmDetach(dpy,_shminfo); XDestroyImage(_image); shmdt(_shminfo->shmaddr); shmctl(_shminfo->shmid,IPC_RMID,0); delete _shminfo; _shminfo = 0; } else #endif XDestroyImage(_image); _data = 0; _image = 0; if (cimg::X11_attr().nb_bits==8) XFreeColormap(dpy,_colormap); _colormap = 0; XSync(dpy,0); // Reset display variables delete[] _title; _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); // End event thread and close display if necessary XUnlockDisplay(dpy); if (!cimg::X11_attr().nb_wins) { // Kill event thread //pthread_cancel(*cimg::X11_attr().event_thread); //XUnlockDisplay(cimg::X11_attr().display); //pthread_join(*cimg::X11_attr().event_thread,0); //delete cimg::X11_attr().event_thread; //cimg::X11_attr().event_thread = 0; // XUnlockDisplay(cimg::X11_attr().display); // <- This call make the library hang sometimes (fix required). // XCloseDisplay(cimg::X11_attr().display); // <- This call make the library hang sometimes (fix required). //cimg::X11_attr().display = 0; } return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): (cimg::X11_attr().nb_bits==16?sizeof(unsigned short):sizeof(unsigned int)))*(unsigned long)_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d(img._width/2,img._height/2,img._depth/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d(img._width/2,img._height/2,img._depth/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return render(nimg).paint(); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char): cimg::X11_attr().nb_bits==16?sizeof(unsigned short): sizeof(unsigned int))*(unsigned long)_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); Display *const dpy = cimg::X11_attr().display; const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*width()/100), tmpdimy = (nheight>0)?nheight:(-nheight*height()/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; XLockDisplay(dpy); if (_window_width!=dimx || _window_height!=dimy) XResizeWindow(dpy,_window,dimx,dimy); if (_width!=dimx || _height!=dimy) switch (cimg::X11_attr().nb_bits) { case 8 : { unsigned char pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; case 16 : { unsigned short pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } break; default : { unsigned int pixel_type = 0; _resize(pixel_type,dimx,dimy,force_redraw); } } _window_width = _width = dimx; _window_height = _height = dimy; _is_resized = false; XUnlockDisplay(dpy); if (_is_fullscreen) move((screen_width()-_width)/2,(screen_height()-_height)/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const unsigned long buf_size = (unsigned long)_width*_height*(cimg::X11_attr().nb_bits==8?1:(cimg::X11_attr().nb_bits==16?2:4)); void *image_data = std::malloc(buf_size); std::memcpy(image_data,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,image_data,buf_size); std::free(image_data); return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); if (_is_fullscreen) _init_fullscreen(); _map_window(); _is_closed = false; XUnlockDisplay(dpy); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); if (_is_fullscreen) _desinit_fullscreen(); XUnmapWindow(dpy,_window); _window_x = _window_y = -1; _is_closed = true; XUnlockDisplay(dpy); return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; show(); XLockDisplay(dpy); XMoveWindow(dpy,_window,posx,posy); _window_x = posx; _window_y = posy; _is_moved = false; XUnlockDisplay(dpy); return paint(); } CImgDisplay& show_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); XUndefineCursor(dpy,_window); XUnlockDisplay(dpy); return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); const char pix_data[8] = { 0 }; XColor col; col.red = col.green = col.blue = 0; Pixmap pix = XCreateBitmapFromData(dpy,_window,pix_data,8,8); Cursor cur = XCreatePixmapCursor(dpy,pix,pix,&col,&col,0,0); XFreePixmap(dpy,pix); XDefineCursor(dpy,_window,cur); XUnlockDisplay(dpy); return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (is_empty() || _is_closed) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); XWarpPointer(dpy,0L,_window,0,0,0,0,posx,posy); _mouse_x = posx; _mouse_y = posy; _is_moved = false; XSync(dpy,0); XUnlockDisplay(dpy); return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char tmp[1024] = { 0 }; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,sizeof(tmp),format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) return *this; delete[] _title; const unsigned int s = std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); XStoreName(dpy,_window,tmp); XUnlockDisplay(dpy); return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(false); } CImgDisplay& paint(const bool wait_expose=true) { if (is_empty()) return *this; Display *const dpy = cimg::X11_attr().display; XLockDisplay(dpy); _paint(wait_expose); XUnlockDisplay(dpy); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img, const bool flag8=false) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d(img._width/2,img._height/2,img._depth/2)); if (cimg::X11_attr().nb_bits==8 && (img._width!=_width || img._height!=_height)) return render(img.get_resize(_width,_height,1,-100,1)); if (cimg::X11_attr().nb_bits==8 && !flag8 && img._spectrum==3) { static const CImg<typename CImg<T>::ucharT> default_colormap = CImg<typename CImg<T>::ucharT>::default_LUT256(); return render(img.get_index(default_colormap,1,false)); } Display *const dpy = cimg::X11_attr().display; const T *data1 = img._data, *data2 = (img._spectrum>1)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>2)?img.data(0,0,0,2):data1; if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); XLockDisplay(dpy); if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, no normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data:new unsigned char[(unsigned long)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) (*ptrd++) = (unsigned char)*(data1++); break; case 2 : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)*(data1++), G = (unsigned char)*(data2++), B = (unsigned char)*(data3++); (*ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, no normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data:new unsigned short[(unsigned long)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; *(ptrd++) = (val&M) | (G>>3); *(ptrd++) = (G<<5) | (G>>1); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++), G = val>>2; *(ptrd++) = (G<<5) | (G>>1); *(ptrd++) = (val&M) | (G>>3); } break; case 2 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; *(ptrd++) = ((unsigned char)*(data1++)&M) | (G>>3); *(ptrd++) = (G<<5); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; *(ptrd++) = (G<<5); *(ptrd++) = ((unsigned char)*(data1++)&M) | (G>>3); } break; default : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; *(ptrd++) = ((unsigned char)*(data1++)&M) | (G>>3); *(ptrd++) = (G<<5) | ((unsigned char)*(data3++)>>3); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)*(data2++)>>2; *(ptrd++) = (G<<5) | ((unsigned char)*(data3++)>>3); *(ptrd++) = ((unsigned char)*(data1++)&M) | (G>>3); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, no normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data:new unsigned int[(unsigned long)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8); else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8) | (unsigned char)*(data3++); else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data3++)<<24) | ((unsigned char)*(data2++)<<16) | ((unsigned char)*(data1++)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(ptrd++) = 0; *(ptrd++) = (unsigned char)*(data1++); *(ptrd++) = 0; *(ptrd++) = 0; } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(ptrd++) = 0; *(ptrd++) = 0; *(ptrd++) = (unsigned char)*(data1++); *(ptrd++) = 0; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(ptrd++) = 0; *(ptrd++) = (unsigned char)*(data2++); *(ptrd++) = (unsigned char)*(data1++); *(ptrd++) = 0; } break; default : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(ptrd++) = 0; *(ptrd++) = (unsigned char)*(data1++); *(ptrd++) = (unsigned char)*(data2++); *(ptrd++) = (unsigned char)*(data3++); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(ptrd++) = (unsigned char)*(data3++); *(ptrd++) = (unsigned char)*(data2++); *(ptrd++) = (unsigned char)*(data1++); *(ptrd++) = 0; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.0f); switch (cimg::X11_attr().nb_bits) { case 8 : { // 256 colormap, with normalization _set_colormap(_colormap,img._spectrum); unsigned char *const ndata = (img._width==_width && img._height==_height)?(unsigned char*)_data:new unsigned char[(unsigned long)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++)-_min)*mm); *(ptrd++) = R; } break; case 2 : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++)-_min)*mm), G = (unsigned char)((*(data2++)-_min)*mm); (*ptrd++) = (R&0xf0) | (G>>4); } break; default : for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++)-_min)*mm), G = (unsigned char)((*(data2++)-_min)*mm), B = (unsigned char)((*(data3++)-_min)*mm); *(ptrd++) = (R&0xe0) | ((G>>5)<<2) | (B>>6); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned char*)_data,_width,_height); delete[] ndata; } } break; case 16 : { // 16 bits colors, with normalization unsigned short *const ndata = (img._width==_width && img._height==_height)?(unsigned short*)_data:new unsigned short[(unsigned long)img._width*img._height]; unsigned char *ptrd = (unsigned char*)ndata; const unsigned int M = 248; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm), G = val>>2; *(ptrd++) = (val&M) | (G>>3); *(ptrd++) = (G<<5) | (val>>3); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm), G = val>>2; *(ptrd++) = (G<<5) | (val>>3); *(ptrd++) = (val&M) | (G>>3); } break; case 2 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++)-_min)*mm)>>2; *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)&M) | (G>>3); *(ptrd++) = (G<<5); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++)-_min)*mm)>>2; *(ptrd++) = (G<<5); *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)&M) | (G>>3); } break; default : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++)-_min)*mm)>>2; *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)&M) | (G>>3); *(ptrd++) = (G<<5) | ((unsigned char)((*(data3++)-_min)*mm)>>3); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char G = (unsigned char)((*(data2++)-_min)*mm)>>2; *(ptrd++) = (G<<5) | ((unsigned char)((*(data3++)-_min)*mm)>>3); *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)&M) | (G>>3); } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned short*)_data,_width,_height); delete[] ndata; } } break; default : { // 24 bits colors, with normalization unsigned int *const ndata = (img._width==_width && img._height==_height)?(unsigned int*)_data:new unsigned int[(unsigned long)img._width*img._height]; if (sizeof(int)==4) { // 32 bits int uses optimized version unsigned int *ptrd = ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm); *(ptrd++) = (val<<16) | (val<<8) | val; } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm); *(ptrd++) = (val<<24) | (val<<16) | (val<<8); } break; case 2 : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)<<16) | ((unsigned char)((*(data2++)-_min)*mm)<<8); else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data2++)-_min)*mm)<<16) | ((unsigned char)((*(data1++)-_min)*mm)<<8); break; default : if (cimg::X11_attr().byte_order==cimg::endianness()) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data1++)-_min)*mm)<<16) | ((unsigned char)((*(data2++)-_min)*mm)<<8) | (unsigned char)((*(data3++)-_min)*mm); else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)((*(data3++)-_min)*mm)<<24) | ((unsigned char)((*(data2++)-_min)*mm)<<16) | ((unsigned char)((*(data1++)-_min)*mm)<<8); } } else { unsigned char *ptrd = (unsigned char*)ndata; switch (img._spectrum) { case 1 : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm); (*ptrd++) = 0; (*ptrd++) = val; (*ptrd++) = val; (*ptrd++) = val; } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm); (*ptrd++) = val; (*ptrd++) = val; (*ptrd++) = val; (*ptrd++) = 0; } break; case 2 : if (cimg::X11_attr().byte_order) cimg::swap(data1,data2); for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { (*ptrd++) = 0; (*ptrd++) = (unsigned char)((*(data2++)-_min)*mm); (*ptrd++) = (unsigned char)((*(data1++)-_min)*mm); (*ptrd++) = 0; } break; default : if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { (*ptrd++) = 0; (*ptrd++) = (unsigned char)((*(data1++)-_min)*mm); (*ptrd++) = (unsigned char)((*(data2++)-_min)*mm); (*ptrd++) = (unsigned char)((*(data3++)-_min)*mm); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { (*ptrd++) = (unsigned char)((*(data3++)-_min)*mm); (*ptrd++) = (unsigned char)((*(data2++)-_min)*mm); (*ptrd++) = (unsigned char)((*(data1++)-_min)*mm); (*ptrd++) = 0; } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,(unsigned int*)_data,_width,_height); delete[] ndata; } } } } XUnlockDisplay(dpy); return *this; } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned char *ptrs = (unsigned char*)_data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); if (cimg::X11_attr().is_blue_first) cimg::swap(data1,data3); switch (cimg::X11_attr().nb_bits) { case 8 : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = *(ptrs++); *(data1++) = (T)(val&0xe0); *(data2++) = (T)((val&0x1c)<<3); *(data3++) = (T)(val<<6); } } break; case 16 : { if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val0 = *(ptrs++), val1 = *(ptrs++); *(data1++) = (T)(val0&0xf8); *(data2++) = (T)((val0<<5) | ((val1&0xe0)>>5)); *(data3++) = (T)(val1<<3); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned short val0 = *(ptrs++), val1 = *(ptrs++); *(data1++) = (T)(val1&0xf8); *(data2++) = (T)((val1<<5) | ((val0&0xe0)>>5)); *(data3++) = (T)(val0<<3); } } break; default : { if (cimg::X11_attr().byte_order) for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { ++ptrs; *(data1++) = (T)*(ptrs++); *(data2++) = (T)*(ptrs++); *(data3++) = (T)*(ptrs++); } else for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { *(data3++) = (T)*(ptrs++); *(data2++) = (T)*(ptrs++); *(data1++) = (T)*(ptrs++); ++ptrs; } } } return *this; } // Windows-based implementation. //------------------------------- #elif cimg_display==2 bool _is_mouse_tracked, _is_cursor_visible; HANDLE _thread, _is_created, _mutex; HWND _window, _background_window; CLIENTCREATESTRUCT _ccs; unsigned int *_data; DEVMODE _curr_mode; BITMAPINFO _bmi; HDC _hdc; static int screen_width() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return mode.dmPelsWidth; } static int screen_height() { DEVMODE mode; mode.dmSize = sizeof(DEVMODE); mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&mode); return mode.dmPelsHeight; } static void wait_all() { WaitForSingleObject(cimg::Win32_attr().wait_event,INFINITE); } static LRESULT APIENTRY _handle_events(HWND window,UINT msg,WPARAM wParam,LPARAM lParam) { #ifdef _WIN64 CImgDisplay *const disp = (CImgDisplay*)GetWindowLongPtr(window,GWLP_USERDATA); #else CImgDisplay *const disp = (CImgDisplay*)GetWindowLong(window,GWL_USERDATA); #endif MSG st_msg; switch (msg) { case WM_CLOSE : disp->_mouse_x = disp->_mouse_y = -1; disp->_window_x = disp->_window_y = 0; disp->set_button().set_key(0).set_key(0,false)._is_closed = true; ReleaseMutex(disp->_mutex); ShowWindow(disp->_window,SW_HIDE); disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); return 0; case WM_SIZE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const unsigned int nw = LOWORD(lParam),nh = HIWORD(lParam); if (nw && nh && (nw!=disp->_width || nh!=disp->_height)) { disp->_window_width = nw; disp->_window_height = nh; disp->_mouse_x = disp->_mouse_y = -1; disp->_is_resized = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_MOVE : { while (PeekMessage(&st_msg,window,WM_SIZE,WM_SIZE,PM_REMOVE)) {} WaitForSingleObject(disp->_mutex,INFINITE); const int nx = (int)(short)(LOWORD(lParam)), ny = (int)(short)(HIWORD(lParam)); if (nx!=disp->_window_x || ny!=disp->_window_y) { disp->_window_x = nx; disp->_window_y = ny; disp->_is_moved = disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } ReleaseMutex(disp->_mutex); } break; case WM_PAINT : disp->paint(); break; case WM_KEYDOWN : disp->set_key((unsigned int)wParam); SetEvent(cimg::Win32_attr().wait_event); break; case WM_KEYUP : disp->set_key((unsigned int)wParam,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MOUSEMOVE : { while (PeekMessage(&st_msg,window,WM_MOUSEMOVE,WM_MOUSEMOVE,PM_REMOVE)) {} disp->_mouse_x = LOWORD(lParam); disp->_mouse_y = HIWORD(lParam); #if (_WIN32_WINNT>=0x0400) && !defined(NOTRACKMOUSEEVENT) if (!disp->_is_mouse_tracked) { TRACKMOUSEEVENT tme; tme.cbSize = sizeof(TRACKMOUSEEVENT); tme.dwFlags = TME_LEAVE; tme.hwndTrack = disp->_window; if (TrackMouseEvent(&tme)) disp->_is_mouse_tracked = true; } #endif if (disp->_mouse_x<0 || disp->_mouse_y<0 || disp->_mouse_x>=disp->width() || disp->_mouse_y>=disp->height()) disp->_mouse_x = disp->_mouse_y = -1; disp->_is_event = true; SetEvent(cimg::Win32_attr().wait_event); } break; case WM_MOUSELEAVE : { disp->_mouse_x = disp->_mouse_y = -1; disp->_is_mouse_tracked = false; } break; case WM_LBUTTONDOWN : disp->set_button(1); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONDOWN : disp->set_button(2); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONDOWN : disp->set_button(3); SetEvent(cimg::Win32_attr().wait_event); break; case WM_LBUTTONUP : disp->set_button(1,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_RBUTTONUP : disp->set_button(2,false); SetEvent(cimg::Win32_attr().wait_event); break; case WM_MBUTTONUP : disp->set_button(3,false); SetEvent(cimg::Win32_attr().wait_event); break; case 0x020A : // WM_MOUSEWHEEL: disp->set_wheel((int)((short)HIWORD(wParam))/120); SetEvent(cimg::Win32_attr().wait_event); case WM_SETCURSOR : if (disp->_is_cursor_visible) ShowCursor(TRUE); else ShowCursor(FALSE); break; } return DefWindowProc(window,msg,wParam,lParam); } static DWORD WINAPI _events_thread(void* arg) { CImgDisplay *const disp = (CImgDisplay*)(((void**)arg)[0]); const char *const title = (const char*)(((void**)arg)[1]); MSG msg; delete[] (void**)arg; disp->_bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); disp->_bmi.bmiHeader.biWidth = disp->width(); disp->_bmi.bmiHeader.biHeight = -disp->height(); disp->_bmi.bmiHeader.biPlanes = 1; disp->_bmi.bmiHeader.biBitCount = 32; disp->_bmi.bmiHeader.biCompression = BI_RGB; disp->_bmi.bmiHeader.biSizeImage = 0; disp->_bmi.bmiHeader.biXPelsPerMeter = 1; disp->_bmi.bmiHeader.biYPelsPerMeter = 1; disp->_bmi.bmiHeader.biClrUsed = 0; disp->_bmi.bmiHeader.biClrImportant = 0; disp->_data = new unsigned int[(unsigned long)disp->_width*disp->_height]; if (!disp->_is_fullscreen) { // Normal window RECT rect; rect.left = rect.top = 0; rect.right = disp->_width-1; rect.bottom = disp->_height-1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (rect.right - rect.left + 1 - disp->_width)/2, border2 = rect.bottom - rect.top + 1 - disp->_height - border1; disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_OVERLAPPEDWINDOW | (disp->_is_closed?0:WS_VISIBLE), CW_USEDEFAULT,CW_USEDEFAULT, disp->_width + 2*border1, disp->_height + border1 + border2, 0,0,0,&(disp->_ccs)); if (!disp->_is_closed) { GetWindowRect(disp->_window,&rect); disp->_window_x = rect.left + border1; disp->_window_y = rect.top + border2; } else disp->_window_x = disp->_window_y = 0; } else { // Fullscreen window const unsigned int sx = screen_width(), sy = screen_height(); disp->_window = CreateWindowA("MDICLIENT",title?title:" ", WS_POPUP | (disp->_is_closed?0:WS_VISIBLE), (sx-disp->_width)/2, (sy-disp->_height)/2, disp->_width,disp->_height,0,0,0,&(disp->_ccs)); disp->_window_x = disp->_window_y = 0; } SetForegroundWindow(disp->_window); disp->_hdc = GetDC(disp->_window); disp->_window_width = disp->_width; disp->_window_height = disp->_height; disp->flush(); #ifdef _WIN64 SetWindowLongPtr(disp->_window,GWLP_USERDATA,(LONG_PTR)disp); SetWindowLongPtr(disp->_window,GWLP_WNDPROC,(LONG_PTR)_handle_events); #else SetWindowLong(disp->_window,GWL_USERDATA,(LONG)disp); SetWindowLong(disp->_window,GWL_WNDPROC,(LONG)_handle_events); #endif SetEvent(disp->_is_created); while (GetMessage(&msg,0,0,0)) DispatchMessage(&msg); return 0; } CImgDisplay& _update_window_pos() { if (_is_closed) _window_x = _window_y = -1; else { RECT rect; rect.left = rect.top = 0; rect.right = _width-1; rect.bottom = _height-1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (rect.right - rect.left + 1 - _width)/2, border2 = rect.bottom - rect.top + 1 - _height - border1; GetWindowRect(_window,&rect); _window_x = rect.left + border1; _window_y = rect.top + border2; } return *this; } void _init_fullscreen() { _background_window = 0; if (!_is_fullscreen || _is_closed) _curr_mode.dmSize = 0; else { DEVMODE mode; unsigned int imode = 0, ibest = 0, bestbpp = 0, bw = ~0U, bh = ~0U; for (mode.dmSize = sizeof(DEVMODE), mode.dmDriverExtra = 0; EnumDisplaySettings(0,imode,&mode); ++imode) { const unsigned int nw = mode.dmPelsWidth, nh = mode.dmPelsHeight; if (nw>=_width && nh>=_height && mode.dmBitsPerPel>=bestbpp && nw<=bw && nh<=bh) { bestbpp = mode.dmBitsPerPel; ibest = imode; bw = nw; bh = nh; } } if (bestbpp) { _curr_mode.dmSize = sizeof(DEVMODE); _curr_mode.dmDriverExtra = 0; EnumDisplaySettings(0,ENUM_CURRENT_SETTINGS,&_curr_mode); EnumDisplaySettings(0,ibest,&mode); ChangeDisplaySettings(&mode,0); } else _curr_mode.dmSize = 0; const unsigned int sx = screen_width(), sy = screen_height(); if (sx!=_width || sy!=_height) { CLIENTCREATESTRUCT background_ccs; _background_window = CreateWindowA("MDICLIENT","",WS_POPUP | WS_VISIBLE, 0,0,sx,sy,0,0,0,&background_ccs); SetForegroundWindow(_background_window); } } } void _desinit_fullscreen() { if (!_is_fullscreen) return; if (_background_window) DestroyWindow(_background_window); _background_window = 0; if (_curr_mode.dmSize) ChangeDisplaySettings(&_curr_mode,0); _is_fullscreen = false; } CImgDisplay& _assign(const unsigned int dimw, const unsigned int dimh, const char *const ptitle=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { // Allocate space for window title const char *const nptitle = ptitle?ptitle:""; const unsigned int s = (unsigned int)std::strlen(nptitle) + 1; char *const tmp_title = s?new char[s]:0; if (s) std::memcpy(tmp_title,nptitle,s*sizeof(char)); // Destroy previous window if existing if (!is_empty()) assign(); // Set display variables _width = cimg::min(dimw,(unsigned int)screen_width()); _height = cimg::min(dimh,(unsigned int)screen_height()); _normalization = normalization_type<4?normalization_type:3; _is_fullscreen = fullscreen_flag; _window_x = _window_y = 0; _is_closed = closed_flag; _is_cursor_visible = true; _is_mouse_tracked = false; _title = tmp_title; flush(); if (_is_fullscreen) _init_fullscreen(); // Create event thread void *const arg = (void*)(new void*[2]); ((void**)arg)[0] = (void*)this; ((void**)arg)[1] = (void*)_title; unsigned long ThreadID = 0; _mutex = CreateMutex(0,FALSE,0); _is_created = CreateEvent(0,FALSE,FALSE,0); _thread = CreateThread(0,0,_events_thread,arg,0,&ThreadID); WaitForSingleObject(_is_created,INFINITE); return *this; } CImgDisplay& assign() { if (is_empty()) return flush(); DestroyWindow(_window); TerminateThread(_thread,0); delete[] _data; delete[] _title; _data = 0; _title = 0; if (_is_fullscreen) _desinit_fullscreen(); _width = _height = _normalization = _window_width = _window_height = 0; _window_x = _window_y = 0; _is_fullscreen = false; _is_closed = true; _min = _max = 0; _title = 0; flush(); return *this; } CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!dimw || !dimh) return assign(); _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag); _min = _max = 0; std::memset(_data,0,sizeof(unsigned int)*_width*_height); return paint(); } template<typename T> CImgDisplay& assign(const CImg<T>& img, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!img) return assign(); CImg<T> tmp; const CImg<T>& nimg = (img._depth==1)?img:(tmp=img.get_projections2d(img._width/2,img._height/2,img._depth/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } template<typename T> CImgDisplay& assign(const CImgList<T>& list, const char *const title=0, const unsigned int normalization_type=3, const bool fullscreen_flag=false, const bool closed_flag=false) { if (!list) return assign(); CImg<T> tmp; const CImg<T> img = list>'x', &nimg = (img._depth==1)?img:(tmp=img.get_projections2d(img._width/2,img._height/2,img._depth/2)); _assign(nimg._width,nimg._height,title,normalization_type,fullscreen_flag,closed_flag); if (_normalization==2) _min = (float)nimg.min_max(_max); return display(nimg); } CImgDisplay& assign(const CImgDisplay& disp) { if (!disp) return assign(); _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed); std::memcpy(_data,disp._data,sizeof(unsigned int)*_width*_height); return paint(); } CImgDisplay& resize(const int nwidth, const int nheight, const bool force_redraw=true) { if (!nwidth || !nheight || (is_empty() && (nwidth<0 || nheight<0))) return assign(); if (is_empty()) return assign(nwidth,nheight); const unsigned int tmpdimx = (nwidth>0)?nwidth:(-nwidth*_width/100), tmpdimy = (nheight>0)?nheight:(-nheight*_height/100), dimx = tmpdimx?tmpdimx:1, dimy = tmpdimy?tmpdimy:1; if (_window_width!=dimx || _window_height!=dimy) { RECT rect; rect.left = rect.top = 0; rect.right = dimx - 1; rect.bottom = dimy - 1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int cwidth = rect.right - rect.left + 1, cheight = rect.bottom - rect.top + 1; SetWindowPos(_window,0,0,0,cwidth,cheight,SWP_NOMOVE | SWP_NOZORDER | SWP_NOCOPYBITS); } if (_width!=dimx || _height!=dimy) { unsigned int *const ndata = new unsigned int[dimx*dimy]; if (force_redraw) _render_resize(_data,_width,_height,ndata,dimx,dimy); else std::memset(ndata,0x80,sizeof(unsigned int)*dimx*dimy); delete[] _data; _data = ndata; _bmi.bmiHeader.biWidth = dimx; _bmi.bmiHeader.biHeight = -(int)dimy; _width = dimx; _height = dimy; } _window_width = dimx; _window_height = dimy; _is_resized = false; if (_is_fullscreen) move((screen_width()-_width)/2,(screen_height()-_height)/2); if (force_redraw) return paint(); return *this; } CImgDisplay& toggle_fullscreen(const bool force_redraw=true) { if (is_empty()) return *this; if (force_redraw) { const unsigned long buf_size = _width*_height*4UL; void *odata = std::malloc(buf_size); std::memcpy(odata,_data,buf_size); assign(_width,_height,_title,_normalization,!_is_fullscreen,false); std::memcpy(_data,odata,buf_size); std::free(odata); return paint(); } return assign(_width,_height,_title,_normalization,!_is_fullscreen,false); } CImgDisplay& show() { if (is_empty() || !_is_closed) return *this; _is_closed = false; if (_is_fullscreen) _init_fullscreen(); ShowWindow(_window,SW_SHOW); _update_window_pos(); return paint(); } CImgDisplay& close() { if (is_empty() || _is_closed) return *this; _is_closed = true; if (_is_fullscreen) _desinit_fullscreen(); ShowWindow(_window,SW_HIDE); _window_x = _window_y = 0; return *this; } CImgDisplay& move(const int posx, const int posy) { if (is_empty()) return *this; if (!_is_fullscreen) { RECT rect; rect.left = rect.top = 0; rect.right = _window_width-1; rect.bottom = _window_height-1; AdjustWindowRect(&rect,WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,false); const int border1 = (rect.right-rect.left+1-_width)/2, border2 = rect.bottom-rect.top+1-_height-border1; SetWindowPos(_window,0,posx-border1,posy-border2,0,0,SWP_NOSIZE | SWP_NOZORDER); } else SetWindowPos(_window,0,posx,posy,0,0,SWP_NOSIZE | SWP_NOZORDER); _window_x = posx; _window_y = posy; _is_moved = false; return show(); } CImgDisplay& show_mouse() { if (is_empty()) return *this; _is_cursor_visible = true; ShowCursor(TRUE); SendMessage(_window,WM_SETCURSOR,0,0); return *this; } CImgDisplay& hide_mouse() { if (is_empty()) return *this; _is_cursor_visible = false; ShowCursor(FALSE); SendMessage(_window,WM_SETCURSOR,0,0); return *this; } CImgDisplay& set_mouse(const int posx, const int posy) { if (_is_closed || posx<0 || posy<0) return *this; _update_window_pos(); const int res = (int)SetCursorPos(_window_x + posx,_window_y + posy); if (res) { _mouse_x = posx; _mouse_y = posy; } return *this; } CImgDisplay& set_title(const char *const format, ...) { if (is_empty()) return *this; char tmp[1024] = { 0 }; va_list ap; va_start(ap, format); cimg_vsnprintf(tmp,sizeof(tmp),format,ap); va_end(ap); if (!std::strcmp(_title,tmp)) return *this; delete[] _title; const unsigned int s = (unsigned int)std::strlen(tmp) + 1; _title = new char[s]; std::memcpy(_title,tmp,s*sizeof(char)); SetWindowTextA(_window, tmp); return *this; } template<typename T> CImgDisplay& display(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "display(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return assign(img); return render(img).paint(); } CImgDisplay& paint() { if (_is_closed) return *this; WaitForSingleObject(_mutex,INFINITE); SetDIBitsToDevice(_hdc,0,0,_width,_height,0,0,0,_height,_data,&_bmi,DIB_RGB_COLORS); ReleaseMutex(_mutex); return *this; } template<typename T> CImgDisplay& render(const CImg<T>& img) { if (!img) throw CImgArgumentException(_cimgdisplay_instance "render(): Empty specified image.", cimgdisplay_instance); if (is_empty()) return *this; if (img._depth!=1) return render(img.get_projections2d(img._width/2,img._height/2,img._depth/2)); const T *data1 = img._data, *data2 = (img._spectrum>=2)?img.data(0,0,0,1):data1, *data3 = (img._spectrum>=3)?img.data(0,0,0,2):data1; WaitForSingleObject(_mutex,INFINITE); unsigned int *const ndata = (img._width==_width && img._height==_height)?_data:new unsigned int[(unsigned long)img._width*img._height], *ptrd = ndata; if (!_normalization || (_normalization==3 && cimg::type<T>::string()==cimg::type<unsigned char>::string())) { _min = _max = 0; switch (img._spectrum) { case 1 : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)*(data1++); *(ptrd++) = (val<<16) | (val<<8) | val; } } break; case 2 : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8); } break; default : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) *(ptrd++) = ((unsigned char)*(data1++)<<16) | ((unsigned char)*(data2++)<<8) | (unsigned char)*(data3++); } } } else { if (_normalization==3) { if (cimg::type<T>::is_float()) _min = (float)img.min_max(_max); else { _min = (float)cimg::type<T>::min(); _max = (float)cimg::type<T>::max(); } } else if ((_min>_max) || _normalization==1) _min = (float)img.min_max(_max); const float delta = _max - _min, mm = 255/(delta?delta:1.0f); switch (img._spectrum) { case 1 : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char val = (unsigned char)((*(data1++)-_min)*mm); *(ptrd++) = (val<<16) | (val<<8) | val; } } break; case 2 : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++)-_min)*mm), G = (unsigned char)((*(data2++)-_min)*mm); *(ptrd++) = (R<<16) | (G<<8); } } break; default : { for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned char R = (unsigned char)((*(data1++)-_min)*mm), G = (unsigned char)((*(data2++)-_min)*mm), B = (unsigned char)((*(data3++)-_min)*mm); *(ptrd++) = (R<<16) | (G<<8) | B; } } } } if (ndata!=_data) { _render_resize(ndata,img._width,img._height,_data,_width,_height); delete[] ndata; } ReleaseMutex(_mutex); return *this; } template<typename T> const CImgDisplay& snapshot(CImg<T>& img) const { if (is_empty()) { img.assign(); return *this; } const unsigned int *ptrs = _data; img.assign(_width,_height,1,3); T *data1 = img.data(0,0,0,0), *data2 = img.data(0,0,0,1), *data3 = img.data(0,0,0,2); for (unsigned long xy = (unsigned long)img._width*img._height; xy>0; --xy) { const unsigned int val = *(ptrs++); *(data1++) = (T)(unsigned char)(val>>16); *(data2++) = (T)(unsigned char)((val>>8)&0xFF); *(data3++) = (T)(unsigned char)(val&0xFF); } return *this; } #endif //@} }; /* #-------------------------------------- # # # # Definition of the CImg<T> structure # # # #-------------------------------------- */ //! Class representing an image (up to 4 dimensions wide), each pixel being of type \c T. /** This is the main class of the %CImg Library. It declares and constructs an image, allows access to its pixel values, and is able to perform various image operations. \par Image representation A %CImg image is defined as an instance of the container \c CImg<T>, which contains a regular grid of pixels, each pixel value being of type \c T. The image grid can have up to 4 dimensions: width, height, depth and number of channels. Usually, the three first dimensions are used to describe spatial coordinates <tt>(x,y,z)</tt>, while the number of channels is rather used as a vector-valued dimension (it may describe the R,G,B color channels for instance). If you need a fifth dimension, you can use image lists \c CImgList<T> rather than simple images \c CImg<T>. Thus, the \c CImg<T> class is able to represent volumetric images of vector-valued pixels, as well as images with less dimensions (1d scalar signal, 2d color images, ...). Most member functions of the class CImg<\c T> are designed to handle this maximum case of (3+1) dimensions. Concerning the pixel value type \c T: fully supported template types are the basic C++ types: <tt>unsigned char, char, short, unsigned int, int, unsigned long, long, float, double, ... </tt>. Typically, fast image display can be done using <tt>CImg<unsigned char></tt> images, while complex image processing algorithms may be rather coded using <tt>CImg<float></tt> or <tt>CImg<double></tt> images that have floating-point pixel values. The default value for the template T is \c float. Using your own template types may be possible. However, you will certainly have to define the complete set of arithmetic and logical operators for your class. \par Image structure The \c CImg<T> structure contains \e six fields: - \c _width defines the number of \a columns of the image (size along the X-axis). - \c _height defines the number of \a rows of the image (size along the Y-axis). - \c _depth defines the number of \a slices of the image (size along the Z-axis). - \c _spectrum defines the number of \a channels of the image (size along the C-axis). - \c _data defines a \a pointer to the \a pixel \a data (of type \c T). - \c _is_shared is a boolean that tells if the memory buffer \c data is shared with another image. You can access these fields publicly although it is recommended to use the dedicated functions width(), height(), depth(), spectrum() and ptr() to do so. Image dimensions are not limited to a specific range (as long as you got enough available memory). A value of \e 1 usually means that the corresponding dimension is \a flat. If one of the dimensions is \e 0, or if the data pointer is null, the image is considered as \e empty. Empty images should not contain any pixel data and thus, will not be processed by CImg member functions (a CImgInstanceException will be thrown instead). Pixel data are stored in memory, in a non interlaced mode (See \ref cimg_storage). \par Image declaration and construction Declaring an image can be done by using one of the several available constructors. Here is a list of the most used: - Construct images from arbitrary dimensions: - <tt>CImg<char> img;</tt> declares an empty image. - <tt>CImg<unsigned char> img(128,128);</tt> declares a 128x128 greyscale image with \c unsigned \c char pixel values. - <tt>CImg<double> img(3,3);</tt> declares a 3x3 matrix with \c double coefficients. - <tt>CImg<unsigned char> img(256,256,1,3);</tt> declares a 256x256x1x3 (color) image (colors are stored as an image with three channels). - <tt>CImg<double> img(128,128,128);</tt> declares a 128x128x128 volumetric and greyscale image (with \c double pixel values). - <tt>CImg<> img(128,128,128,3);</tt> declares a 128x128x128 volumetric color image (with \c float pixels, which is the default value of the template parameter \c T). - \b Note: images pixels are <b>not automatically initialized to 0</b>. You may use the function \c fill() to do it, or use the specific constructor taking 5 parameters like this: <tt>CImg<> img(128,128,128,3,0);</tt> declares a 128x128x128 volumetric color image with all pixel values to 0. - Construct images from filenames: - <tt>CImg<unsigned char> img("image.jpg");</tt> reads a JPEG color image from the file "image.jpg". - <tt>CImg<float> img("analyze.hdr");</tt> reads a volumetric image (ANALYZE7.5 format) from the file "analyze.hdr". - \b Note: You need to install <a href="http://www.imagemagick.org">ImageMagick</a> to be able to read common compressed image formats (JPG,PNG, ...) (See \ref cimg_files_io). - Construct images from C-style arrays: - <tt>CImg<int> img(data_buffer,256,256);</tt> constructs a 256x256 greyscale image from a \c int* buffer \c data_buffer (of size 256x256=65536). - <tt>CImg<unsigned char> img(data_buffer,256,256,1,3,false);</tt> constructs a 256x256 color image from a \c unsigned \c char* buffer \c data_buffer (where R,G,B channels follow each others). - <tt>CImg<unsigned char> img(data_buffer,256,256,1,3,true);</tt> constructs a 256x256 color image from a \c unsigned \c char* buffer \c data_buffer (where R,G,B channels are multiplexed). The complete list of constructors can be found <a href="#constructors">here</a>. \par Most useful functions The \c CImg<T> class contains a lot of functions that operates on images. Some of the most useful are: - operator()(): allows to access or write pixel values. - display(): displays the image in a new window. **/ template<typename T> struct CImg { unsigned int _width, _height, _depth, _spectrum; bool _is_shared; T *_data; //! Simple iterator type, to loop through each pixel value of an image instance. /** \note - The \c CImg<T>::iterator type is defined to be a <tt>T*</tt>. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code CImg<float> img("reference.jpg"); // Load image from file. for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) *it = 0; // Set all pixels to '0', through a CImg iterator. img.fill(0); // Do the same with a built-in method. \endcode **/ typedef T* iterator; //! Simple const iterator type, to loop through each pixel value of a \c const image instance. /** \note - The \c CImg<T>::const_iterator type is defined to be a \c const \c T*. - You will seldom have to use iterators in %CImg, most classical operations being achieved (often in a faster way) using methods of \c CImg<T>. \par Example \code const CImg<float> img("reference.jpg"); // Load image from file. float sum = 0; for (CImg<float>::iterator it = img.begin(), it<img.end(); ++it) sum+=*it; // Compute sum of all pixel values, through a CImg iterator. const float sum2 = img.sum(); // Do the same with a built-in method. \endcode **/ typedef const T* const_iterator; //! Pixel value type. /** Refer to the type of the pixel values of an image instance. \note - The \c CImg<T>::value_type type of a \c CImg<T> is defined to be a \c T. - \c CImg<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common types related to template type T. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,unsigned long>::type Tulong; typedef typename cimg::superset<T,long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,unsigned long>::type ulongT; typedef typename cimg::last<T,long>::type longT; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimg_plugin #include cimg_plugin #endif #ifdef cimg_plugin1 #include cimg_plugin1 #endif #ifdef cimg_plugin2 #include cimg_plugin2 #endif #ifdef cimg_plugin3 #include cimg_plugin3 #endif #ifdef cimg_plugin4 #include cimg_plugin4 #endif #ifdef cimg_plugin5 #include cimg_plugin5 #endif #ifdef cimg_plugin6 #include cimg_plugin6 #endif #ifdef cimg_plugin7 #include cimg_plugin7 #endif #ifdef cimg_plugin8 #include cimg_plugin8 #endif //@} //--------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //--------------------------------------------------------- //! Destroy image. /** \note - The pixel buffer data() is deallocated if necessary, e.g. for non-empty and non-shared image instances. - Destroying an empty or shared image does nothing actually. \warning - When destroying a non-shared image, make sure that you will \e not operate on a remaining shared image that shares its buffer with the destroyed instance, in order to avoid further invalid memory access (to a deallocated buffer). **/ ~CImg() { if (!_is_shared) delete[] _data; } //! Construct empty image. /** \note - An empty image has no pixel data and all of its dimensions width(), height(), depth(), spectrum() are set to \c 0, as well as its pixel buffer pointer data(). - An empty image may be re-assigned afterwards, e.g. with the family of assign(unsigned int,unsigned int,unsigned int,unsigned int) methods, or by operator=(const CImg<t>&). In all cases, the type of pixels stays \c T. - An empty image is never shared. \par Example \code CImg<float> img1, img2; // Construct two empty images. img1.assign(256,256,1,3); // Re-assign 'img1' to be a 256x256x1x3 (color) image. img2 = img1.get_rand(0,255); // Re-assign 'img2' to be a random-valued version of 'img1'. img2.assign(); // Re-assign 'img2' to be an empty image again. \endcode **/ CImg():_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {} //! Construct image with specified size. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \note - It is able to create only \e non-shared images, and allocates thus a pixel buffer data() for each constructed image instance. - Setting one dimension \c size_x,\c size_y,\c size_z or \c size_c to \c 0 leads to the construction of an \e empty image. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values during construction (e.g. with \c 0), use constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) instead. \par Example \code CImg<float> img1(256,256,1,3); // Construct a 256x256x1x3 (color) image, filled with garbage values. CImg<float> img2(256,256,1,3,0); // Construct a 256x256x1x3 (color) image, filled with value '0'. \endcode **/ explicit CImg(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1): _is_shared(false) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values. /** \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value Initialization value. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with the specified \c value. \warning - It cannot be used to construct a vector-valued image and initialize it with \e vector-valued pixels (e.g. RGB vector, for color images). For this task, you may use fillC() after construction. **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T value): _is_shared(false) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } fill(value); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a sequence of integers. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of integers \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be an \e integer). \param value1 Second value of the initialization sequence (must be an \e integer). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with a sequence of specified integer values. \warning - You must specify \e exactly \c size_x*\c size_y*\c size_z*\c size_c integers in the initialization sequence. Otherwise, the constructor may crash or fill your image pixels with garbage. \par Example \code const CImg<float> img(2,2,1,3, // Construct a 2x2 color (RGB) image. 0,255,0,255, // Set the 4 values for the red component. 0,0,255,255, // Set the 4 values for the green component. 64,64,64,64); // Set the 4 values for the blue component. img.resize(150,150).display(); \endcode \image html ref_constructor1.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { #define _CImg_stdarg(img,a0,a1,N,t) { \ unsigned long _siz = (unsigned long)N; \ if (_siz--) { \ va_list ap; \ va_start(ap,a1); \ T *ptrd = (img)._data; \ *(ptrd++) = (T)a0; \ if (_siz--) { \ *(ptrd++) = (T)a1; \ for (; _siz; --_siz) *(ptrd++) = (T)va_arg(ap,t); \ } \ va_end(ap); \ } \ } assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(unsigned long)size_x*size_y*size_z*size_c,int); } //! Construct image with specified size and initialize pixel values from a sequence of doubles. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initialize pixel values from the specified sequence of doubles \c value0,\c value1,\c ... \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param value0 First value of the initialization sequence (must be a \e double). \param value1 Second value of the initialization sequence (must be a \e double). \param ... \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...), but takes a sequence of double values instead of integers. \warning - You must specify \e exactly \c dx*\c dy*\c dz*\c dc doubles in the initialization sequence. Otherwise, the constructor may crash or fill your image with garbage. For instance, the code below will probably crash on most platforms: \code const CImg<float> img(2,2,1,1, 0.5,0.5,255,255); // FAIL: The two last arguments are 'int', not 'double'! \endcode **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(unsigned long)size_x*size_y*size_z*size_c,double); } //! Construct image with specified size and initialize pixel values from a value string. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified string \c values. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param values Value string describing the way pixel values are set. \param repeat_values Tells if the value filling process is repeated over the image. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it also fills the pixel buffer with values described in the value string \c values. - Value string \c values may describe two different filling processes: - Either \c values is a sequences of values assigned to the image pixels, as in <tt>"1,2,3,7,8,2"</tt>. In this case, set \c repeat_values to \c true to periodically fill the image with the value sequence. - Either, \c values is a formula, as in <tt>"cos(x/10)*sin(y/20)"</tt>. In this case, parameter \c repeat_values is pointless. - For both cases, specifying \c repeat_values is mandatory. It disambiguates the possible overloading of constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T) with \c T being a <tt>const char*</tt>. - A \c CImgArgumentException is thrown when an invalid value string \c values is specified. \par Example \code const CImg<float> img1(129,129,1,3,"0,64,128,192,255",true), // Construct image filled from a value sequence. img2(129,129,1,3,"if(c==0,255*abs(cos(x/10)),1.8*y)",false); // Construct image filled from a formula. (img1,img2).display(); \endcode \image html ref_constructor2.jpg **/ CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values):_is_shared(false) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } fill(values,repeat_values); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer. /** Construct a new image instance of size \c size_x x \c size_y x \c size_z x \c size_c, with pixels of type \c T, and initializes pixel values from the specified \c t* memory buffer. \param values Pointer to the input memory buffer. \param size_x Image width(). \param size_y Image height(). \param size_z Image depth(). \param size_c Image spectrum() (number of channels). \param is_shared Tells if input memory buffer must be shared by the current instance. \note - If \c is_shared is \c false, the image instance allocates its own pixel buffer, and values from the specified input buffer are copied to the instance buffer. If buffer types \c T and \c t are different, a regular static cast is performed during buffer copy. - Otherwise, the image instance does \e not allocate a new buffer, and uses the input memory buffer as its own pixel buffer. This case requires that types \c T and \c t are the same. Later, destroying such a shared image will not deallocate the pixel buffer, this task being obviously charged to the initial buffer allocator. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. when requested size is too big for available memory). \warning - You must take care when operating on a shared image, since it may have an invalid pixel buffer pointer data() (e.g. already deallocated). \par Example \code unsigned char tab[256*256] = { 0 }; CImg<unsigned char> img1(tab,256,256,1,1,false), // Construct new non-shared image from buffer 'tab'. img2(tab,256,256,1,1,true); // Construct new shared-image from buffer 'tab'. tab[1024] = 255; // Here, 'img2' is indirectly modified, but not 'img1'. \endcode **/ template<typename t> CImg(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a (%u,%u,%u,%u) shared instance from a (%s*) buffer " "(pixel types are different).", cimg_instance, size_x,size_y,size_z,size_c,CImg<t>::pixel_type()); } const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_shared=false) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (values && siz) { _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(values); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } std::memcpy(_data,values,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image from reading an image file. /** Construct a new image instance with pixels of type \c T, and initialize pixel values with the data read from an image file. \param filename Filename, as a C-string. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it reads the image dimensions and pixel values from the specified image file. - The recognition of the image file format by %CImg higly depends on the tools installed on your system and on the external libraries you used to link your code against. - Considered pixel type \c T should better fit the file format specification, or data loss may occur during file load (e.g. constructing a \c CImg<unsigned char> from a float-valued image file). - A \c CImgIOException is thrown when the specified \c filename cannot be read, or if the file format is not recognized. \par Example \code const CImg<float> img("reference.jpg"); img.display(); \endcode \image html ref_image.jpg **/ explicit CImg(const char *const filename):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(filename); } //! Construct image copy. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance. \param img Input image to copy. \note - Constructed copy has the same size width() x height() x depth() x spectrum() and pixel values as the input image \c img. - If input image \c img is \e shared and if types \c T and \c t are the same, the constructed copy is also \e shared, and shares its pixel buffer with \c img. Modifying a pixel value in the constructed copy will thus also modifies it in the input image \c img. This behavior is needful to allow functions to return shared images. - Otherwise, the constructed copy allocates its own pixel buffer, and copies pixel values from the input image \c img into its buffer. The copied pixel values may be eventually statically casted if types \c T and \c t are different. - Constructing a copy from an image \c img when types \c t and \c T are the same is significantly faster than with different types. - A \c CImgInstanceException is thrown when the pixel buffer cannot be allocated (e.g. not enough available memory). **/ template<typename t> CImg(const CImg<t>& img):_is_shared(false) { const unsigned long siz = img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Construct image copy \specialization. CImg(const CImg<T>& img) { const unsigned long siz = img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = img._is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Advanced copy constructor. /** Construct a new image instance with pixels of type \c T, as a copy of an existing \c CImg<t> instance, while forcing the shared state of the constructed copy. \param img Input image to copy. \param is_shared Tells about the shared state of the constructed copy. \note - Similar to CImg(const CImg<t>&), except that it allows to decide the shared state of the constructed image, which does not depend anymore on the shared state of the input image \c img: - If \c is_shared is \c true, the constructed copy will share its pixel buffer with the input image \c img. For that case, the pixel types \c T and \c t \e must be the same. - If \c is_shared is \c false, the constructed copy will allocate its own pixel buffer, whether the input image \c img is shared or not. - A \c CImgArgumentException is thrown when a shared copy is requested with different pixel types \c T and \c t. **/ template<typename t> CImg(const CImg<t>& img, const bool is_shared):_is_shared(false) { if (is_shared) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgArgumentException(_cimg_instance "CImg(): Invalid construction request of a shared instance from a " "CImg<%s> image (%u,%u,%u,%u,%p) (pixel types are different).", cimg_instance, CImg<t>::pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data); } const unsigned long siz = img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } const t *ptrs = img._data; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); } else { _width = _height = _depth = _spectrum = 0; _data = 0; } } //! Advanced copy constructor \specialization. CImg(const CImg<T>& img, const bool is_shared) { const unsigned long siz = img.size(); if (img._data && siz) { _width = img._width; _height = img._height; _depth = img._depth; _spectrum = img._spectrum; _is_shared = is_shared; if (_is_shared) _data = const_cast<T*>(img._data); else { try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*img._width*img._height*img._depth*img._spectrum), img._width,img._height,img._depth,img._spectrum); } std::memcpy(_data,img._data,siz*sizeof(T)); } } else { _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; } } //! Construct image with dimensions borrowed from another image. /** Construct a new image instance with pixels of type \c T, and size get from some dimensions of an existing \c CImg<t> instance. \param img Input image from which dimensions are borrowed. \param dimensions C-string describing the image size along the X,Y,Z and C-dimensions. \note - Similar to CImg(unsigned int,unsigned int,unsigned int,unsigned int), but it takes the image dimensions (\e not its pixel values) from an existing \c CImg<t> instance. - The allocated pixel buffer is \e not filled with a default value, and is likely to contain garbage values. In order to initialize pixel values (e.g. with \c 0), use constructor CImg(const CImg<t>&,const char*,T) instead. \par Example \code const CImg<float> img1(256,128,1,3), // 'img1' is a 256x128x1x3 image. img2(img1,"xyzc"), // 'img2' is a 256x128x1x3 image. img3(img1,"y,x,z,c"), // 'img3' is a 128x256x1x3 image. img4(img1,"c,x,y,3",0), // 'img4' is a 3x128x256x3 image (with pixels initialized to '0'). \endcode **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions); } //! Construct image with dimensions borrowed from another image and initialize pixel values. /** Construct a new image instance with pixels of type \c T, and size get from the dimensions of an existing \c CImg<t> instance, and set all pixel values to specified \c value. \param img Input image from which dimensions are borrowed. \param dimensions String describing the image size along the X,Y,Z and V-dimensions. \param value Value used for initialization. \note - Similar to CImg(const CImg<t>&,const char*), but it also fills the pixel buffer with the specified \c value. **/ template<typename t> CImg(const CImg<t>& img, const char *const dimensions, const T value): _width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { assign(img,dimensions).fill(value); } //! Construct image from a display window. /** Construct a new image instance with pixels of type \c T, as a snapshot of an existing \c CImgDisplay instance. \param disp Input display window. \note - The width() and height() of the constructed image instance are the same as the specified \c CImgDisplay. - The depth() and spectrum() of the constructed image instance are respectively set to \c 1 and \c 3 (i.e. a 2d color image). - The image pixels are read as 8-bits RGB values. **/ explicit CImg(const CImgDisplay &disp):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) { disp.snapshot(*this); } //! Construct empty image \inplace. /** In-place version of the default constructor CImg(). It simply resets the instance to an empty image. **/ CImg<T>& assign() { if (!_is_shared) delete[] _data; _width = _height = _depth = _spectrum = 0; _is_shared = false; _data = 0; return *this; } //! Construct image with specified size \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (!siz) return assign(); const unsigned long curr_siz = size(); if (siz!=curr_siz) { if (_is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignement request of shared instance from specified image (%u,%u,%u,%u).", cimg_instance, size_x,size_y,size_z,size_c); else { delete[] _data; try { _data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } } } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; return *this; } //! Construct image with specified size and initialize pixel values \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,T). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const T value) { return assign(size_x,size_y,size_z,size_c).fill(value); } //! Construct image with specified size and initialize pixel values from a sequence of integers \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,int,int,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const int value0, const int value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(unsigned long)size_x*size_y*size_z*size_c,int); return *this; } //! Construct image with specified size and initialize pixel values from a sequence of doubles \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,double,double,...). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const double value0, const double value1, ...) { assign(size_x,size_y,size_z,size_c); _CImg_stdarg(*this,value0,value1,(unsigned long)size_x*size_y*size_z*size_c,double); return *this; } //! Construct image with specified size and initialize pixel values from a value string \inplace. /** In-place version of the constructor CImg(unsigned int,unsigned int,unsigned int,unsigned int,const char*,bool). **/ CImg<T>& assign(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const char *const values, const bool repeat_values) { return assign(size_x,size_y,size_z,size_c).fill(values,repeat_values); } //! Construct image with specified size and initialize pixel values from a memory buffer \inplace. /** In-place version of the constructor CImg(const t*,unsigned int,unsigned int,unsigned int,unsigned int). **/ template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); assign(size_x,size_y,size_z,size_c); const t *ptrs = values; cimg_for(*this,ptrd,T) *ptrd = (T)*(ptrs++); return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \specialization. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (!values || !siz) return assign(); const unsigned long curr_siz = size(); if (values==_data && siz==curr_siz) return assign(size_x,size_y,size_z,size_c); if (_is_shared || values+siz<_data || values>=_data+size()) { assign(size_x,size_y,size_z,size_c); if (_is_shared) std::memmove(_data,values,siz*sizeof(T)); else std::memcpy(_data,values,siz*sizeof(T)); } else { T *new_data = 0; try { new_data = new T[siz]; } catch (...) { _width = _height = _depth = _spectrum = 0; _data = 0; throw CImgInstanceException(_cimg_instance "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).", cimg_instance, cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),size_x,size_y,size_z,size_c); } std::memcpy(new_data,values,siz*sizeof(T)); delete[] _data; _data = new_data; _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; } return *this; } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. template<typename t> CImg<T>& assign(const t *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { if (is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignment request of shared instance from (%s*) buffer" "(pixel types are different).", cimg_instance, CImg<t>::pixel_type()); return assign(values,size_x,size_y,size_z,size_c); } //! Construct image with specified size and initialize pixel values from a memory buffer \overloading. CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_shared) { const unsigned long siz = (unsigned long)size_x*size_y*size_z*size_c; if (!values || !siz) { if (is_shared) throw CImgArgumentException(_cimg_instance "assign(): Invalid assignment request of shared instance from (null) or empty buffer.", cimg_instance); else return assign(); } if (!is_shared) { if (_is_shared) assign(); assign(values,size_x,size_y,size_z,size_c); } else { if (!_is_shared) { if (values+siz<_data || values>=_data+size()) assign(); else cimg::warn(_cimg_instance "assign(): Shared image instance has overlapping memory.", cimg_instance); } _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c; _is_shared = true; _data = const_cast<T*>(values); } return *this; } //! Construct image from reading an image file \inplace. /** In-place version of the constructor CImg(const char*). **/ CImg<T>& assign(const char *const filename) { return load(filename); } //! Construct image copy \inplace. /** In-place version of the constructor CImg(const CImg<t>&). **/ template<typename t> CImg<T>& assign(const CImg<t>& img) { return assign(img._data,img._width,img._height,img._depth,img._spectrum); } //! In-place version of the advanced copy constructor. /** In-place version of the constructor CImg(const CImg<t>&,bool). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const bool is_shared) { return assign(img._data,img._width,img._height,img._depth,img._spectrum,is_shared); } //! Construct image with dimensions borrowed from another image \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions) { if (!dimensions || !*dimensions) return assign(img._width,img._height,img._depth,img._spectrum); unsigned int siz[4] = { 0,1,1,1 }, k = 0; for (const char *s = dimensions; *s && k<4; ++k) { char item[256] = { 0 }; if (std::sscanf(s,"%255[^0-9%xyzvwhdcXYZVWHDC]",item)>0) s+=std::strlen(item); if (*s) { unsigned int val = 0; char sep = 0; if (std::sscanf(s,"%u%c",&val,&sep)>0) { if (sep=='%') siz[k] = val*(k==0?_width:k==1?_height:k==2?_depth:_spectrum)/100; else siz[k] = val; while (*s>='0' && *s<='9') ++s; if (sep=='%') ++s; } else switch (cimg::uncase(*s)) { case 'x' : case 'w' : siz[k] = img._width; ++s; break; case 'y' : case 'h' : siz[k] = img._height; ++s; break; case 'z' : case 'd' : siz[k] = img._depth; ++s; break; case 'c' : case 's' : siz[k] = img._spectrum; ++s; break; default : throw CImgArgumentException(_cimg_instance "assign(): Invalid character '%c' detected in specified dimension string '%s'.", cimg_instance, *s,dimensions); } } } return assign(siz[0],siz[1],siz[2],siz[3]); } //! Construct image with dimensions borrowed from another image and initialize pixel values \inplace. /** In-place version of the constructor CImg(const CImg<t>&,const char*,T). **/ template<typename t> CImg<T>& assign(const CImg<t>& img, const char *const dimensions, const T value) { return assign(img,dimensions).fill(value); } //! Construct image from a display window \inplace. /** In-place version of the constructor CImg(const CImgDisplay&). **/ CImg<T>& assign(const CImgDisplay &disp) { disp.snapshot(*this); return *this; } //! Construct empty image \inplace. /** Equivalent to assign(). \note - It has been defined for compatibility with STL naming conventions. **/ CImg<T>& clear() { return assign(); } //! Transfer content of an image instance into another one. /** Transfer the dimensions and the pixel buffer content of an image instance into another one, and replace instance by an empty image. It avoids the copy of the pixel buffer when possible. \param img Destination image. \note - Pixel types \c T and \c t of source and destination images can be different, though the process is designed to be instantaneous when \c T and \c t are the same. \par Example \code CImg<float> src(256,256,1,3,0), // Construct a 256x256x1x3 (color) image filled with value '0'. dest(16,16); // Construct a 16x16x1x1 (scalar) image. src.move_to(dest); // Now, 'src' is empty and 'dest' is the 256x256x1x3 image. \endcode **/ template<typename t> CImg<t>& move_to(CImg<t>& img) { img.assign(*this); assign(); return img; } //! Transfer content of an image instance into another one \specialization. CImg<T>& move_to(CImg<T>& img) { if (_is_shared || img._is_shared) img.assign(*this); else swap(img); assign(); return img; } //! Transfer content of an image instance into a new image in an image list. /** Transfer the dimensions and the pixel buffer content of an image instance into a newly inserted image at position \c pos in specified \c CImgList<t> instance. \param list Destination list. \param pos Position of the newly inserted image in the list. \note - When optionnal parameter \c pos is ommited, the image instance is transfered as a new image at the end of the specified \c list. - It is convenient to sequentially insert new images into image lists, with no additional copies of memory buffer. \par Example \code CImgList<float> list; // Construct an empty image list. CImg<float> img("reference.jpg"); // Read image from filename. img.move_to(list); // Transfer image content as a new item in the list (no buffer copy). \endcode **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos=~0U) { const unsigned int npos = pos>list._width?list._width:pos; move_to(list.insert(1,npos)[npos]); return list; } //! Swap fields of two image instances. /** \param img Image to swap fields with. \note - It can be used to interchange the content of two images in a very fast way. Can be convenient when dealing with algorithms requiring two swapping buffers. \par Example \code CImg<float> img1("lena.jpg"), img2("milla.jpg"); img1.swap(img2); // Now, 'img1' is 'milla' and 'img2' is 'lena'. \endcode **/ CImg<T>& swap(CImg<T>& img) { cimg::swap(_width,img._width); cimg::swap(_height,img._height); cimg::swap(_depth,img._depth); cimg::swap(_spectrum,img._spectrum); cimg::swap(_data,img._data); cimg::swap(_is_shared,img._is_shared); return img; } //! Return a reference to an empty image. /** \note This function is useful mainly to declare optional parameters having type \c CImg<T> in functions prototypes, e.g. \code void f(const int x=0, const int y=0, const CImg<float>& img=CImg<float>::empty()); \endcode **/ static CImg<T>& empty() { static CImg<T> _empty; return _empty.assign(); } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Access to a pixel value. /** Return a reference to a located pixel value of the image instance, being possibly \e const, whether the image instance is \e const or not. This is the standard method to get/set pixel values in \c CImg<T> images. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Range of pixel coordinates start from <tt>(0,0,0,0)</tt> to <tt>(width()-1,height()-1,depth()-1,spectrum()-1)</tt>. - Due to the particular arrangement of the pixel buffers defined in %CImg, you can omit one coordinate if the corresponding dimension is equal to \c 1. For instance, pixels of a 2d image (depth() equal to \c 1) can be accessed by <tt>img(x,y,c)</tt> instead of <tt>img(x,y,0,c)</tt>. \warning - There is \e no boundary checking done in this operator, to make it as fast as possible. You \e must take care of out-of-bounds access by yourself, if necessary. For debuging purposes, you may want to define macro \c 'cimg_verbosity'>=3 to enable additional boundary checking operations in this operator. In that case, warning messages will be printed on the error output when accessing out-of-bounds pixels. \par Example \code CImg<float> img(100,100,1,3,0); // Construct a 100x100x1x3 (color) image with pixels set to '0'. const float valR = img(10,10,0,0), // Read red value at coordinates (10,10). valG = img(10,10,0,1), // Read green value at coordinates (10,10) valB = img(10,10,2), // Read blue value at coordinates (10,10) (Z-coordinate can be omitted). avg = (valR + valG + valB)/3; // Compute average pixel value. img(10,10,0) = img(10,10,1) = img(10,10,2) = avg; // Replace the color pixel (10,10) by the average grey value. \endcode **/ #if cimg_verbosity>=3 T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const unsigned long off = (unsigned long)offset(x,y,z,c); if (!_data || off>=size()) { cimg::warn(_cimg_instance "operator(): Invalid pixel request, at coordinates (%u,%u,%u,%u) [offset=%u].", cimg_instance, x,y,z,c,off); return *_data; } else return _data[off]; } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->operator()(x,y,z,c); } //! Access to a pixel value. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param wh Precomputed offset, must be equal to <tt>width()*\ref height()</tt>. \param whd Precomputed offset, must be equal to <tt>width()*\ref height()*\ref depth()</tt>. \note - Similar to (but faster than) operator()(). It uses precomputed offsets to optimize memory access. You may use it to optimize the reading/writing of several pixel values in the same image (e.g. in a loop). **/ T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const unsigned long wh, const unsigned long whd=0) { cimg::unused(wh,whd); return (*this)(x,y,z,c); } //! Access to a pixel value \const. const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const unsigned long wh, const unsigned long whd=0) const { cimg::unused(wh,whd); return (*this)(x,y,z,c); } #else T& operator()(const unsigned int x) { return _data[x]; } const T& operator()(const unsigned int x) const { return _data[x]; } T& operator()(const unsigned int x, const unsigned int y) { return _data[x + y*_width]; } const T& operator()(const unsigned int x, const unsigned int y) const { return _data[x + y*_width]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) { return _data[x + y*(unsigned long)_width + z*(unsigned long)_width*_height]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z) const { return _data[x + y*(unsigned long)_width + z*(unsigned long)_width*_height]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) { return _data[x + y*(unsigned long)_width + z*(unsigned long)_width*_height + c*(unsigned long)_width*_height*_depth]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c) const { return _data[x + y*(unsigned long)_width + z*(unsigned long)_width*_height + c*(unsigned long)_width*_height*_depth]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const unsigned long wh) { return _data[x + y*_width + z*wh]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int, const unsigned long wh) const { return _data[x + y*_width + z*wh]; } T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const unsigned long wh, const unsigned long whd) { return _data[x + y*_width + z*wh + c*whd]; } const T& operator()(const unsigned int x, const unsigned int y, const unsigned int z, const unsigned int c, const unsigned long wh, const unsigned long whd) const { return _data[x + y*_width + z*wh + c*whd]; } #endif //! Implicitely cast an image into a \c T*. /** Implicitely cast a \c CImg<T> instance into a \c T* or \c const \c T* pointer, whether the image instance is \e const or not. The returned pointer points on the first value of the image pixel buffer. \note - It simply returns the pointer data() to the pixel buffer. - This implicit conversion is convenient to test the empty state of images (data() being \c 0 in this case), e.g. \code CImg<float> img1(100,100), img2; // 'img1' is a 100x100 image, 'img2' is an empty image. if (img1) { // Test succeeds, 'img1' is not an empty image. if (!img2) { // Test succeeds, 'img2' is an empty image. std::printf("'img1' is not empty, 'img2' is empty."); } } \endcode - It also allows to use brackets to access pixel values, without need for a \c CImg<T>::operator[](), e.g. \code CImg<float> img(100,100); const float value = img[99]; // Access to value of the last pixel on the first row. img[510] = 255; // Set pixel value at (10,5). \endcode **/ operator T*() { return _data; } //! Implicitely cast an image into a \c T* \const. operator const T*() const { return _data; } //! Assign a value to all image pixels. /** Assign specified \c value to each pixel value of the image instance. \param value Value that will be assigned to image pixels. \note - The image size is never modified. - The \c value may be casted to pixel type \c T if necessary. \par Example \code CImg<char> img(100,100); // Declare image (with garbage values). img = 0; // Set all pixel values to '0'. img = 1.2; // Set all pixel values to '1' (cast of '1.2' as a 'char'). \endcode **/ CImg<T>& operator=(const T value) { return fill(value); } //! Assign pixels values from a specified expression. /** Initialize all pixel values from the specified string \c expression. \param expression Value string describing the way pixel values are set. \note - String parameter \c expression may describe different things: - If \c expression is a list of values (as in \c "1,2,3,8,3,2"), or a formula (as in \c "(x*y)%255"), the pixel values are set from specified \c expression and the image size is not modified. - If \c expression is a filename (as in \c "reference.jpg"), the corresponding image file is loaded and replace the image instance. The image size is modified if necessary. \par Example \code CImg<float> img1(100,100), img2(img1), img3(img1); // Declare three 100x100 scalar images with unitialized pixel values. img1 = "0,50,100,150,200,250,200,150,100,50"; // Set pixel values of 'img1' from a value sequence. img2 = "10*((x*y)%25)"; // Set pixel values of 'img2' from a formula. img3 = "reference.jpg"; // Set pixel values of 'img3' from a file (image size is modified). (img1,img2,img3).display(); \endcode \image html ref_operator_eq.jpg **/ CImg<T>& operator=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; load(expression); } cimg::exception_mode() = omode; return *this; } //! Copy an image into the current image instance. /** Similar to the in-place copy constructor assign(const CImg<t>&). **/ template<typename t> CImg<T>& operator=(const CImg<t>& img) { return assign(img); } //! Copy an image into the current image instance \specialization. CImg<T>& operator=(const CImg<T>& img) { return assign(img); } //! Copy the content of a display window to the current image instance. /** Similar to assign(const CImgDisplay&). **/ CImg<T>& operator=(const CImgDisplay& disp) { disp.snapshot(*this); return *this; } //! In-place addition operator. /** Add specified \c value to all pixels of an image instance. \param value Value to add. \note - Resulting pixel values are casted to fit the pixel type \c T. For instance, adding \c 0.2 to a \c CImg<char> is possible but does nothing indeed. - Overflow values are treated as with standard C++ numeric types. For instance, \code CImg<unsigned char> img(100,100,1,1,255); // Construct a 100x100 image with pixel values '255'. img+=1; // Add '1' to each pixels -> Overflow. // here all pixels of image 'img' are equal to '0'. \endcode - To prevent value overflow, you may want to consider pixel type \c T as \c float or \c double, and use cut() after addition. \par Example \code CImg<unsigned char> img1("reference.jpg"); // Load a 8-bits RGB image (values in [0,255]). CImg<float> img2(img1); // Construct a float-valued copy of 'img1'. img2+=100; // Add '100' to pixel values -> goes out of [0,255] but no problems with floats. img2.cut(0,255); // Cut values in [0,255] to fit the 'unsigned char' constraint. img1 = img2; // Rewrite safe result in 'unsigned char' version 'img1'. const CImg<unsigned char> img3 = (img1 + 100).cut(0,255); // Do the same in a more simple and elegant way. (img1,img2,img3).display(); \endcode \image html ref_operator_plus.jpg **/ template<typename t> CImg<T>& operator+=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(*ptrd + value); return *this; } //! In-place addition operator. /** Add values to image pixels, according to the specified string \c expression. \param expression Value string describing the way pixel values are added. \note - Similar to operator=(const char*), except that it adds values to the pixels of the current image instance, instead of assigning them. **/ CImg<T>& operator+=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator+="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)(*ptrd + mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this+=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place addition operator. /** Add values to image pixels, according to the values of the input image \c img. \param img Input image to add. \note - The size of the image instance is never modified. - It is not mandatory that input image \c img has the same size as the image instance. If less values are available in \c img, then the values are added cyclically. For instance, adding one WxH scalar image (spectrum() equal to \c 1) to one WxH color image (spectrum() equal to \c 3) means each color channel will be incremented with the same values at the same locations. \par Example \code CImg<float> img1("reference.jpg"); // Load a RGB color image (img1.spectrum()==3) const CImg<float> img2(img1.width(),img.height(),1,1,"255*(x/w)^2"); // Construct a scalar shading (img2.spectrum()==1). img1+=img2; // Add shading to each channel of 'img1'. img1.cut(0,255); // Prevent [0,255] overflow. (img2,img1).display(); \endcode \image html ref_operator_plus1.jpg **/ template<typename t> CImg<T>& operator+=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this+=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd + *(ptrs++)); } return *this; } //! In-place increment operator (prefix). /** Add \c 1 to all image pixels, and return a reference to the current incremented image instance. \note - Writing \c ++img is equivalent to \c img+=1. **/ CImg<T>& operator++() { cimg_for(*this,ptrd,T) ++*ptrd; return *this; } //! In-place increment operator (postfix). /** Add \c 1 to all image pixels, and return a new copy of the initial (pre-incremented) image instance. \note - Use the prefixed version operator++() if you don't need a copy of the initial (pre-incremented) image instance, since a useless image copy may be expensive in terms of memory usage. **/ CImg<T> operator++(int) { const CImg<T> copy(*this,false); ++*this; return copy; } //! Return a non-shared copy of the image instance. /** \note - Use this operator to ensure you get a non-shared copy of an image instance with same pixel type \c T. Indeed, the usual copy constructor CImg<T>(const CImg<T>&) returns a shared copy of a shared input image, and it may be not desirable to work on a regular copy (e.g. for a resize operation) if you have no informations about the shared state of the input image. - Writing \c (+img) is equivalent to \c CImg<T>(img,false). **/ CImg<T> operator+() const { return CImg<T>(*this,false); } //! Addition operator. /** Similar to operator+=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const t value) const { return CImg<_cimg_Tt>(*this,false)+=value; } //! Addition operator. /** Similar to operator+=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator+(const char *const expression) const { return CImg<Tfloat>(*this,false)+=expression; } //! Addition operator. /** Similar to operator+=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator+(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)+=img; } //! In-place substraction operator. /** Similar to operator+=(const t), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(*ptrd - value); return *this; } //! In-place substraction operator. /** Similar to operator+=(const char*), except that it performs a substraction instead of an addition. **/ CImg<T>& operator-=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator-="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)(*ptrd - mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this-=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place substraction operator. /** Similar to operator+=(const CImg<t>&), except that it performs a substraction instead of an addition. **/ template<typename t> CImg<T>& operator-=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this-=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd - *(ptrs++)); } return *this; } //! In-place decrement operator (prefix). /** Similar to operator++(), except that it performs a decrement instead of an increment. **/ CImg<T>& operator--() { cimg_for(*this,ptrd,T) *ptrd = *ptrd-(T)1; return *this; } //! In-place decrement operator (postfix). /** Similar to operator++(int), except that it performs a decrement instead of an increment. **/ CImg<T> operator--(int) { const CImg<T> copy(*this,false); --*this; return copy; } //! Replace each pixel by its opposite value. /** \note - If the computed opposite values are out-of-range, they are treated as with standard C++ numeric types. For instance, the \c unsigned \c char opposite of \c 1 is \c 255. \par Example \code const CImg<unsigned char> img1("reference.jpg"), // Load a RGB color image. img2 = -img1; // Compute its opposite (in 'unsigned char'). (img1,img2).display(); \endcode \image html ref_operator_minus.jpg **/ CImg<T> operator-() const { return CImg<T>(_width,_height,_depth,_spectrum,(T)0)-=*this; } //! Substraction operator. /** Similar to operator-=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const t value) const { return CImg<_cimg_Tt>(*this,false)-=value; } //! Substraction operator. /** Similar to operator-=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator-(const char *const expression) const { return CImg<Tfloat>(*this,false)-=expression; } //! Substraction operator. /** Similar to operator-=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator-(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)-=img; } //! In-place multiplication operator. /** Similar to operator+=(const t), except that it performs a multiplication instead of an addition. **/ template<typename t> CImg<T>& operator*=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(*ptrd * value); return *this; } //! In-place multiplication operator. /** Similar to operator+=(const char*), except that it performs a multiplication instead of an addition. **/ CImg<T>& operator*=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator*="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)(*ptrd * mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; mul(CImg<T>(_width,_height,_depth,_spectrum,expression,true)); } cimg::exception_mode() = omode; return *this; } //! In-place multiplication operator. /** Replace the image instance by the matrix multiplication between the image instance and the specified matrix \c img. \param img Second operand of the matrix multiplication. \note - It does \e not compute a pointwise multiplication between two images. For this purpose, use mul(const CImg<t>&) instead. - The size of the image instance can be modified by this operator. \par Example \code CImg<float> A(2,2,1,1, 1,2,3,4); // Construct 2x2 matrix A = [1,2;3,4]. const CImg<float> X(1,2,1,1, 1,2); // Construct 1x2 vector X = [1;2]. A*=X; // Assign matrix multiplication A*X to 'A'. // 'A' is now a 1x2 vector whose values are [5;11]. \endcode **/ template<typename t> CImg<T>& operator*=(const CImg<t>& img) { return ((*this)*img).move_to(*this); } //! Multiplication operator. /** Similar to operator*=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const t value) const { return CImg<_cimg_Tt>(*this,false)*=value; } //! Multiplication operator. /** Similar to operator*=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator*(const char *const expression) const { return CImg<Tfloat>(*this,false)*=expression; } //! Multiplication operator. /** Similar to operator*=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator*(const CImg<t>& img) const { if (_width!=img._height || _depth!=1 || _spectrum!=1) throw CImgArgumentException(_cimg_instance "operator*(): Invalid multiplication of instance by specified matrix (%u,%u,%u,%u,%p)", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); CImg<_cimg_Tt> res(img._width,_height); _cimg_Ttdouble value; #ifdef cimg_use_openmp #pragma omp parallel for if (size()>=1000 && img.size()>=1000) private(value) cimg_forXY(res,i,j) { value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); res(i,j) = (_cimg_Tt)value; } #else _cimg_Tt *ptrd = res._data; cimg_forXY(res,i,j) { value = 0; cimg_forX(*this,k) value+=(*this)(k,j)*img(i,k); *(ptrd++) = (_cimg_Tt)value; } #endif return res; } //! In-place division operator. /** Similar to operator+=(const t), except that it performs a division instead of an addition. **/ template<typename t> CImg<T>& operator/=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(*ptrd / value); return *this; } //! In-place division operator. /** Similar to operator+=(const char*), except that it performs a division instead of an addition. **/ CImg<T>& operator/=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator/="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)(*ptrd / mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; div(CImg<T>(_width,_height,_depth,_spectrum,expression,true)); } cimg::exception_mode() = omode; return *this; } //! In-place division operator. /** Replace the image instance by the (right) matrix division between the image instance and the specified matrix \c img. \param img Second operand of the matrix division. \note - It does \e not compute a pointwise division between two images. For this purpose, use div(const CImg<t>&) instead. - It returns the matrix operation \c A*inverse(img). - The size of the image instance can be modified by this operator. **/ template<typename t> CImg<T>& operator/=(const CImg<t>& img) { return (*this*img.get_invert()).move_to(*this); } //! Division operator. /** Similar to operator/=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const t value) const { return CImg<_cimg_Tt>(*this,false)/=value; } //! Division operator. /** Similar to operator/=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator/(const char *const expression) const { return CImg<Tfloat>(*this,false)/=expression; } //! Division operator. /** Similar to operator/=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator/(const CImg<t>& img) const { return (*this)*img.get_invert(); } //! In-place modulo operator. /** Similar to operator+=(const t), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)cimg::mod(*ptrd,(T)value); return *this; } //! In-place modulo operator. /** Similar to operator+=(const char*), except that it performs a modulo operation instead of an addition. **/ CImg<T>& operator%=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator%="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)cimg::mod(*ptrd,(T)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this%=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place modulo operator. /** Similar to operator+=(const CImg<t>&), except that it performs a modulo operation instead of an addition. **/ template<typename t> CImg<T>& operator%=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this%=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = cimg::mod(*ptrd,(T)*(ptrs++)); } return *this; } //! Modulo operator. /** Similar to operator%=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const t value) const { return CImg<_cimg_Tt>(*this,false)%=value; } //! Modulo operator. /** Similar to operator%=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ CImg<Tfloat> operator%(const char *const expression) const { return CImg<Tfloat>(*this,false)%=expression; } //! Modulo operator. /** Similar to operator%=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image may be a superset of the initial pixel type \c T, if necessary. **/ template<typename t> CImg<_cimg_Tt> operator%(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false)%=img; } //! In-place bitwise AND operator. /** Similar to operator+=(const t), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)((unsigned long)*ptrd & (unsigned long)value); return *this; } //! In-place bitwise AND operator. /** Similar to operator+=(const char*), except that it performs a bitwise AND operation instead of an addition. **/ CImg<T>& operator&=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator&="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)((unsigned long)*ptrd & (unsigned long)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this&=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place bitwise AND operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise AND operation instead of an addition. **/ template<typename t> CImg<T>& operator&=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this&=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((unsigned long)*ptrd & (unsigned long)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((unsigned long)*ptrd & (unsigned long)*(ptrs++)); } return *this; } //! Bitwise AND operator. /** Similar to operator&=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const t value) const { return (+*this)&=value; } //! Bitwise AND operator. /** Similar to operator&=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator&(const char *const expression) const { return (+*this)&=expression; } //! Bitwise AND operator. /** Similar to operator&=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator&(const CImg<t>& img) const { return (+*this)&=img; } //! In-place bitwise OR operator. /** Similar to operator+=(const t), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)((unsigned long)*ptrd | (unsigned long)value); return *this; } //! In-place bitwise OR operator. /** Similar to operator+=(const char*), except that it performs a bitwise OR operation instead of an addition. **/ CImg<T>& operator|=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator|="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)((unsigned long)*ptrd | (unsigned long)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this|=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place bitwise OR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise OR operation instead of an addition. **/ template<typename t> CImg<T>& operator|=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this|=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((unsigned long)*ptrd | (unsigned long)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((unsigned long)*ptrd | (unsigned long)*(ptrs++)); } return *this; } //! Bitwise OR operator. /** Similar to operator|=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const t value) const { return (+*this)|=value; } //! Bitwise OR operator. /** Similar to operator|=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator|(const char *const expression) const { return (+*this)|=expression; } //! Bitwise OR operator. /** Similar to operator|=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator|(const CImg<t>& img) const { return (+*this)|=img; } //! In-place bitwise XOR operator. /** Similar to operator+=(const t), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const t) instead. **/ template<typename t> CImg<T>& operator^=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)((unsigned long)*ptrd ^ (unsigned long)value); return *this; } //! In-place bitwise XOR operator. /** Similar to operator+=(const char*), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const char*) instead. **/ CImg<T>& operator^=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator^="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)((unsigned long)*ptrd ^ (unsigned long)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this^=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place bitwise XOR operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise XOR operation instead of an addition. \warning - It does \e not compute the \e power of pixel values. For this purpose, use pow(const CImg<t>&) instead. **/ template<typename t> CImg<T>& operator^=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((unsigned long)*ptrd ^ (unsigned long)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((unsigned long)*ptrd ^ (unsigned long)*(ptrs++)); } return *this; } //! Bitwise XOR operator. /** Similar to operator^=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const t value) const { return (+*this)^=value; } //! Bitwise XOR operator. /** Similar to operator^=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator^(const char *const expression) const { return (+*this)^=expression; } //! Bitwise XOR operator. /** Similar to operator^=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator^(const CImg<t>& img) const { return (+*this)^=img; } //! In-place bitwise left shift operator. /** Similar to operator+=(const t), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(((long)*ptrd) << (int)value); return *this; } //! In-place bitwise left shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise left shift instead of an addition. **/ CImg<T>& operator<<=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator<<="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)((long)*ptrd << (int)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this<<=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place bitwise left shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise left shift instead of an addition. **/ template<typename t> CImg<T>& operator<<=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((long)*ptrd << (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((long)*ptrd << (int)*(ptrs++)); } return *this; } //! Bitwise left shift operator. /** Similar to operator<<=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const t value) const { return (+*this)<<=value; } //! Bitwise left shift operator. /** Similar to operator<<=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator<<(const char *const expression) const { return (+*this)<<=expression; } //! Bitwise left shift operator. /** Similar to operator<<=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator<<(const CImg<t>& img) const { return (+*this)<<=img; } //! In-place bitwise right shift operator. /** Similar to operator+=(const t), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const t value) { cimg_for(*this,ptrd,T) *ptrd = (T)(((long)*ptrd) >> (int)value); return *this; } //! In-place bitwise right shift operator. /** Similar to operator+=(const char*), except that it performs a bitwise right shift instead of an addition. **/ CImg<T>& operator>>=(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator<<="); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)((long)*ptrd >> (int)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { cimg::exception_mode() = omode; *this>>=CImg<T>(_width,_height,_depth,_spectrum,expression,true); } cimg::exception_mode() = omode; return *this; } //! In-place bitwise right shift operator. /** Similar to operator+=(const CImg<t>&), except that it performs a bitwise right shift instead of an addition. **/ template<typename t> CImg<T>& operator>>=(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return *this^=+img; T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)((long)*ptrd >> (int)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)((long)*ptrd >> (int)*(ptrs++)); } return *this; } //! Bitwise right shift operator. /** Similar to operator>>=(const t), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const t value) const { return (+*this)>>=value; } //! Bitwise right shift operator. /** Similar to operator>>=(const char*), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ CImg<T> operator>>(const char *const expression) const { return (+*this)>>=expression; } //! Bitwise right shift operator. /** Similar to operator>>=(const CImg<t>&), except that it returns a new image instance instead of operating in-place. The pixel type of the returned image is \c T. **/ template<typename t> CImg<T> operator>>(const CImg<t>& img) const { return (+*this)>>=img; } //! Bitwise inversion operator. /** Similar to operator-(), except that it compute the bitwise inverse instead of the opposite value. **/ CImg<T> operator~() const { CImg<T> res(_width,_height,_depth,_spectrum); const T *ptrs = _data; cimg_for(res,ptrd,T) { const unsigned long value = (unsigned long)*(ptrs++); *ptrd = (T)~value; } return res; } //! Test if all pixels of an image have the same value. /** Return \c true is all pixels of the image instance are equal to the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator==(const t value) const { if (is_empty()) return false; typedef _cimg_Tt Tt; bool is_equal = true; for (T *ptrd = _data + size(); is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)value)) {} return is_equal; } //! Test if all pixel values of an image follow a specified expression. /** Return \c true is all pixels of the image instance are equal to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator==(const char *const expression) const { if (is_empty()) return !*expression; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; bool is_equal = true; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"operator<<="); const T *ptrs = _data; cimg_forXYZC(*this,x,y,z,c) { if (!is_equal) break; is_equal = ((double)*(ptrs++)==mp.eval(x,y,z,c)); } } catch (CImgException&) { cimg::exception_mode() = omode; is_equal = (*this==CImg<T>(_width,_height,_depth,_spectrum,expression,true)); } cimg::exception_mode() = omode; return is_equal; } //! Test if two images have the same size and values. /** Return \c true if the image instance and the input image \c img have the same dimensions and pixel values, and \c false otherwise. \param img Input image to compare with. \note - The pixel buffer pointers data() of the two compared images do not have to be the same for operator==() to return \c true. Only the dimensions and the pixel values matter. Thus, the comparison can be \c true even for different pixel types \c T and \c t. \par Example \code const CImg<float> img1(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'float' pixel values). const CImg<char> img2(1,3,1,1, 0,1,2); // Construct a 1x3 vector [0;1;2] (with 'char' pixel values). if (img1==img2) { // Test succeeds, image dimensions and values are the same. std::printf("'img1' and 'img2' have same dimensions and values."); } \endcode **/ template<typename t> bool operator==(const CImg<t>& img) const { typedef _cimg_Tt Tt; const unsigned long siz = size(); bool is_equal = true; if (siz!=img.size()) return false; t *ptrs = img._data + siz; for (T *ptrd = _data + siz; is_equal && ptrd>_data; is_equal = ((Tt)*(--ptrd)==(Tt)*(--ptrs))) {} return is_equal; } //! Test if pixels of an image are all different from a value. /** Return \c true is all pixels of the image instance are different than the specified \c value. \param value Reference value to compare with. **/ template<typename t> bool operator!=(const t value) const { return !((*this)==value); } //! Test if all pixel values of an image are different from a specified expression. /** Return \c true is all pixels of the image instance are different to the specified \c expression. \param expression Value string describing the way pixel values are compared. **/ bool operator!=(const char *const expression) const { return !((*this)==expression); } //! Test if two images have different sizes or values. /** Return \c true if the image instance and the input image \c img have different dimensions or pixel values, and \c false otherwise. \param img Input image to compare with. \note - Writing \c img1!=img2 is equivalent to \c !(img1==img2). **/ template<typename t> bool operator!=(const CImg<t>& img) const { return !((*this)==img); } //! Construct an image list from two images. /** Return a new list of image (\c CImgList instance) containing exactly two elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image \c img, at position [\c 1]. \param img Input image that will be the second image of the resulting list. \note - The family of operator,() is convenient to easily create list of images, but it is also \e quite \e slow in practice (see warning below). - Constructed lists contain no shared images. If image instance or input image \c img are shared, they are inserted as new non-shared copies in the resulting list. - The pixel type of the returned list may be a superset of the initial pixel type \c T, if necessary. \warning - Pipelining operator,() \c N times will perform \c N copies of the entire content of a (growing) image list. This may become very expensive in terms of speed and used memory. You should avoid using this technique to build a new CImgList instance from several images, if you are seeking for performance. Fast insertions of images in an image list are possible with CImgList<T>::insert(const CImg<t>&,unsigned int,bool) or move_to(CImgList<t>&,unsigned int). \par Example \code const CImg<float> img1("reference.jpg"), img2 = img1.get_mirror('x'), img3 = img2.get_blur(5); const CImgList<float> list = (img1,img2); // Create list of two elements from 'img1' and 'img2'. (list,img3).display(); // Display image list containing copies of 'img1','img2' and 'img3'. \endcode \image html ref_operator_comma.jpg **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImg<t>& img) const { return CImgList<_cimg_Tt>(*this,img); } //! Construct an image list from image instance and an input image list. /** Return a new list of images (\c CImgList instance) containing exactly \c list.size() \c + \c 1 elements: - A copy of the image instance, at position [\c 0]. - A copy of the specified image list \c list, from positions [\c 1] to [\c list.size()]. \param list Input image list that will be appended to the image instance. \note - Similar to operator,(const CImg<t>&) const, except that it takes an image list as an argument. **/ template<typename t> CImgList<_cimg_Tt> operator,(const CImgList<t>& list) const { return CImgList<_cimg_Tt>(list,false).insert(*this,0); } //! Split image along specified axis. /** Return a new list of images (\c CImgList instance) containing the splitted components of the instance image along the specified axis. \param axis Splitting axis (can be '\c x','\c y','\c z' or '\c c') \note - Similar to get_split(char,int) const, with default second argument. \par Example \code const CImg<unsigned char> img("reference.jpg"); // Load a RGB color image. const CImgList<unsigned char> list = (img<'c'); // Get a list of its three R,G,B channels. (img,list).display(); \endcode \image html ref_operator_less.jpg **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the number of image columns. /** Return the image width, i.e. the image dimension along the X-axis. \note - The width() of an empty image is equal to \c 0. - width() is typically equal to \c 1 when considering images as \e vectors for matrix calculations. - width() returns an \c int, although the image width is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._width</tt>. **/ int width() const { return (int)_width; } //! Return the number of image rows. /** Return the image height, i.e. the image dimension along the Y-axis. \note - The height() of an empty image is equal to \c 0. - height() returns an \c int, although the image height is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._height</tt>. **/ int height() const { return (int)_height; } //! Return the number of image slices. /** Return the image depth, i.e. the image dimension along the Z-axis. \note - The depth() of an empty image is equal to \c 0. - depth() is typically equal to \c 1 when considering usual 2d images. When depth()\c > \c 1, the image is said to be \e volumetric. - depth() returns an \c int, although the image depth is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._depth</tt>. **/ int depth() const { return (int)_depth; } //! Return the number of image channels. /** Return the number of image channels, i.e. the image dimension along the C-axis. \note - The spectrum() of an empty image is equal to \c 0. - spectrum() is typically equal to \c 1 when considering scalar-valued images, to \c 3 for RGB-coded color images, and to \c 4 for RGBA-coded color images (with alpha-channel). The number of channels of an image instance is not limited. The meaning of the pixel values is not linked up to the number of channels (e.g. a 4-channel image may indifferently stands for a RGBA or CMYK color image). - spectrum() returns an \c int, although the image spectrum is internally stored as an \c unsigned \c int. Using an \c int is safer and prevents arithmetic traps possibly encountered when doing calculations involving \c unsigned \c int variables. Access to the initial \c unsigned \c int variable is possible (though not recommended) by <tt>(*this)._spectrum</tt>. **/ int spectrum() const { return (int)_spectrum; } //! Return the total number of pixel values. /** Return <tt>width()*\ref height()*\ref depth()*\ref spectrum()</tt>, i.e. the total number of values of type \c T in the pixel buffer of the image instance. \note - The size() of an empty image is equal to \c 0. - The allocated memory size for a pixel buffer of a non-shared \c CImg<T> instance is equal to <tt>size()*sizeof(T)</tt>. \par Example \code const CImg<float> img(100,100,1,3); // Construct new 100x100 color image. if (img.size()==30000) // Test succeeds. std::printf("Pixel buffer uses %lu bytes", img.size()*sizeof(float)); \endcode **/ unsigned long size() const { return (unsigned long)_width*_height*_depth*_spectrum; } //! Return a pointer to the first pixel value. /** Return a \c T*, or a \c const \c T* pointer to the first value in the pixel buffer of the image instance, whether the instance is \c const or not. \note - The data() of an empty image is equal to \c 0 (null pointer). - The allocated pixel buffer for the image instance starts from \c data() and goes to <tt>data()+\ref size()-1</tt> (included). - To get the pointer to one particular location of the pixel buffer, use data(unsigned int,unsigned int,unsigned int,unsigned int) instead. **/ T* data() { return _data; } //! Return a pointer to the first pixel value \const. const T* data() const { return _data; } //! Return a pointer to a located pixel value. /** Return a \c T*, or a \c const \c T* pointer to the value located at (\c x,\c y,\c z,\c c) in the pixel buffer of the image instance, whether the instance is \c const or not. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c))</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). **/ #if cimg_verbosity>=3 T *data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { const unsigned long off = (unsigned long)offset(x,y,z,c); if (off>=size()) { cimg::warn(_cimg_instance "data(): Invalid pointer request, at coordinates (%u,%u,%u,%u) [offset=%u].", cimg_instance, x,y,z,c,off); return _data; } return _data + off; } //! Return a pointer to a located pixel value \const. const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return const_cast<CImg<T>*>(this)->data(x,y,z,c); } #else T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return _data + x + y*(unsigned long)_width + z*(unsigned long)_width*_height + c*(unsigned long)_width*_height*_depth; } const T* data(const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return _data + x + y*_width + z*(unsigned long)_width*_height + c*(unsigned long)_width*_height*_depth; } #endif //! Return the offset to a located pixel value, with respect to the beginning of the pixel buffer. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Writing \c img.data(x,y,z,c) is equivalent to <tt>&(img(x,y,z,c)) - img.data()</tt>. Thus, this method has the same properties as operator()(unsigned int,unsigned int,unsigned int,unsigned int). \par Example \code const CImg<float> img(100,100,1,3); // Define a 100x100 RGB-color image. const long off = img.offset(10,10,0,2); // Get the offset of the blue value of the pixel located at (10,10). const float val = img[off]; // Get the blue value of this pixel. \endcode **/ long offset(const int x, const int y=0, const int z=0, const int c=0) const { return x + y*(long)_width + z*(long)_width*_height + c*(long)_width*_height*_depth; } //! Return a CImg<T>::iterator pointing to the first pixel value. /** \note - Equivalent to data(). - It has been mainly defined for compatibility with STL naming conventions. **/ iterator begin() { return _data; } //! Return a CImg<T>::iterator pointing to the first value of the pixel buffer \const. const_iterator begin() const { return _data; } //! Return a CImg<T>::iterator pointing next to the last pixel value. /** \note - Writing \c img.end() is equivalent to <tt>img.data() + img.size()</tt>. - It has been mainly defined for compatibility with STL naming conventions. \warning - The returned iterator actually points to a value located \e outside the acceptable bounds of the pixel buffer. Trying to read or write the content of the returned iterator will probably result in a crash. Use it mainly as an strict upper bound for a CImg<T>::iterator. \par Example \code CImg<float> img(100,100,1,3); // Define a 100x100 RGB color image. for (CImg<float>::iterator it = img.begin(); it<img.end(); ++it) // 'img.end()' used here as an upper bound for the iterator. *it = 0; \endcode **/ iterator end() { return _data + size(); } //! Return a CImg<T>::iterator pointing next to the last pixel value \const. const_iterator end() const { return _data + size(); } //! Return a reference to the first pixel value. /** \note - Writing \c img.front() is equivalent to <tt>img[0]</tt>, or <tt>img(0,0,0,0)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& front() { return *_data; } //! Return a reference to the first pixel value \const. const T& front() const { return *_data; } //! Return a reference to the last pixel value. /** \note - Writing \c img.end() is equivalent to <tt>img[img.size()-1]</tt>, or <tt>img(img.width()-1,img.height()-1,img.depth()-1,img.spectrum()-1)</tt>. - It has been mainly defined for compatibility with STL naming conventions. **/ T& back() { return *(_data + size() - 1); } //! Return a reference to the last pixel value \const. const T& back() const { return *(_data + size() - 1); } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to a specified default value in case of out-of-bounds access. \param offset Offset to the desired pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note - Writing \c img.at(offset,out_value) is similar to <tt>img[offset]</tt>, except that if \c offset is outside bounds (e.g. \c offset<0 or \c offset>=img.size()), a reference to a value \c out_value is safely returned instead. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. **/ T& at(const int offset, const T out_value) { return (offset<0 || offset>=(int)size())?(cimg::temporary(out_value)=out_value):(*this)[offset]; } //! Access to a pixel value at a specified offset, using Dirichlet boundary conditions \const. T at(const int offset, const T out_value) const { return (offset<0 || offset>=(int)size())?out_value:(*this)[offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions. /** Return a reference to the pixel value of the image instance located at a specified \c offset, or to the nearest pixel location in the image instance in case of out-of-bounds access. \param offset Offset to the desired pixel value. \note - Similar to at(int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified offset, i.e. - If \c offset<0, then \c img[0] is returned. - If \c offset>=img.size(), then \c img[img.size()-1] is returned. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel offset. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int). **/ T& at(const int offset) { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } T& _at(const int offset) { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz-1:offset]; } //! Access to a pixel value at a specified offset, using Neumann boundary conditions \const. T at(const int offset) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "at(): Empty instance.", cimg_instance); return _at(offset); } T _at(const int offset) const { const unsigned int siz = (unsigned int)size(); return (*this)[offset<0?0:(unsigned int)offset>=siz?siz-1:offset]; } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to a specified default value in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c x,\c y,\c z,\c c) is outside image bounds. \note - Similar to operator()(), except that an out-of-bounds access along the X-axis returns the specified value \c out_value. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y, const int z, const int c, const T out_value) { return (x<0 || x>=width())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X-coordinate \const. T atX(const int x, const int y, const int z, const int c, const T out_value) const { return (x<0 || x>=width())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate. /** Return a reference to the pixel value of the image instance located at (\c x,\c y,\c z,\c c), or to the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to at(int,int,int,int,const T), except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - Due to the additional boundary checking operation, this method is slower than operator()(). Use it when you are \e not sure about the validity of the specified pixel coordinates. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _at(int,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ T& atX(const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } T& _atX(const int x, const int y=0, const int z=0, const int c=0) { return (*this)(x<0?0:(x>=width()?width()-1:x),y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X-coordinate \const. T atX(const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atX(): Empty instance.", cimg_instance); return _atX(x,y,z,c); } T _atX(const int x, const int y=0, const int z=0, const int c=0) const { return (*this)(x<0?0:(x>=width()?width()-1:x),y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X and Y-coordinates. **/ T& atXY(const int x, const int y, const int z, const int c, const T out_value) { return (x<0 || y<0 || x>=width() || y>=height())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y coordinates \const. T atXY(const int x, const int y, const int z, const int c, const T out_value) const { return (x<0 || y<0 || x>=width() || y>=height())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXY(int,int,int,int). **/ T& atXY(const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } T& _atXY(const int x, const int y, const int z=0, const int c=0) { return (*this)(x<0?0:(x>=width()?width()-1:x), y<0?0:(y>=height()?height()-1:y),z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates \const. T atXY(const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXY(): Empty instance.", cimg_instance); return _atXY(x,y,z,c); } T _atXY(const int x, const int y, const int z=0, const int c=0) const { return (*this)(x<0?0:(x>=width()?width()-1:x), y<0?0:(y>=height()?height()-1:y),z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed both on X,Y and Z-coordinates. **/ T& atXYZ(const int x, const int y, const int z, const int c, const T out_value) { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions for the X,Y and Z-coordinates \const. T atXYZ(const int x, const int y, const int z, const int c, const T out_value) const { return (x<0 || y<0 || z<0 || x>=width() || y>=height() || z>=depth())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to atX(int,int,int,int), except that boundary checking is performed both on X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZ(int,int,int,int). **/ T& atXYZ(const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } T& _atXYZ(const int x, const int y, const int z, const int c=0) { return (*this)(x<0?0:(x>=width()?width()-1:x),y<0?0:(y>=height()?height()-1:y), z<0?0:(z>=depth()?depth()-1:z),c); } //! Access to a pixel value, using Neumann boundary conditions for the X,Y and Z-coordinates \const. T atXYZ(const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZ(): Empty instance.", cimg_instance); return _atXYZ(x,y,z,c); } T _atXYZ(const int x, const int y, const int z, const int c=0) const { return (*this)(x<0?0:(x>=width()?width()-1:x),y<0?0:(y>=height()?height()-1:y), z<0?0:(z>=depth()?depth()-1:z),c); } //! Access to a pixel value, using Dirichlet boundary conditions. /** Similar to atX(int,int,int,int,const T), except that boundary checking is performed on all X,Y,Z and C-coordinates. **/ T& atXYZC(const int x, const int y, const int z, const int c, const T out_value) { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())? (cimg::temporary(out_value)=out_value):(*this)(x,y,z,c); } //! Access to a pixel value, using Dirichlet boundary conditions \const. T atXYZC(const int x, const int y, const int z, const int c, const T out_value) const { return (x<0 || y<0 || z<0 || c<0 || x>=width() || y>=height() || z>=depth() || c>=spectrum())?out_value:(*this)(x,y,z,c); } //! Access to a pixel value, using Neumann boundary conditions. /** Similar to atX(int,int,int,int), except that boundary checking is performed on all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _atXYZC(int,int,int,int). **/ T& atXYZC(const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } T& _atXYZC(const int x, const int y, const int z, const int c) { return (*this)(x<0?0:(x>=width()?width()-1:x), y<0?0:(y>=height()?height()-1:y), z<0?0:(z>=depth()?depth()-1:z), c<0?0:(c>=spectrum()?spectrum()-1:c)); } //! Access to a pixel value, using Neumann boundary conditions \const. T atXYZC(const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "atXYZC(): Empty instance.", cimg_instance); return _atXYZC(x,y,z,c); } T _atXYZC(const int x, const int y, const int z, const int c) const { return (*this)(x<0?0:(x>=width()?width()-1:x), y<0?0:(y>=height()?height()-1:y), z<0?0:(z>=depth()?depth()-1:z), c<0?0:(c>=spectrum()?spectrum()-1:c)); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to atX(int,int,int,int,const T), except that the returned pixel value is approximated by a linear interpolation along the X-axis, if corresponding coordinates are not integers. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y, const int z, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1; const float dx = fx - x; const Tfloat Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atXY(nx,y,z,c,out_value); return Ic + dx*(In-Ic); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X-coordinate. /** Return a linearly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to linear_atX(float,int,int,int,const T) const, except that an out-of-bounds access returns the value of the nearest pixel in the image instance, regarding the specified X-coordinate. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atX(): Empty instance.", cimg_instance); return _linear_atX(fx,y,z,c); } Tfloat _linear_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx); const unsigned int x = (unsigned int)nfx; const float dx = nfx - x; const unsigned int nx = dx>0?x+1:x; const Tfloat Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c); return Ic + dx*(In-Ic); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. **/ Tfloat linear_atXY(const float fx, const float fy, const int z, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; const Tfloat Icc = (Tfloat)atXY(x,y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value); return Icc + dx*(Inc-Icc + dy*(Icc+Inn-Icn-Inc)) + dy*(Icn-Icc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXY(float,float,int,int). **/ Tfloat linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXY(): Empty instance.", cimg_instance); return _linear_atXY(fx,fy,z,c); } Tfloat _linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx), nfy = fy<0?0:(fy>_height-1?_height-1:fy); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy; const float dx = nfx - x, dy = nfy - y; const unsigned int nx = dx>0?x+1:x, ny = dy>0?y+1:y; const Tfloat Icc = (Tfloat)(*this)(x,y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c); return Icc + dx*(Inc-Icc + dy*(Icc+Inn-Icn-Inc)) + dy*(Icn-Icc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat linear_atXYZ(const float fx, const float fy, const float fz, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Iccc = (Tfloat)atXYZ(x,y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Iccn = (Tfloat)atXYZ(x,y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value); return Iccc + dx*(Incc-Iccc + dy*(Iccc+Innc-Icnc-Incc + dz*(Iccn+Innn+Icnc+Incc-Icnn-Incn-Iccc-Innc)) + dz*(Iccc+Incn-Iccn-Incc)) + dy*(Icnc-Iccc + dz*(Iccc+Icnn-Iccn-Icnc)) + dz*(Iccn-Iccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZ(float,float,float,int). **/ Tfloat linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZ(): Empty instance.", cimg_instance); return _linear_atXYZ(fx,fy,fz,c); } Tfloat _linear_atXYZ(const float fx, const float fy=0, const float fz=0, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx), nfy = fy<0?0:(fy>_height-1?_height-1:fy), nfz = fz<0?0:(fz>_depth-1?_depth-1:fz); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const unsigned int nx = dx>0?x+1:x, ny = dy>0?y+1:y, nz = dz>0?z+1:z; const Tfloat Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c); return Iccc + dx*(Incc-Iccc + dy*(Iccc+Innc-Icnc-Incc + dz*(Iccn+Innn+Icnc+Incc-Icnn-Incn-Iccc-Innc)) + dz*(Iccc+Incn-Iccn-Incc)) + dy*(Icnc-Iccc + dz*(Iccc+Icnn-Iccn-Icnc)) + dz*(Iccn-Iccc); } //! Return pixel value, using linear interpolation and Dirichlet boundary conditions for all X,Y,Z and C-coordinates. /** Similar to linear_atX(float,int,int,int,const T) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. **/ Tfloat linear_atXYZC(const float fx, const float fy, const float fz, const float fc, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1, c = (int)fc - (fc>=0?0:1), nc = c + 1; const float dx = fx - x, dy = fy - y, dz = fz - z, dc = fc - c; const Tfloat Icccc = (Tfloat)atXYZC(x,y,z,c,out_value), Inccc = (Tfloat)atXYZC(nx,y,z,c,out_value), Icncc = (Tfloat)atXYZC(x,ny,z,c,out_value), Inncc = (Tfloat)atXYZC(nx,ny,z,c,out_value), Iccnc = (Tfloat)atXYZC(x,y,nz,c,out_value), Incnc = (Tfloat)atXYZC(nx,y,nz,c,out_value), Icnnc = (Tfloat)atXYZC(x,ny,nz,c,out_value), Innnc = (Tfloat)atXYZC(nx,ny,nz,c,out_value), Icccn = (Tfloat)atXYZC(x,y,z,nc,out_value), Inccn = (Tfloat)atXYZC(nx,y,z,nc,out_value), Icncn = (Tfloat)atXYZC(x,ny,z,nc,out_value), Inncn = (Tfloat)atXYZC(nx,ny,z,nc,out_value), Iccnn = (Tfloat)atXYZC(x,y,nz,nc,out_value), Incnn = (Tfloat)atXYZC(nx,y,nz,nc,out_value), Icnnn = (Tfloat)atXYZC(x,ny,nz,nc,out_value), Innnn = (Tfloat)atXYZC(nx,ny,nz,nc,out_value); return Icccc + dx*(Inccc-Icccc + dy*(Icccc+Inncc-Icncc-Inccc + dz*(Iccnc+Innnc+Icncc+Inccc-Icnnc-Incnc-Icccc-Inncc + dc*(Iccnn+Innnn+Icncn+Inccn+Icnnc+Incnc+Icccc+Inncc-Icnnn-Incnn-Icccn-Inncn-Iccnc-Innnc-Icncc-Inccc)) + dc*(Icccn+Inncn+Icncc+Inccc-Icncn-Inccn-Icccc-Inncc)) + dz*(Icccc+Incnc-Iccnc-Inccc + dc*(Icccn+Incnn+Iccnc+Inccc-Iccnn-Inccn-Icccc-Incnc)) + dc*(Icccc+Inccn-Inccc-Icccn)) + dy*(Icncc-Icccc + dz*(Icccc+Icnnc-Iccnc-Icncc + dc*(Icccn+Icnnn+Iccnc+Icncc-Iccnn-Icncn-Icccc-Icnnc)) + dc*(Icccc+Icncn-Icncc-Icccn)) + dz*(Iccnc-Icccc + dc*(Icccc+Iccnn-Iccnc-Icccn)) + dc*(Icccn-Icccc); } //! Return pixel value, using linear interpolation and Neumann boundary conditions for all X,Y,Z and C-coordinates. /** Similar to linear_atX(float,int,int,int) const, except that the linear interpolation and the boundary checking are achieved for all X,Y,Z and C-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _linear_atXYZC(float,float,float,float). **/ Tfloat linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "linear_atXYZC(): Empty instance.", cimg_instance); return _linear_atXYZC(fx,fy,fz,fc); } Tfloat _linear_atXYZC(const float fx, const float fy=0, const float fz=0, const float fc=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx), nfy = fy<0?0:(fy>_height-1?_height-1:fy), nfz = fz<0?0:(fz>_depth-1?_depth-1:fz), nfc = fc<0?0:(fc>_spectrum-1?_spectrum-1:fc); const unsigned int x = (unsigned int)nfx, y = (unsigned int)nfy, z = (unsigned int)nfz, c = (unsigned int)nfc; const float dx = nfx - x, dy = nfy - y, dz = nfz - z, dc = nfc - c; const unsigned int nx = dx>0?x+1:x, ny = dy>0?y+1:y, nz = dz>0?z+1:z, nc = dc>0?c+1:c; const Tfloat Icccc = (Tfloat)(*this)(x,y,z,c), Inccc = (Tfloat)(*this)(nx,y,z,c), Icncc = (Tfloat)(*this)(x,ny,z,c), Inncc = (Tfloat)(*this)(nx,ny,z,c), Iccnc = (Tfloat)(*this)(x,y,nz,c), Incnc = (Tfloat)(*this)(nx,y,nz,c), Icnnc = (Tfloat)(*this)(x,ny,nz,c), Innnc = (Tfloat)(*this)(nx,ny,nz,c), Icccn = (Tfloat)(*this)(x,y,z,nc), Inccn = (Tfloat)(*this)(nx,y,z,nc), Icncn = (Tfloat)(*this)(x,ny,z,nc), Inncn = (Tfloat)(*this)(nx,ny,z,nc), Iccnn = (Tfloat)(*this)(x,y,nz,nc), Incnn = (Tfloat)(*this)(nx,y,nz,nc), Icnnn = (Tfloat)(*this)(x,ny,nz,nc), Innnn = (Tfloat)(*this)(nx,ny,nz,nc); return Icccc + dx*(Inccc-Icccc + dy*(Icccc+Inncc-Icncc-Inccc + dz*(Iccnc+Innnc+Icncc+Inccc-Icnnc-Incnc-Icccc-Inncc + dc*(Iccnn+Innnn+Icncn+Inccn+Icnnc+Incnc+Icccc+Inncc-Icnnn-Incnn-Icccn-Inncn-Iccnc-Innnc-Icncc-Inccc)) + dc*(Icccn+Inncn+Icncc+Inccc-Icncn-Inccn-Icccc-Inncc)) + dz*(Icccc+Incnc-Iccnc-Inccc + dc*(Icccn+Incnn+Iccnc+Inccc-Iccnn-Inccn-Icccc-Incnc)) + dc*(Icccc+Inccn-Inccc-Icccn)) + dy*(Icncc-Icccc + dz*(Icccc+Icnnc-Iccnc-Icncc + dc*(Icccn+Icnnn+Iccnc+Icncc-Iccnn-Icncn-Icccc-Icnnc)) + dc*(Icccc+Icncn-Icncc-Icccn)) + dz*(Iccnc-Icccc + dc*(Icccc+Iccnn-Iccnc-Icccn)) + dc*(Icccn-Icccc); } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or a specified default value in case of out-of-bounds access along the X-axis. \param fx d X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c (\c fx,\c y,\c z,\c c) is outside image bounds. \note - Similar to linear_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a \e cubic interpolation along the X-axis. - The type of the returned pixel value is extended to \c float, if the pixel type \c T is not float-valued. \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y, const int z, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2; const float dx = fx - x; const Tfloat Ip = (Tfloat)atX(px,y,z,c,out_value), Ic = (Tfloat)atX(x,y,z,c,out_value), In = (Tfloat)atX(nx,y,z,c,out_value), Ia = (Tfloat)atX(ax,y,z,c,out_value); return Ic + 0.5f*(dx*(-Ip+In) + dx*dx*(2*Ip-5*Ic+4*In-Ia) + dx*dx*dx*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int,const T) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atX(const float fx, const int y, const int z, const int c, const T out_value, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atX(fx,y,z,c,out_value); return val<min_value?min_value:val>max_value?max_value:val; } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Return a cubicly-interpolated pixel value of the image instance located at (\c fx,\c y,\c z,\c c), or the value of the nearest pixel location in the image instance in case of out-of-bounds access along the X-axis. \param fx X-coordinate of the pixel value (float-valued). \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Similar to cubic_atX(float,int,int,int,const T) const, except that the returned pixel value is approximated by a cubic interpolation along the X-axis. - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atX(float,int,int,int). \warning - There is \e no boundary checking performed for the Y,Z and C-coordinates, so they must be inside image bounds. **/ Tfloat cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atX(): Empty instance.", cimg_instance); return _cubic_atX(fx,y,z,c); } Tfloat _cubic_atX(const float fx, const int y=0, const int z=0, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx); const int x = (int)nfx; const float dx = nfx - x; const int px = x-1<0?0:x-1, nx = dx>0?x+1:x, ax = x+2>=width()?width()-1:x+2; const Tfloat Ip = (Tfloat)(*this)(px,y,z,c), Ic = (Tfloat)(*this)(x,y,z,c), In = (Tfloat)(*this)(nx,y,z,c), Ia = (Tfloat)(*this)(ax,y,z,c); return Ic + 0.5f*(dx*(-Ip+In) + dx*dx*(2*Ip-5*Ic+4*In-Ia) + dx*dx*dx*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Neumann boundary conditions for the X-coordinate. /** Similar to cubic_atX(float,int,int,int) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atX(const float fx, const int y, const int z, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atX(fx,y,z,c); return val<min_value?min_value:val>max_value?max_value:val; } Tfloat _cubic_atX(const float fx, const int y, const int z, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = _cubic_atX(fx,y,z,c); return val<min_value?min_value:val>max_value?max_value:val; } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X and Y-coordinates. **/ Tfloat cubic_atXY(const float fx, const float fy, const int z, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2; const float dx = fx - x, dy = fy - y; const Tfloat Ipp = (Tfloat)atXY(px,py,z,c,out_value), Icp = (Tfloat)atXY(x,py,z,c,out_value), Inp = (Tfloat)atXY(nx,py,z,c,out_value), Iap = (Tfloat)atXY(ax,py,z,c,out_value), Ip = Icp + 0.5f*(dx*(-Ipp+Inp) + dx*dx*(2*Ipp-5*Icp+4*Inp-Iap) + dx*dx*dx*(-Ipp+3*Icp-3*Inp+Iap)), Ipc = (Tfloat)atXY(px,y,z,c,out_value), Icc = (Tfloat)atXY(x, y,z,c,out_value), Inc = (Tfloat)atXY(nx,y,z,c,out_value), Iac = (Tfloat)atXY(ax,y,z,c,out_value), Ic = Icc + 0.5f*(dx*(-Ipc+Inc) + dx*dx*(2*Ipc-5*Icc+4*Inc-Iac) + dx*dx*dx*(-Ipc+3*Icc-3*Inc+Iac)), Ipn = (Tfloat)atXY(px,ny,z,c,out_value), Icn = (Tfloat)atXY(x,ny,z,c,out_value), Inn = (Tfloat)atXY(nx,ny,z,c,out_value), Ian = (Tfloat)atXY(ax,ny,z,c,out_value), In = Icn + 0.5f*(dx*(-Ipn+Inn) + dx*dx*(2*Ipn-5*Icn+4*Inn-Ian) + dx*dx*dx*(-Ipn+3*Icn-3*Inn+Ian)), Ipa = (Tfloat)atXY(px,ay,z,c,out_value), Ica = (Tfloat)atXY(x,ay,z,c,out_value), Ina = (Tfloat)atXY(nx,ay,z,c,out_value), Iaa = (Tfloat)atXY(ax,ay,z,c,out_value), Ia = Ica + 0.5f*(dx*(-Ipa+Ina) + dx*dx*(2*Ipa-5*Ica+4*Ina-Iaa) + dx*dx*dx*(-Ipa+3*Ica-3*Ina+Iaa)); return Ic + 0.5f*(dy*(-Ip+In) + dy*dy*(2*Ip-5*Ic+4*In-Ia) + dy*dy*dy*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X and Y-coordinates. /** Similar to cubic_atXY(float,float,int,int,const T) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atXY(const float fx, const float fy, const int z, const int c, const T out_value, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atXY(fx,fy,z,c,out_value); return val<min_value?min_value:val>max_value?max_value:val; } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved for both X and Y-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXY(float,float,int,int). **/ Tfloat cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXY(): Empty instance.", cimg_instance); return _cubic_atXY(fx,fy,z,c); } Tfloat _cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx), nfy = fy<0?0:(fy>_height-1?_height-1:fy); const int x = (int)nfx, y = (int)nfy; const float dx = nfx - x, dy = nfy - y; const int px = x-1<0?0:x-1, nx = dx>0?x+1:x, ax = x+2>=width()?width()-1:x+2, py = y-1<0?0:y-1, ny = dy>0?y+1:y, ay = y+2>=height()?height()-1:y+2; const Tfloat Ipp = (Tfloat)(*this)(px,py,z,c), Icp = (Tfloat)(*this)(x,py,z,c), Inp = (Tfloat)(*this)(nx,py,z,c), Iap = (Tfloat)(*this)(ax,py,z,c), Ip = Icp + 0.5f*(dx*(-Ipp+Inp) + dx*dx*(2*Ipp-5*Icp+4*Inp-Iap) + dx*dx*dx*(-Ipp+3*Icp-3*Inp+Iap)), Ipc = (Tfloat)(*this)(px,y,z,c), Icc = (Tfloat)(*this)(x, y,z,c), Inc = (Tfloat)(*this)(nx,y,z,c), Iac = (Tfloat)(*this)(ax,y,z,c), Ic = Icc + 0.5f*(dx*(-Ipc+Inc) + dx*dx*(2*Ipc-5*Icc+4*Inc-Iac) + dx*dx*dx*(-Ipc+3*Icc-3*Inc+Iac)), Ipn = (Tfloat)(*this)(px,ny,z,c), Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c), Ian = (Tfloat)(*this)(ax,ny,z,c), In = Icn + 0.5f*(dx*(-Ipn+Inn) + dx*dx*(2*Ipn-5*Icn+4*Inn-Ian) + dx*dx*dx*(-Ipn+3*Icn-3*Inn+Ian)), Ipa = (Tfloat)(*this)(px,ay,z,c), Ica = (Tfloat)(*this)(x,ay,z,c), Ina = (Tfloat)(*this)(nx,ay,z,c), Iaa = (Tfloat)(*this)(ax,ay,z,c), Ia = Ica + 0.5f*(dx*(-Ipa+Ina) + dx*dx*(2*Ipa-5*Ica+4*Ina-Iaa) + dx*dx*dx*(-Ipa+3*Ica-3*Ina+Iaa)); return Ic + 0.5f*(dy*(-Ip+In) + dy*dy*(2*Ip-5*Ic+4*In-Ia) + dy*dy*dy*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Neumann boundary conditions for the X and Y-coordinates. /** Similar to cubic_atXY(float,float,int,int) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atXY(const float fx, const float fy, const int z, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atXY(fx,fy,z,c); return val<min_value?min_value:val>max_value?max_value:val; } Tfloat _cubic_atXY(const float fx, const float fy, const int z, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = _cubic_atXY(fx,fy,z,c); return val<min_value?min_value:val>max_value?max_value:val; } //! Return pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int,const T) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const T out_value) const { const int x = (int)fx - (fx>=0?0:1), px = x - 1, nx = x + 1, ax = x + 2, y = (int)fy - (fy>=0?0:1), py = y - 1, ny = y + 1, ay = y + 2, z = (int)fz - (fz>=0?0:1), pz = z - 1, nz = z + 1, az = z + 2; const float dx = fx - x, dy = fy - y, dz = fz - z; const Tfloat Ippp = (Tfloat)atXYZ(px,py,pz,c,out_value), Icpp = (Tfloat)atXYZ(x,py,pz,c,out_value), Inpp = (Tfloat)atXYZ(nx,py,pz,c,out_value), Iapp = (Tfloat)atXYZ(ax,py,pz,c,out_value), Ipp = Icpp + 0.5f*(dx*(-Ippp+Inpp) + dx*dx*(2*Ippp-5*Icpp+4*Inpp-Iapp) + dx*dx*dx*(-Ippp+3*Icpp-3*Inpp+Iapp)), Ipcp = (Tfloat)atXYZ(px,y,pz,c,out_value), Iccp = (Tfloat)atXYZ(x, y,pz,c,out_value), Incp = (Tfloat)atXYZ(nx,y,pz,c,out_value), Iacp = (Tfloat)atXYZ(ax,y,pz,c,out_value), Icp = Iccp + 0.5f*(dx*(-Ipcp+Incp) + dx*dx*(2*Ipcp-5*Iccp+4*Incp-Iacp) + dx*dx*dx*(-Ipcp+3*Iccp-3*Incp+Iacp)), Ipnp = (Tfloat)atXYZ(px,ny,pz,c,out_value), Icnp = (Tfloat)atXYZ(x,ny,pz,c,out_value), Innp = (Tfloat)atXYZ(nx,ny,pz,c,out_value), Ianp = (Tfloat)atXYZ(ax,ny,pz,c,out_value), Inp = Icnp + 0.5f*(dx*(-Ipnp+Innp) + dx*dx*(2*Ipnp-5*Icnp+4*Innp-Ianp) + dx*dx*dx*(-Ipnp+3*Icnp-3*Innp+Ianp)), Ipap = (Tfloat)atXYZ(px,ay,pz,c,out_value), Icap = (Tfloat)atXYZ(x,ay,pz,c,out_value), Inap = (Tfloat)atXYZ(nx,ay,pz,c,out_value), Iaap = (Tfloat)atXYZ(ax,ay,pz,c,out_value), Iap = Icap + 0.5f*(dx*(-Ipap+Inap) + dx*dx*(2*Ipap-5*Icap+4*Inap-Iaap) + dx*dx*dx*(-Ipap+3*Icap-3*Inap+Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp+Inp) + dy*dy*(2*Ipp-5*Icp+4*Inp-Iap) + dy*dy*dy*(-Ipp+3*Icp-3*Inp+Iap)), Ippc = (Tfloat)atXYZ(px,py,z,c,out_value), Icpc = (Tfloat)atXYZ(x,py,z,c,out_value), Inpc = (Tfloat)atXYZ(nx,py,z,c,out_value), Iapc = (Tfloat)atXYZ(ax,py,z,c,out_value), Ipc = Icpc + 0.5f*(dx*(-Ippc+Inpc) + dx*dx*(2*Ippc-5*Icpc+4*Inpc-Iapc) + dx*dx*dx*(-Ippc+3*Icpc-3*Inpc+Iapc)), Ipcc = (Tfloat)atXYZ(px,y,z,c,out_value), Iccc = (Tfloat)atXYZ(x, y,z,c,out_value), Incc = (Tfloat)atXYZ(nx,y,z,c,out_value), Iacc = (Tfloat)atXYZ(ax,y,z,c,out_value), Icc = Iccc + 0.5f*(dx*(-Ipcc+Incc) + dx*dx*(2*Ipcc-5*Iccc+4*Incc-Iacc) + dx*dx*dx*(-Ipcc+3*Iccc-3*Incc+Iacc)), Ipnc = (Tfloat)atXYZ(px,ny,z,c,out_value), Icnc = (Tfloat)atXYZ(x,ny,z,c,out_value), Innc = (Tfloat)atXYZ(nx,ny,z,c,out_value), Ianc = (Tfloat)atXYZ(ax,ny,z,c,out_value), Inc = Icnc + 0.5f*(dx*(-Ipnc+Innc) + dx*dx*(2*Ipnc-5*Icnc+4*Innc-Ianc) + dx*dx*dx*(-Ipnc+3*Icnc-3*Innc+Ianc)), Ipac = (Tfloat)atXYZ(px,ay,z,c,out_value), Icac = (Tfloat)atXYZ(x,ay,z,c,out_value), Inac = (Tfloat)atXYZ(nx,ay,z,c,out_value), Iaac = (Tfloat)atXYZ(ax,ay,z,c,out_value), Iac = Icac + 0.5f*(dx*(-Ipac+Inac) + dx*dx*(2*Ipac-5*Icac+4*Inac-Iaac) + dx*dx*dx*(-Ipac+3*Icac-3*Inac+Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc+Inc) + dy*dy*(2*Ipc-5*Icc+4*Inc-Iac) + dy*dy*dy*(-Ipc+3*Icc-3*Inc+Iac)), Ippn = (Tfloat)atXYZ(px,py,nz,c,out_value), Icpn = (Tfloat)atXYZ(x,py,nz,c,out_value), Inpn = (Tfloat)atXYZ(nx,py,nz,c,out_value), Iapn = (Tfloat)atXYZ(ax,py,nz,c,out_value), Ipn = Icpn + 0.5f*(dx*(-Ippn+Inpn) + dx*dx*(2*Ippn-5*Icpn+4*Inpn-Iapn) + dx*dx*dx*(-Ippn+3*Icpn-3*Inpn+Iapn)), Ipcn = (Tfloat)atXYZ(px,y,nz,c,out_value), Iccn = (Tfloat)atXYZ(x, y,nz,c,out_value), Incn = (Tfloat)atXYZ(nx,y,nz,c,out_value), Iacn = (Tfloat)atXYZ(ax,y,nz,c,out_value), Icn = Iccn + 0.5f*(dx*(-Ipcn+Incn) + dx*dx*(2*Ipcn-5*Iccn+4*Incn-Iacn) + dx*dx*dx*(-Ipcn+3*Iccn-3*Incn+Iacn)), Ipnn = (Tfloat)atXYZ(px,ny,nz,c,out_value), Icnn = (Tfloat)atXYZ(x,ny,nz,c,out_value), Innn = (Tfloat)atXYZ(nx,ny,nz,c,out_value), Iann = (Tfloat)atXYZ(ax,ny,nz,c,out_value), Inn = Icnn + 0.5f*(dx*(-Ipnn+Innn) + dx*dx*(2*Ipnn-5*Icnn+4*Innn-Iann) + dx*dx*dx*(-Ipnn+3*Icnn-3*Innn+Iann)), Ipan = (Tfloat)atXYZ(px,ay,nz,c,out_value), Ican = (Tfloat)atXYZ(x,ay,nz,c,out_value), Inan = (Tfloat)atXYZ(nx,ay,nz,c,out_value), Iaan = (Tfloat)atXYZ(ax,ay,nz,c,out_value), Ian = Ican + 0.5f*(dx*(-Ipan+Inan) + dx*dx*(2*Ipan-5*Ican+4*Inan-Iaan) + dx*dx*dx*(-Ipan+3*Ican-3*Inan+Iaan)), In = Icn + 0.5f*(dy*(-Ipn+Inn) + dy*dy*(2*Ipn-5*Icn+4*Inn-Ian) + dy*dy*dy*(-Ipn+3*Icn-3*Inn+Ian)), Ippa = (Tfloat)atXYZ(px,py,az,c,out_value), Icpa = (Tfloat)atXYZ(x,py,az,c,out_value), Inpa = (Tfloat)atXYZ(nx,py,az,c,out_value), Iapa = (Tfloat)atXYZ(ax,py,az,c,out_value), Ipa = Icpa + 0.5f*(dx*(-Ippa+Inpa) + dx*dx*(2*Ippa-5*Icpa+4*Inpa-Iapa) + dx*dx*dx*(-Ippa+3*Icpa-3*Inpa+Iapa)), Ipca = (Tfloat)atXYZ(px,y,az,c,out_value), Icca = (Tfloat)atXYZ(x, y,az,c,out_value), Inca = (Tfloat)atXYZ(nx,y,az,c,out_value), Iaca = (Tfloat)atXYZ(ax,y,az,c,out_value), Ica = Icca + 0.5f*(dx*(-Ipca+Inca) + dx*dx*(2*Ipca-5*Icca+4*Inca-Iaca) + dx*dx*dx*(-Ipca+3*Icca-3*Inca+Iaca)), Ipna = (Tfloat)atXYZ(px,ny,az,c,out_value), Icna = (Tfloat)atXYZ(x,ny,az,c,out_value), Inna = (Tfloat)atXYZ(nx,ny,az,c,out_value), Iana = (Tfloat)atXYZ(ax,ny,az,c,out_value), Ina = Icna + 0.5f*(dx*(-Ipna+Inna) + dx*dx*(2*Ipna-5*Icna+4*Inna-Iana) + dx*dx*dx*(-Ipna+3*Icna-3*Inna+Iana)), Ipaa = (Tfloat)atXYZ(px,ay,az,c,out_value), Icaa = (Tfloat)atXYZ(x,ay,az,c,out_value), Inaa = (Tfloat)atXYZ(nx,ay,az,c,out_value), Iaaa = (Tfloat)atXYZ(ax,ay,az,c,out_value), Iaa = Icaa + 0.5f*(dx*(-Ipaa+Inaa) + dx*dx*(2*Ipaa-5*Icaa+4*Inaa-Iaaa) + dx*dx*dx*(-Ipaa+3*Icaa-3*Inaa+Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa+Ina) + dy*dy*(2*Ipa-5*Ica+4*Ina-Iaa) + dy*dy*dy*(-Ipa+3*Ica-3*Ina+Iaa)); return Ic + 0.5f*(dz*(-Ip+In) + dz*dz*(2*Ip-5*Ic+4*In-Ia) + dz*dz*dz*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Dirichlet boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atXYZ(float,float,float,int,const T) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const T out_value, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atXYZ(fx,fy,fz,c,out_value); return val<min_value?min_value:val>max_value?max_value:val; } //! Return pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atX(float,int,int,int) const, except that the cubic interpolation and boundary checking are achieved both for X,Y and Z-coordinates. \note - If you know your image instance is \e not empty, you may rather use the slightly faster method \c _cubic_atXYZ(float,float,float,int). **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "cubic_atXYZ(): Empty instance.", cimg_instance); return _cubic_atXYZ(fx,fy,fz,c); } Tfloat _cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const { const float nfx = fx<0?0:(fx>_width-1?_width-1:fx), nfy = fy<0?0:(fy>_height-1?_height-1:fy), nfz = fz<0?0:(fz>_depth-1?_depth-1:fz); const int x = (int)nfx, y = (int)nfy, z = (int)nfz; const float dx = nfx - x, dy = nfy - y, dz = nfz - z; const int px = x-1<0?0:x-1, nx = dx>0?x+1:x, ax = x+2>=width()?width()-1:x+2, py = y-1<0?0:y-1, ny = dy>0?y+1:y, ay = y+2>=height()?height()-1:y+2, pz = z-1<0?0:z-1, nz = dz>0?z+1:z, az = z+2>=depth()?depth()-1:z+2; const Tfloat Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c), Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c), Ipp = Icpp + 0.5f*(dx*(-Ippp+Inpp) + dx*dx*(2*Ippp-5*Icpp+4*Inpp-Iapp) + dx*dx*dx*(-Ippp+3*Icpp-3*Inpp+Iapp)), Ipcp = (Tfloat)(*this)(px,y,pz,c), Iccp = (Tfloat)(*this)(x, y,pz,c), Incp = (Tfloat)(*this)(nx,y,pz,c), Iacp = (Tfloat)(*this)(ax,y,pz,c), Icp = Iccp + 0.5f*(dx*(-Ipcp+Incp) + dx*dx*(2*Ipcp-5*Iccp+4*Incp-Iacp) + dx*dx*dx*(-Ipcp+3*Iccp-3*Incp+Iacp)), Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c), Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c), Inp = Icnp + 0.5f*(dx*(-Ipnp+Innp) + dx*dx*(2*Ipnp-5*Icnp+4*Innp-Ianp) + dx*dx*dx*(-Ipnp+3*Icnp-3*Innp+Ianp)), Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c), Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c), Iap = Icap + 0.5f*(dx*(-Ipap+Inap) + dx*dx*(2*Ipap-5*Icap+4*Inap-Iaap) + dx*dx*dx*(-Ipap+3*Icap-3*Inap+Iaap)), Ip = Icp + 0.5f*(dy*(-Ipp+Inp) + dy*dy*(2*Ipp-5*Icp+4*Inp-Iap) + dy*dy*dy*(-Ipp+3*Icp-3*Inp+Iap)), Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c), Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c), Ipc = Icpc + 0.5f*(dx*(-Ippc+Inpc) + dx*dx*(2*Ippc-5*Icpc+4*Inpc-Iapc) + dx*dx*dx*(-Ippc+3*Icpc-3*Inpc+Iapc)), Ipcc = (Tfloat)(*this)(px,y,z,c), Iccc = (Tfloat)(*this)(x, y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c), Iacc = (Tfloat)(*this)(ax,y,z,c), Icc = Iccc + 0.5f*(dx*(-Ipcc+Incc) + dx*dx*(2*Ipcc-5*Iccc+4*Incc-Iacc) + dx*dx*dx*(-Ipcc+3*Iccc-3*Incc+Iacc)), Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c), Inc = Icnc + 0.5f*(dx*(-Ipnc+Innc) + dx*dx*(2*Ipnc-5*Icnc+4*Innc-Ianc) + dx*dx*dx*(-Ipnc+3*Icnc-3*Innc+Ianc)), Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c), Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c), Iac = Icac + 0.5f*(dx*(-Ipac+Inac) + dx*dx*(2*Ipac-5*Icac+4*Inac-Iaac) + dx*dx*dx*(-Ipac+3*Icac-3*Inac+Iaac)), Ic = Icc + 0.5f*(dy*(-Ipc+Inc) + dy*dy*(2*Ipc-5*Icc+4*Inc-Iac) + dy*dy*dy*(-Ipc+3*Icc-3*Inc+Iac)), Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c), Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c), Ipn = Icpn + 0.5f*(dx*(-Ippn+Inpn) + dx*dx*(2*Ippn-5*Icpn+4*Inpn-Iapn) + dx*dx*dx*(-Ippn+3*Icpn-3*Inpn+Iapn)), Ipcn = (Tfloat)(*this)(px,y,nz,c), Iccn = (Tfloat)(*this)(x, y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c), Iacn = (Tfloat)(*this)(ax,y,nz,c), Icn = Iccn + 0.5f*(dx*(-Ipcn+Incn) + dx*dx*(2*Ipcn-5*Iccn+4*Incn-Iacn) + dx*dx*dx*(-Ipcn+3*Iccn-3*Incn+Iacn)), Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c), Inn = Icnn + 0.5f*(dx*(-Ipnn+Innn) + dx*dx*(2*Ipnn-5*Icnn+4*Innn-Iann) + dx*dx*dx*(-Ipnn+3*Icnn-3*Innn+Iann)), Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c), Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c), Ian = Ican + 0.5f*(dx*(-Ipan+Inan) + dx*dx*(2*Ipan-5*Ican+4*Inan-Iaan) + dx*dx*dx*(-Ipan+3*Ican-3*Inan+Iaan)), In = Icn + 0.5f*(dy*(-Ipn+Inn) + dy*dy*(2*Ipn-5*Icn+4*Inn-Ian) + dy*dy*dy*(-Ipn+3*Icn-3*Inn+Ian)), Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c), Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c), Ipa = Icpa + 0.5f*(dx*(-Ippa+Inpa) + dx*dx*(2*Ippa-5*Icpa+4*Inpa-Iapa) + dx*dx*dx*(-Ippa+3*Icpa-3*Inpa+Iapa)), Ipca = (Tfloat)(*this)(px,y,az,c), Icca = (Tfloat)(*this)(x, y,az,c), Inca = (Tfloat)(*this)(nx,y,az,c), Iaca = (Tfloat)(*this)(ax,y,az,c), Ica = Icca + 0.5f*(dx*(-Ipca+Inca) + dx*dx*(2*Ipca-5*Icca+4*Inca-Iaca) + dx*dx*dx*(-Ipca+3*Icca-3*Inca+Iaca)), Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c), Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c), Ina = Icna + 0.5f*(dx*(-Ipna+Inna) + dx*dx*(2*Ipna-5*Icna+4*Inna-Iana) + dx*dx*dx*(-Ipna+3*Icna-3*Inna+Iana)), Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c), Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c), Iaa = Icaa + 0.5f*(dx*(-Ipaa+Inaa) + dx*dx*(2*Ipaa-5*Icaa+4*Inaa-Iaaa) + dx*dx*dx*(-Ipaa+3*Icaa-3*Inaa+Iaaa)), Ia = Ica + 0.5f*(dy*(-Ipa+Ina) + dy*dy*(2*Ipa-5*Ica+4*Ina-Iaa) + dy*dy*dy*(-Ipa+3*Ica-3*Ina+Iaa)); return Ic + 0.5f*(dz*(-Ip+In) + dz*dz*(2*Ip-5*Ic+4*In-Ia) + dz*dz*dz*(-Ip+3*Ic-3*In+Ia)); } //! Return damped pixel value, using cubic interpolation and Neumann boundary conditions for the X,Y and Z-coordinates. /** Similar to cubic_atXYZ(float,float,float,int) const, except that you can specify the authorized minimum and maximum of the returned value. **/ Tfloat cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = cubic_atXYZ(fx,fy,fz,c); return val<min_value?min_value:val>max_value?max_value:val; } Tfloat _cubic_atXYZ(const float fx, const float fy, const float fz, const int c, const Tfloat min_value, const Tfloat max_value) const { const Tfloat val = _cubic_atXYZ(fx,fy,fz,c); return val<min_value?min_value:val>max_value?max_value:val; } //! Set pixel value, using linear interpolation for the X and Y-coordinates. /** Set pixel value at specified coordinates (\c fx,\c fy,\c z,\c c) in the image instance, in a way that the value is spread amongst several neighbors if the pixel coordinates are indeed float-valued. \param value Pixel value to set. \param fx X-coordinate of the pixel value (float-valued). \param fy Y-coordinate of the pixel value (float-valued). \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param is_added Tells if the pixel value is added to (\c true), or simply replace (\c false) the current image pixel(s). \return A reference to the current image instance. \note - If specified coordinates are outside image bounds, no operations are performed. **/ CImg<T>& set_linear_atXY(const T& value, const float fx, const float fy=0, const int z=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1; const float dx = fx - x, dy = fy - y; if (z>=0 && z<depth() && c>=0 && c<spectrum()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*(1-dy), w2 = is_added?1:(1-w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1-dy), w2 = is_added?1:(1-w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*dy, w2 = is_added?1:(1-w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy, w2 = is_added?1:(1-w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } return *this; } //! Set pixel value, using linear interpolation for the X,Y and Z-coordinates. /** Similar to set_linear_atXY(const T&,float,float,int,int,bool), except that the linear interpolation is achieved both for X,Y and Z-coordinates. **/ CImg<T>& set_linear_atXYZ(const T& value, const float fx, const float fy=0, const float fz=0, const int c=0, const bool is_added=false) { const int x = (int)fx - (fx>=0?0:1), nx = x + 1, y = (int)fy - (fy>=0?0:1), ny = y + 1, z = (int)fz - (fz>=0?0:1), nz = z + 1; const float dx = fx - x, dy = fy - y, dz = fz - z; if (c>=0 && c<spectrum()) { if (z>=0 && z<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*(1-dy)*(1-dz), w2 = is_added?1:(1-w1); (*this)(x,y,z,c) = (T)(w1*value + w2*(*this)(x,y,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1-dy)*(1-dz), w2 = is_added?1:(1-w1); (*this)(nx,y,z,c) = (T)(w1*value + w2*(*this)(nx,y,z,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*dy*(1-dz), w2 = is_added?1:(1-w1); (*this)(x,ny,z,c) = (T)(w1*value + w2*(*this)(x,ny,z,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*(1-dz), w2 = is_added?1:(1-w1); (*this)(nx,ny,z,c) = (T)(w1*value + w2*(*this)(nx,ny,z,c)); } } } if (nz>=0 && nz<depth()) { if (y>=0 && y<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*(1-dy)*dz, w2 = is_added?1:(1-w1); (*this)(x,y,nz,c) = (T)(w1*value + w2*(*this)(x,y,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*(1-dy)*dz, w2 = is_added?1:(1-w1); (*this)(nx,y,nz,c) = (T)(w1*value + w2*(*this)(nx,y,nz,c)); } } if (ny>=0 && ny<height()) { if (x>=0 && x<width()) { const float w1 = (1-dx)*dy*dz, w2 = is_added?1:(1-w1); (*this)(x,ny,nz,c) = (T)(w1*value + w2*(*this)(x,ny,nz,c)); } if (nx>=0 && nx<width()) { const float w1 = dx*dy*dz, w2 = is_added?1:(1-w1); (*this)(nx,ny,nz,c) = (T)(w1*value + w2*(*this)(nx,ny,nz,c)); } } } } return *this; } //! Return a C-string containing a list of all values of the image instance. /** Return a new \c CImg<char> image whose buffer data() is a \c char* string describing the list of all pixel values of the image instance (written in base 10), separated by specified \c separator character. \param separator A \c char character which specifies the separator between values in the returned C-string. \param max_size Maximum size of the returned image. \note - The returned image is never empty. - For an empty image instance, the returned string is <tt>""</tt>. - If \c max_size is equal to \c 0, there are no limits on the size of the returned string. - Otherwise, if the maximum number of string characters is exceeded, the value string is cut off and terminated by character \c '\0'. In that case, the returned image size is <tt>max_size + 1</tt>. **/ CImg<charT> value_string(const char separator=',', const unsigned int max_size=0) const { if (is_empty()) return CImg<charT>::string(""); CImgList<charT> items; char s_item[256] = { 0 }; const T *ptrs = _data; unsigned int string_size = 0; for (unsigned long off = 0, siz = (unsigned int)size(); off<siz && string_size<=max_size; ++off) { const unsigned int printed_size = 1U + cimg_snprintf(s_item,sizeof(s_item),cimg::type<T>::format(),cimg::type<T>::format(*(ptrs++))); CImg<charT> item(s_item,printed_size); item[printed_size-1] = separator; item.move_to(items); if (max_size) string_size+=printed_size; } CImg<charT> res; (items>'x').move_to(res); if (max_size && res._width>max_size) res.crop(0,max_size); res.back() = 0; return res; } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Test shared state of the pixel buffer. /** Return \c true if image instance has a shared memory buffer, and \c false otherwise. \note - A shared image do not own his pixel buffer data() and will not deallocate it on destruction. - Most of the time, a \c CImg<T> image instance will \e not be shared. - A shared image can only be obtained by a limited set of constructors and methods (see list below). **/ bool is_shared() const { return _is_shared; } //! Test if image instance is empty. /** Return \c true, if image instance is empty, i.e. does \e not contain any pixel values, has dimensions \c 0 x \c 0 x \c 0 x \c 0 and a pixel buffer pointer set to \c 0 (null pointer), and \c false otherwise. **/ bool is_empty() const { return !(_data && _width && _height && _depth && _spectrum); } //! Test if image instance contains a 'inf' value. /** Return \c true, if image instance contains a 'inf' value, and \c false otherwise. **/ bool is_inf() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_inf((float)*p)) return true; return false; } //! Test if image instance contains a 'nan' value. /** Return \c true, if image instance contains a 'nan' value, and \c false otherwise. **/ bool is_nan() const { if (cimg::type<T>::is_float()) cimg_for(*this,p,T) if (cimg::type<T>::is_nan((float)*p)) return true; return false; } //! Test if image width is equal to specified value. bool is_sameX(const unsigned int size_x) const { return _width==size_x; } //! Test if image width is equal to specified value. template<typename t> bool is_sameX(const CImg<t>& img) const { return is_sameX(img._width); } //! Test if image width is equal to specified value. bool is_sameX(const CImgDisplay& disp) const { return is_sameX(disp._width); } //! Test if image height is equal to specified value. bool is_sameY(const unsigned int size_y) const { return _height==size_y; } //! Test if image height is equal to specified value. template<typename t> bool is_sameY(const CImg<t>& img) const { return is_sameY(img._height); } //! Test if image height is equal to specified value. bool is_sameY(const CImgDisplay& disp) const { return is_sameY(disp._height); } //! Test if image depth is equal to specified value. bool is_sameZ(const unsigned int size_z) const { return _depth==size_z; } //! Test if image depth is equal to specified value. template<typename t> bool is_sameZ(const CImg<t>& img) const { return is_sameZ(img._depth); } //! Test if image spectrum is equal to specified value. bool is_sameC(const unsigned int size_c) const { return _spectrum==size_c; } //! Test if image spectrum is equal to specified value. template<typename t> bool is_sameC(const CImg<t>& img) const { return is_sameC(img._spectrum); } //! Test if image width and height are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameY(unsigned int) const are both verified. **/ bool is_sameXY(const unsigned int size_x, const unsigned int size_y) const { return _width==size_x && _height==size_y; } //! Test if image width and height are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameY(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXY(const CImg<t>& img) const { return is_sameXY(img._width,img._height); } //! Test if image width and height are the same as that of an existing display window. /** Test if is_sameX(const CImgDisplay&) const and is_sameY(const CImgDisplay&) const are both verified. **/ bool is_sameXY(const CImgDisplay& disp) const { return is_sameXY(disp._width,disp._height); } //! Test if image width and depth are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXZ(const unsigned int size_x, const unsigned int size_z) const { return _width==size_x && _depth==size_z; } //! Test if image width and depth are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZ(const CImg<t>& img) const { return is_sameXZ(img._width,img._depth); } //! Test if image width and spectrum are equal to specified values. /** Test if is_sameX(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXC(const unsigned int size_x, const unsigned int size_c) const { return _width==size_x && _spectrum==size_c; } //! Test if image width and spectrum are the same as that of another image. /** Test if is_sameX(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXC(const CImg<t>& img) const { return is_sameXC(img._width,img._spectrum); } //! Test if image height and depth are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameYZ(const unsigned int size_y, const unsigned int size_z) const { return _height==size_y && _depth==size_z; } //! Test if image height and depth are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZ(const CImg<t>& img) const { return is_sameYZ(img._height,img._depth); } //! Test if image height and spectrum are equal to specified values. /** Test if is_sameY(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYC(const unsigned int size_y, const unsigned int size_c) const { return _height==size_y && _spectrum==size_c; } //! Test if image height and spectrum are the same as that of another image. /** Test if is_sameY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYC(const CImg<t>& img) const { return is_sameYC(img._height,img._spectrum); } //! Test if image depth and spectrum are equal to specified values. /** Test if is_sameZ(unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameZC(const unsigned int size_z, const unsigned int size_c) const { return _depth==size_z && _spectrum==size_c; } //! Test if image depth and spectrum are the same as that of another image. /** Test if is_sameZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameZC(const CImg<t>& img) const { return is_sameZC(img._depth,img._spectrum); } //! Test if image width, height and depth are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameZ(unsigned int) const are both verified. **/ bool is_sameXYZ(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z) const { return is_sameXY(size_x,size_y) && _depth==size_z; } //! Test if image width, height and depth are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameZ(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZ(const CImg<t>& img) const { return is_sameXYZ(img._width,img._height,img._depth); } //! Test if image width, height and spectrum are equal to specified values. /** Test if is_sameXY(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_c) const { return is_sameXY(size_x,size_y) && _spectrum==size_c; } //! Test if image width, height and spectrum are the same as that of another image. /** Test if is_sameXY(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYC(const CImg<t>& img) const { return is_sameXYC(img._width,img._height,img._spectrum); } //! Test if image width, depth and spectrum are equal to specified values. /** Test if is_sameXZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXZC(const unsigned int size_x, const unsigned int size_z, const unsigned int size_c) const { return is_sameXZ(size_x,size_z) && _spectrum==size_c; } //! Test if image width, depth and spectrum are the same as that of another image. /** Test if is_sameXZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXZC(const CImg<t>& img) const { return is_sameXZC(img._width,img._depth,img._spectrum); } //! Test if image height, depth and spectrum are equal to specified values. /** Test if is_sameYZ(unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameYZC(const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameYZ(size_y,size_z) && _spectrum==size_c; } //! Test if image height, depth and spectrum are the same as that of another image. /** Test if is_sameYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameYZC(const CImg<t>& img) const { return is_sameYZC(img._height,img._depth,img._spectrum); } //! Test if image width, height, depth and spectrum are equal to specified values. /** Test if is_sameXYZ(unsigned int,unsigned int,unsigned int) const and is_sameC(unsigned int) const are both verified. **/ bool is_sameXYZC(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c) const { return is_sameXYZ(size_x,size_y,size_z) && _spectrum==size_c; } //! Test if image width, height, depth and spectrum are the same as that of another image. /** Test if is_sameXYZ(const CImg<t>&) const and is_sameC(const CImg<t>&) const are both verified. **/ template<typename t> bool is_sameXYZC(const CImg<t>& img) const { return is_sameXYZC(img._width,img._height,img._depth,img._spectrum); } //! Test if specified coordinates are inside image bounds. /** Return \c true if pixel located at (\c x,\c y,\c z,\c c) is inside bounds of the image instance, and \c false otherwise. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note - Return \c true only if all these conditions are verified: - The image instance is \e not empty. - <tt>0<=x<=\ref width()-1</tt>. - <tt>0<=y<=\ref height()-1</tt>. - <tt>0<=z<=\ref depth()-1</tt>. - <tt>0<=c<=\ref spectrum()-1</tt>. **/ bool containsXYZC(const int x, const int y=0, const int z=0, const int c=0) const { return !is_empty() && x>=0 && x<width() && y>=0 && y<height() && z>=0 && z<depth() && c>=0 && c<spectrum(); } //! Test if pixel value is inside image bounds and get its X,Y,Z and C-coordinates. /** Return \c true, if specified reference refers to a pixel value inside bounds of the image instance, and \c false otherwise. \param pixel Reference to pixel value to test. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note - Useful to convert an offset to a buffer value into pixel value coordinates: \code const CImg<float> img(100,100,1,3); // Construct a 100x100 RGB color image. const unsigned long offset = 1249; // Offset to the pixel (49,12,0,0). unsigned int x,y,z,c; if (img.contains(img[offset],x,y,z,c)) { // Convert offset to (x,y,z,c) coordinates. std::printf("Offset %u refers to pixel located at (%u,%u,%u,%u).\n", offset,x,y,z,c); } \endcode **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z, t& c) const { const unsigned long wh = (unsigned long)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data+siz) return false; unsigned long off = (unsigned long)(ppixel - _data); const unsigned long nc = off/whd; off%=whd; const unsigned long nz = off/wh; off%=wh; const unsigned long ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; c = (t)nc; return true; } //! Test if pixel value is inside image bounds and get its X,Y and Z-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X,Y and Z-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y, t& z) const { const unsigned long wh = (unsigned long)_width*_height, whd = wh*_depth, siz = whd*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data+siz) return false; unsigned long off = ((unsigned long)(ppixel - _data))%whd; const unsigned long nz = off/wh; off%=wh; const unsigned long ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; z = (t)nz; return true; } //! Test if pixel value is inside image bounds and get its X and Y-coordinates. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X and Y-coordinates are set. **/ template<typename t> bool contains(const T& pixel, t& x, t& y) const { const unsigned long wh = (unsigned long)_width*_height, siz = wh*_depth*_spectrum; const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data+siz) return false; unsigned long off = ((unsigned int)(ppixel - _data))%wh; const unsigned long ny = off/_width, nx = off%_width; x = (t)nx; y = (t)ny; return true; } //! Test if pixel value is inside image bounds and get its X-coordinate. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that only the X-coordinate is set. **/ template<typename t> bool contains(const T& pixel, t& x) const { const T *const ppixel = &pixel; if (is_empty() || ppixel<_data || ppixel>=_data+size()) return false; x = (t)(((unsigned long)(ppixel - _data))%_width); return true; } //! Test if pixel value is inside image bounds. /** Similar to contains(const T&,t&,t&,t&,t&) const, except that no pixel coordinates are set. **/ bool contains(const T& pixel) const { const T *const ppixel = &pixel; return !is_empty() && ppixel>=_data && ppixel<_data + size(); } //! Test if pixel buffers of instance and input images overlap. /** Return \c true, if pixel buffers attached to image instance and input image \c img overlap, and \c false otherwise. \param img Input image to compare with. \note - Buffer overlapping may happen when manipulating \e shared images. - If two image buffers overlap, operating on one of the image will probably modify the other one. - Most of the time, \c CImg<T> instances are \e non-shared and do not overlap between each others. \par Example \code const CImg<float> img1("reference.jpg"), // Load RGB-color image. img2 = img1.get_shared_channel(1); // Get shared version of the green channel. if (img1.is_overlapped(img2)) { // Test succeeds, 'img1' and 'img2' overlaps. std::printf("Buffers overlap!\n"); } \endcode **/ template<typename t> bool is_overlapped(const CImg<t>& img) const { const unsigned long csiz = size(), isiz = img.size(); return !((void*)(_data + csiz)<=(void*)img._data || (void*)_data>=(void*)(img._data + isiz)); } //! Test if the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3d object. /** Return \c true is the 3d object represented by the set {\c *this,\c primitives,\c colors,\c opacities} defines a valid 3d object, and \c false otherwise. The vertex coordinates are defined by the instance image. \param primitives List of primitives of the 3d object. \param colors List of colors of the 3d object. \param opacities List (or image) of opacities of the 3d object. \param is_full_check Tells if full checking of the 3d object must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c is_full_checking to \c false to speed-up the 3d object checking. In this case, only the size of each 3d object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ template<typename tp, typename tc, typename to> bool is_object3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities, const bool is_full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check consistency for the particular case of an empty 3d object. if (is_empty()) { if (primitives || colors || opacities) { if (error_message) std::sprintf(error_message, "3d object has no vertices but %u primitives, %u colors and %lu opacities", primitives._width,colors._width,(unsigned long)opacities.size()); return false; } return true; } // Check consistency of vertices. if (_height!=3 || _depth>1 || _spectrum>1) { // Check vertices dimensions. if (error_message) std::sprintf(error_message, "3d object (%u,%u) has invalid vertices dimensions (%u,%u,%u,%u)", _width,primitives._width,_width,_height,_depth,_spectrum); return false; } if (colors._width>primitives._width+1) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) defines %u colors", _width,primitives._width,colors._width); return false; } if (opacities.size()>primitives._width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) defines %lu opacities", _width,primitives._width,(unsigned long)opacities.size()); return false; } if (!is_full_check) return true; // Check consistency of primitives. cimglist_for(primitives,l) { const CImg<tp>& primitive = primitives[l]; const unsigned long psiz = primitive.size(); switch (psiz) { case 1 : { // Point. const unsigned int i0 = (unsigned int)primitive(0); if (i0>=_width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) refers to invalid vertex indice %u in point primitive %u", _width,primitives._width,i0,l); return false; } } break; case 5 : { // Sphere. const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) refers to invalid vertex indices (%u,%u) in sphere primitive %u", _width,primitives._width,i0,i1,l); return false; } } break; case 2 : // Segment. case 6 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); if (i0>=_width || i1>=_width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) refers to invalid vertex indices (%u,%u) in segment primitive %u", _width,primitives._width,i0,i1,l); return false; } } break; case 3 : // Triangle. case 9 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); if (i0>=_width || i1>=_width || i2>=_width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) refers to invalid vertex indices (%u,%u,%u) in triangle primitive %u", _width,primitives._width,i0,i1,i2,l); return false; } } break; case 4 : // Quadrangle. case 12 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); if (i0>=_width || i1>=_width || i2>=_width || i3>=_width) { if (error_message) std::sprintf(error_message, "3d object (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in quadrangle primitive %u", _width,primitives._width,i0,i1,i2,i3,l); return false; } } break; default : if (error_message) std::sprintf(error_message, "3d object has invalid primitive %u of size %u", l,(unsigned int)psiz); return false; } } // Check consistency of colors. cimglist_for(colors,c) { const CImg<tc>& color = colors[c]; if (!color) { if (error_message) std::sprintf(error_message, "3d object has empty color for primitive %u", c); return false; } } // Check consistency of light texture. if (colors._width>primitives._width) { const CImg<tc> &light = colors.back(); if (!light || light._depth>1) { if (error_message) std::sprintf(error_message, "3d object has invalid light texture (%u,%u,%u,%u)", light._width,light._height,light._depth,light._spectrum); return false; } } return true; } //! Test if image instance represents a valid serialization of a 3d object. /** Return \c true if the image instance represents a valid serialization of a 3d object, and \c false otherwise. \param is_full_check Tells if full checking of the instance must be performed. \param[out] error_message C-string to contain the error message, if the test does not succeed. \note - Set \c is_full_checking to \c false to speed-up the 3d object checking. In this case, only the size of each 3d object component is checked. - Size of the string \c error_message should be at least 128-bytes long, to be able to contain the error message. **/ bool is_CImg3d(const bool is_full_check=true, char *const error_message=0) const { if (error_message) *error_message = 0; // Check instance dimension and header. if (_width!=1 || _height<8 || _depth!=1 || _spectrum!=1) { if (error_message) std::sprintf(error_message, "CImg3d has invalid dimensions (%u,%u,%u,%u)", _width,_height,_depth,_spectrum); return false; } const T *ptrs = _data, *const ptre = end(); if (!_is_CImg3d(*(ptrs++),'C') || !_is_CImg3d(*(ptrs++),'I') || !_is_CImg3d(*(ptrs++),'m') || !_is_CImg3d(*(ptrs++),'g') || !_is_CImg3d(*(ptrs++),'3') || !_is_CImg3d(*(ptrs++),'d')) { if (error_message) std::sprintf(error_message, "CImg3d header not found"); return false; } const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); // Check consistency of vertex data. if (!nb_points) { if (nb_primitives) { if (error_message) std::sprintf(error_message, "CImg3d has no vertices but %u primitives", nb_primitives); return false; } if (ptrs!=ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) is empty but contains %u byte%s more than expected", nb_points,nb_primitives,(unsigned int)(ptre-ptrs),(ptre-ptrs)>1?"s":""); return false; } return true; } ptrs+=3*nb_points; if (ptrs>ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has incomplete vertex data", nb_points,nb_primitives); return false; } if (!is_full_check) return true; // Check consistency of primitive data. if (ptrs==ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has no primitive data", nb_points,nb_primitives); return false; } for (unsigned int p = 0; p<nb_primitives; ++p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); switch (nb_inds) { case 1 : { // Point. const unsigned int i0 = cimg::float2uint((float)*(ptrs++)); if (i0>=nb_points) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indice %u in point primitive %u", nb_points,nb_primitives,i0,p); return false; } } break; case 5 : { // Sphere. const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); ptrs+=3; if (i0>=nb_points || i1>=nb_points) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in sphere primitive %u", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 2 : case 6 : { // Segment. const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==6) ptrs+=4; if (i0>=nb_points || i1>=nb_points) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u) in segment primitive %u", nb_points,nb_primitives,i0,i1,p); return false; } } break; case 3 : case 9 : { // Triangle. const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==9) ptrs+=6; if (i0>=nb_points || i1>=nb_points || i2>=nb_points) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u) in triangle primitive %u", nb_points,nb_primitives,i0,i1,i2,p); return false; } } break; case 4 : case 12 : { // Quadrangle. const unsigned int i0 = cimg::float2uint((float)*(ptrs++)), i1 = cimg::float2uint((float)*(ptrs++)), i2 = cimg::float2uint((float)*(ptrs++)), i3 = cimg::float2uint((float)*(ptrs++)); if (nb_inds==12) ptrs+=8; if (i0>=nb_points || i1>=nb_points || i2>=nb_points || i3>=nb_points) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid vertex indices (%u,%u,%u,%u) in quadrangle primitive %u", nb_points,nb_primitives,i0,i1,i2,i3,p); return false; } } break; default : if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has invalid primitive %u of size %u", nb_points,nb_primitives,p,nb_inds); return false; } if (ptrs>ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has incomplete primitive data for primitive %u", nb_points,nb_primitives,p); return false; } } // Check consistency of color data. if (ptrs==ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has no color/texture data", nb_points,nb_primitives); return false; } for (unsigned int c = 0; c<nb_primitives; ++c) { if (*(ptrs++)!=(T)-128) ptrs+=2; else if ((ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs-3), h = (unsigned int)*(ptrs-2), s = (unsigned int)*(ptrs-1); if (!h && !s) { if (w>=c) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared sprite/texture indice %u for primitive %u", nb_points,nb_primitives,w,c); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has incomplete color/texture data for primitive %u", nb_points,nb_primitives,c); return false; } } // Check consistency of opacity data. if (ptrs==ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has no opacity data", nb_points,nb_primitives); return false; } for (unsigned int o = 0; o<nb_primitives; ++o) { if (*(ptrs++)==(T)-128 && (ptrs+=3)<ptre) { const unsigned int w = (unsigned int)*(ptrs-3), h = (unsigned int)*(ptrs-2), s = (unsigned int)*(ptrs-1); if (!h && !s) { if (w>=o) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) refers to invalid shared opacity indice %u for primitive %u", nb_points,nb_primitives,w,o); return false; } } else ptrs+=w*h*s; } if (ptrs>ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) has incomplete opacity data for primitive %u", nb_points,nb_primitives,o); return false; } } // Check end of data. if (ptrs<ptre) { if (error_message) std::sprintf(error_message, "CImg3d (%u,%u) contains %u byte%s more than expected", nb_points,nb_primitives,(unsigned int)(ptre-ptrs),(ptre-ptrs)>1?"s":""); return false; } return true; } static bool _is_CImg3d(const T val, const char c) { return val>=(T)c && val<(T)(c+1); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- // Define the math formula parser/compiler and evaluator. struct _cimg_math_parser { CImgList<charT> label; CImgList<uintT> code; CImg<uintT> level, opcode; CImg<doubleT> mem; CImg<charT> expr; const CImg<T>& reference; CImg<Tdouble> reference_stats; unsigned int mempos, result; const char *const calling_function; #define _cimg_mp_return(x) { *se = saved_char; return x; } #define _cimg_mp_opcode0(op) _cimg_mp_return(opcode0(op)); #define _cimg_mp_opcode1(op,i1) _cimg_mp_return(opcode1(op,i1)); #define _cimg_mp_opcode2(op,i1,i2) { const unsigned int _i1 = i1, _i2 = i2; _cimg_mp_return(opcode2(op,_i1,_i2)); } #define _cimg_mp_opcode3(op,i1,i2,i3) { const unsigned int _i1 = i1, _i2 = i2, _i3 = i3; _cimg_mp_return(opcode3(op,_i1,_i2,_i3)); } #define _cimg_mp_opcode6(op,i1,i2,i3,i4,i5,i6) { const unsigned int _i1 = i1, _i2 = i2, _i3 = i3, _i4 = i4, _i5 = i5, _i6 = i6; \ _cimg_mp_return(opcode6(op,_i1,_i2,_i3,_i4,_i5,_i6)); } // Constructor - Destructor. _cimg_math_parser(const CImg<T>& img, const char *const expression, const char *const funcname=0): reference(img),calling_function(funcname?funcname:"cimg_math_parser") { unsigned int l = 0; if (expression) { l = (unsigned int)std::strlen(expression); expr.assign(expression,l+1); if (*expr._data) { char *d = expr._data; for (const char *s = expr._data; *s || (bool)(*d=0); ++s) if (*s!=' ') *(d++) = *s; l = (unsigned int)(d - expr._data); } } if (!l) throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Empty specified expression.", pixel_type(),calling_function); int lv = 0; // Count parenthesis level of expression. level.assign(l); unsigned int *pd = level._data; for (const char *ps = expr._data; *ps && lv>=0; ++ps) *(pd++) = (unsigned int)(*ps=='('?lv++:*ps==')'?--lv:lv); if (lv!=0) { throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Unbalanced parentheses in specified expression '%s'.", pixel_type(),calling_function, expr._data); } // Init constant values. mem.assign(512); label.assign(512); mem[0] = 0; mem[1] = 1; mem[2] = (double)reference._width; mem[3] = (double)reference._height; mem[4] = (double)reference._depth; mem[5] = (double)reference._spectrum; mem[6] = cimg::PI; mem[7] = std::exp(1.0); // Then [8] = x, [9] = y, [10] = z, [11] = c mempos = 12; result = compile(expr._data,expr._data+l); // Compile formula into a serie of opcodes. } // Insert code instructions. unsigned int opcode0(const char op) { if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(op,pos).move_to(code); return pos; } unsigned int opcode1(const char op, const unsigned int arg1) { if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(op,pos,arg1).move_to(code); return pos; } unsigned int opcode2(const char op, const unsigned int arg1, const unsigned int arg2) { if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(op,pos,arg1,arg2).move_to(code); return pos; } unsigned int opcode3(const char op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3) { if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(op,pos,arg1,arg2,arg3).move_to(code); return pos; } unsigned int opcode6(const char op, const unsigned int arg1, const unsigned int arg2, const unsigned int arg3, const unsigned int arg4, const unsigned int arg5, const unsigned int arg6) { if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(op,pos,arg1,arg2,arg3,arg4,arg5,arg6).move_to(code); return pos; } // Compilation procedure. unsigned int compile(char *const ss, char *const se) { if (!ss || se<=ss || !*ss) { throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Missing item in specified expression '%s'.", pixel_type(),calling_function, expr._data); } char *const se1 = se-1, *const se2 = se-2, *const se3 = se-3, *const se4 = se-4, *const ss1 = ss+1, *const ss2 = ss+2, *const ss3 = ss+3, *const ss4 = ss+4, *const ss5 = ss+5, *const ss6 = ss+6, *const ss7 = ss+7; const char saved_char = *se; *se = 0; const unsigned int clevel = level[ss-expr._data], clevel1 = clevel+1; if (*se1==';') return compile(ss,se1); // Look for a single value, variable or variable assignment. char end = 0, sep = 0; double val = 0; const int nb = std::sscanf(ss,"%lf%c%c",&val,&sep,&end); if (nb==1) { if (val==0) _cimg_mp_return(0); if (val==1) _cimg_mp_return(1); if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; mem[pos] = val; _cimg_mp_return(pos); } if (nb==2 && sep=='%') { if (val==0) _cimg_mp_return(0); if (val==100) _cimg_mp_return(1); if (mempos>=mem._width) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; mem[pos] = val/100; _cimg_mp_return(pos); } if (ss1==se) switch (*ss) { case 'w' : _cimg_mp_return(2); case 'h' : _cimg_mp_return(3); case 'd' : _cimg_mp_return(4); case 's' : _cimg_mp_return(5); case 'x' : _cimg_mp_return(8); case 'y' : _cimg_mp_return(9); case 'z' : _cimg_mp_return(10); case 'c' : _cimg_mp_return(11); case 'e' : _cimg_mp_return(7); case 'u' : case '?' : _cimg_mp_opcode2(0,0,1); case 'g' : _cimg_mp_opcode0(1); case 'i' : _cimg_mp_opcode0(2); } if (ss1==se1) { if (*ss=='p' && *ss1=='i') _cimg_mp_return(6); // pi if (*ss=='i') { if (*ss1=='m') _cimg_mp_opcode0(57); // im if (*ss1=='M') _cimg_mp_opcode0(58); // iM if (*ss1=='a') _cimg_mp_opcode0(59); // ia if (*ss1=='v') _cimg_mp_opcode0(60); // iv } if (*ss1=='m') { if (*ss=='x') _cimg_mp_opcode0(61); // xm if (*ss=='y') _cimg_mp_opcode0(62); // ym if (*ss=='z') _cimg_mp_opcode0(63); // zm if (*ss=='c') _cimg_mp_opcode0(64); // cm } if (*ss1=='M') { if (*ss=='x') _cimg_mp_opcode0(65); // xM if (*ss=='y') _cimg_mp_opcode0(66); // yM if (*ss=='z') _cimg_mp_opcode0(67); // zM if (*ss=='c') _cimg_mp_opcode0(68); // cM } } if (ss3==se) { if (*ss=='x' && *ss1=='/' && *ss2=='w') _cimg_mp_opcode0(3); if (*ss=='y' && *ss1=='/' && *ss2=='h') _cimg_mp_opcode0(4); if (*ss=='z' && *ss1=='/' && *ss2=='d') _cimg_mp_opcode0(5); if (*ss=='c' && *ss1=='/' && *ss2=='s') _cimg_mp_opcode0(6); } // Look for variable declarations. for (char *s = se2; s>ss; --s) if (*s==';' && level[s-expr._data]==clevel) { compile(ss,s); _cimg_mp_return(compile(s+1,se)); } for (char *s = ss1, *ps = ss, *ns = ss2; s<se1; ++s, ++ps, ++ns) if (*s=='=' && *ns!='=' && *ps!='=' && *ps!='>' && *ps!='<' && *ps!='!' && level[s-expr._data]==clevel) { CImg<charT> variable_name(ss,(unsigned int)(s-ss+1)); variable_name.back() = 0; bool is_valid_name = true; if ((*ss>='0' && *ss<='9') || (s==ss+1 && (*ss=='x' || *ss=='y' || *ss=='z' || *ss=='c' || *ss=='w' || *ss=='h' || *ss=='d' || *ss=='s' || *ss=='e' || *ss=='u' || *ss=='g' || *ss=='i')) || (s==ss+2 && ((*ss=='p' && *(ss+1)=='i') || (*ss=='i' && (*(ss+1)=='m' || *(ss+1)=='M' || *(ss+1)=='a' || *(ss+1)=='v')) || (*ss=='x' && (*(ss+1)=='m' || *(ss+1)=='M')) || (*ss=='y' && (*(ss+1)=='m' || *(ss+1)=='M')) || (*ss=='z' && (*(ss+1)=='m' || *(ss+1)=='M')) || (*ss=='c' && (*(ss+1)=='m' || *(ss+1)=='M'))))) is_valid_name = false; for (const char *ns = ss; ns<s; ++ns) if ((*ns<'a' || *ns>'z') && (*ns<'A' || *ns>'Z') && (*ns<'0' || *ns>'9') && *ns!='_') { is_valid_name = false; break; } if (!is_valid_name) { *se = saved_char; if (!std::strcmp(variable_name,"x") || !std::strcmp(variable_name,"y") || !std::strcmp(variable_name,"z") || !std::strcmp(variable_name,"c") || !std::strcmp(variable_name,"w") || !std::strcmp(variable_name,"h") || !std::strcmp(variable_name,"d") || !std::strcmp(variable_name,"s") || !std::strcmp(variable_name,"e") || !std::strcmp(variable_name,"u") || !std::strcmp(variable_name,"g") || !std::strcmp(variable_name,"i") || !std::strcmp(variable_name,"pi") || !std::strcmp(variable_name,"im") || !std::strcmp(variable_name,"iM") || !std::strcmp(variable_name,"ia") || !std::strcmp(variable_name,"iv") || !std::strcmp(variable_name,"xm") || !std::strcmp(variable_name,"ym") || !std::strcmp(variable_name,"zm") || !std::strcmp(variable_name,"cm") || !std::strcmp(variable_name,"xM") || !std::strcmp(variable_name,"yM") || !std::strcmp(variable_name,"zM") || !std::strcmp(variable_name,"cM")) throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Invalid assignment of reserved variable name '%s' in specified expression '%s'.", pixel_type(),calling_function, variable_name._data,expr._data); else throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Invalid variable name '%s' in specified expression '%s'.", pixel_type(),calling_function, variable_name._data,expr._data); } for (unsigned int i = 0; i<mempos; ++i) // Check for existing variable with same name. if (label[i]._data && !std::strcmp(variable_name,label[i])) { *se = saved_char; throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Invalid multiple assignments of variable '%s' in specified expression '%s'.", pixel_type(),calling_function, variable_name._data,expr._data); } const unsigned int src_pos = compile(s+1,se); if (mempos>=mem.size()) mem.resize(-200,1,1,1,0); const unsigned int dest_pos = mempos++; variable_name.move_to(label[dest_pos]); CImg<uintT>::vector(7,dest_pos,src_pos).move_to(code); _cimg_mp_return(dest_pos); } // Look for unary/binary operators. The operator precedences is defined as in C++. for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='|' && *ns=='|' && level[s-expr._data]==clevel) _cimg_mp_opcode2(8,compile(ss,s),compile(s+2,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='&' && *ns=='&' && level[s-expr._data]==clevel) _cimg_mp_opcode2(9,compile(ss,s),compile(s+2,se)); for (char *s = se2; s>ss; --s) if (*s=='|' && level[s-expr._data]==clevel) _cimg_mp_opcode2(10,compile(ss,s),compile(s+1,se)); for (char *s = se2; s>ss; --s) if (*s=='&' && level[s-expr._data]==clevel) _cimg_mp_opcode2(11,compile(ss,s),compile(s+1,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='!' && *ns=='=' && level[s-expr._data]==clevel) _cimg_mp_opcode2(12,compile(ss,s),compile(s+2,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='=' && *ns=='=' && level[s-expr._data]==clevel) _cimg_mp_opcode2(13,compile(ss,s),compile(s+2,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='=' && level[s-expr._data]==clevel) _cimg_mp_opcode2(14,compile(ss,s),compile(s+2,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='=' && level[s-expr._data]==clevel) _cimg_mp_opcode2(15,compile(ss,s),compile(s+2,se)); for (char *s = se2, *ns = se1, *ps = se3; s>ss; --s, --ns, --ps) if (*s=='<' && *ns!='<' && *ps!='<' && level[s-expr._data]==clevel) _cimg_mp_opcode2(16,compile(ss,s),compile(s+1,se)); for (char *s = se2, *ns = se1, *ps = se3; s>ss; --s, --ns, --ps) if (*s=='>' && *ns!='>' && *ps!='>' && level[s-expr._data]==clevel) _cimg_mp_opcode2(17,compile(ss,s),compile(s+1,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='<' && *ns=='<' && level[s-expr._data]==clevel) _cimg_mp_opcode2(18,compile(ss,s),compile(s+2,se)); for (char *s = se3, *ns = se2; s>ss; --s, --ns) if (*s=='>' && *ns=='>' && level[s-expr._data]==clevel) _cimg_mp_opcode2(19,compile(ss,s),compile(s+2,se)); for (char *s = se2, *ps = se3; s>ss; --s, --ps) if (*s=='+' && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && (*ps!='e' || !(ps>ss && (*(ps-1)=='.' || (*(ps-1)>='0' && *(ps-1)<='9')))) && level[s-expr._data]==clevel) _cimg_mp_opcode2(21,compile(ss,s),compile(s+1,se)); for (char *s = se2, *ps = se3; s>ss; --s, --ps) if (*s=='-' && *ps!='-' && *ps!='+' && *ps!='*' && *ps!='/' && *ps!='%' && *ps!='&' && *ps!='|' && *ps!='^' && *ps!='!' && *ps!='~' && (*ps!='e' || !(ps>ss && (*(ps-1)=='.' || (*(ps-1)>='0' && *(ps-1)<='9')))) && level[s-expr._data]==clevel) _cimg_mp_opcode2(20,compile(ss,s),compile(s+1,se)); for (char *s = se2; s>ss; --s) if (*s=='*' && level[s-expr._data]==clevel) _cimg_mp_opcode2(22,compile(ss,s),compile(s+1,se)); for (char *s = se2; s>ss; --s) if (*s=='/' && level[s-expr._data]==clevel) _cimg_mp_opcode2(23,compile(ss,s),compile(s+1,se)); for (char *s = se2, *ns = se1; s>ss; --s, --ns) if (*s=='%' && *ns!='^' && level[s-expr._data]==clevel) _cimg_mp_opcode2(24,compile(ss,s),compile(s+1,se)); if (ss<se1) { if (*ss=='+') _cimg_mp_return(compile(ss1,se)); if (*ss=='-') _cimg_mp_opcode1(26,compile(ss1,se)); if (*ss=='!') _cimg_mp_opcode1(27,compile(ss1,se)); if (*ss=='~') _cimg_mp_opcode1(28,compile(ss1,se)); } for (char *s = se2; s>ss; --s) if (*s=='^' && level[s-expr._data]==clevel) _cimg_mp_opcode2(25,compile(ss,s),compile(s+1,se)); // Look for a function call or a parenthesis. if (*se1==')') { if (*ss=='(') _cimg_mp_return(compile(ss1,se1)); if (!std::strncmp(ss,"sin(",4)) _cimg_mp_opcode1(29,compile(ss4,se1)); if (!std::strncmp(ss,"cos(",4)) _cimg_mp_opcode1(30,compile(ss4,se1)); if (!std::strncmp(ss,"tan(",4)) _cimg_mp_opcode1(31,compile(ss4,se1)); if (!std::strncmp(ss,"asin(",5)) _cimg_mp_opcode1(32,compile(ss5,se1)); if (!std::strncmp(ss,"acos(",5)) _cimg_mp_opcode1(33,compile(ss5,se1)); if (!std::strncmp(ss,"atan(",5)) _cimg_mp_opcode1(34,compile(ss5,se1)); if (!std::strncmp(ss,"sinh(",5)) _cimg_mp_opcode1(35,compile(ss5,se1)); if (!std::strncmp(ss,"cosh(",5)) _cimg_mp_opcode1(36,compile(ss5,se1)); if (!std::strncmp(ss,"tanh(",5)) _cimg_mp_opcode1(37,compile(ss5,se1)); if (!std::strncmp(ss,"log10(",6)) _cimg_mp_opcode1(38,compile(ss6,se1)); if (!std::strncmp(ss,"log2(",5)) _cimg_mp_opcode1(71,compile(ss5,se1)); if (!std::strncmp(ss,"log(",4)) _cimg_mp_opcode1(39,compile(ss4,se1)); if (!std::strncmp(ss,"exp(",4)) _cimg_mp_opcode1(40,compile(ss4,se1)); if (!std::strncmp(ss,"sqrt(",5)) _cimg_mp_opcode1(41,compile(ss5,se1)); if (!std::strncmp(ss,"sign(",5)) _cimg_mp_opcode1(42,compile(ss5,se1)); if (!std::strncmp(ss,"abs(",4)) _cimg_mp_opcode1(43,compile(ss4,se1)); if (!std::strncmp(ss,"atan2(",6)) { char *s1 = ss6; while (s1<se2 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; _cimg_mp_opcode2(44,compile(ss6,s1),compile(s1+1,se1)); } if (!std::strncmp(ss,"if(",3)) { char *s1 = ss3; while (s1<se4 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; char *s2 = s1+1; while (s2<se2 && (*s2!=',' || level[s2-expr._data]!=clevel1)) ++s2; _cimg_mp_opcode3(45,compile(ss3,s1),compile(s1+1,s2),compile(s2+1,se1)); } if (!std::strncmp(ss,"round(",6)) { unsigned int value = 0, round = 1, direction = 0; char *s1 = ss6; while (s1<se2 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; value = compile(ss6,s1==se2?++s1:s1); if (s1<se1) { char *s2 = s1+1; while (s2<se2 && (*s2!=',' || level[s2-expr._data]!=clevel1)) ++s2; round = compile(s1+1,s2==se2?++s2:s2); if (s2<se1) direction = compile(s2+1,se1); } _cimg_mp_opcode3(46,value,round,direction); } if (!std::strncmp(ss,"?(",2) || !std::strncmp(ss,"u(",2)) { if (*ss2==')') _cimg_mp_opcode2(0,0,1); char *s1 = ss2; while (s1<se1 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; if (s1<se1) _cimg_mp_opcode2(0,compile(ss2,s1),compile(s1+1,se1)); _cimg_mp_opcode2(0,0,compile(ss2,s1)); } if (!std::strncmp(ss,"i(",2)) { if (*ss2==')') _cimg_mp_return(0); unsigned int indx = 8, indy = 9, indz = 10, indc = 11, borders = 0, interpolation = 0; if (ss2!=se1) { char *s1 = ss2; while (s1<se2 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; indx = compile(ss2,s1==se2?++s1:s1); if (s1<se1) { char *s2 = s1+1; while (s2<se2 && (*s2!=',' || level[s2-expr._data]!=clevel1)) ++s2; indy = compile(s1+1,s2==se2?++s2:s2); if (s2<se1) { char *s3 = s2+1; while (s3<se2 && (*s3!=',' || level[s3-expr._data]!=clevel1)) ++s3; indz = compile(s2+1,s3==se2?++s3:s3); if (s3<se1) { char *s4 = s3+1; while (s4<se2 && (*s4!=',' || level[s4-expr._data]!=clevel1)) ++s4; indc = compile(s3+1,s4==se2?++s4:s4); if (s4<se1) { char *s5 = s4+1; while (s5<se2 && (*s5!=',' || level[s5-expr._data]!=clevel1)) ++s5; interpolation = compile(s4+1,s5==se2?++s5:s5); if (s5<se1) borders = compile(s5+1,se1); } } } } } _cimg_mp_opcode6(47,indx,indy,indz,indc,interpolation,borders); } if (!std::strncmp(ss,"min(",4) || !std::strncmp(ss,"max(",4)) { CImgList<uintT> opcode; if (mempos>=mem.size()) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(ss[1]=='i'?48:49,pos).move_to(opcode); for (char *s = ss4; s<se; ++s) { char *ns = s; while (ns<se && (*ns!=',' || level[ns-expr._data]!=clevel1) && (*ns!=')' || level[ns-expr._data]!=clevel)) ++ns; CImg<uintT>::vector(compile(s,ns)).move_to(opcode); s = ns; } (opcode>'y').move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"arg(",4)) { CImgList<uintT> opcode; if (mempos>=mem.size()) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; CImg<uintT>::vector(69,pos).move_to(opcode); for (char *s = ss4; s<se; ++s) { char *ns = s; while (ns<se && (*ns!=',' || level[ns-expr._data]!=clevel1) && (*ns!=')' || level[ns-expr._data]!=clevel)) ++ns; CImg<uintT>::vector(compile(s,ns)).move_to(opcode); s = ns; } (opcode>'y').move_to(code); _cimg_mp_return(pos); } if (!std::strncmp(ss,"narg(",5)) { if (*ss5==')') _cimg_mp_return(0); unsigned int nb_args = 0; for (char *s = ss5; s<se; ++s) { char *ns = s; while (ns<se && (*ns!=',' || level[ns-expr._data]!=clevel1) && (*ns!=')' || level[ns-expr._data]!=clevel)) ++ns; ++nb_args; s = ns; } if (nb_args==0 || nb_args==1) _cimg_mp_return(nb_args); if (mempos>=mem.size()) mem.resize(-200,1,1,1,0); const unsigned int pos = mempos++; mem[pos] = nb_args; _cimg_mp_return(pos); } if (!std::strncmp(ss,"isval(",6)) { char sep = 0, end = 0; double val = 0; if (std::sscanf(ss6,"%lf%c%c",&val,&sep,&end)==2 && sep==')') _cimg_mp_return(1); _cimg_mp_return(0); } if (!std::strncmp(ss,"isnan(",6)) _cimg_mp_opcode1(50,compile(ss6,se1)); if (!std::strncmp(ss,"isinf(",6)) _cimg_mp_opcode1(51,compile(ss6,se1)); if (!std::strncmp(ss,"isint(",6)) _cimg_mp_opcode1(52,compile(ss6,se1)); if (!std::strncmp(ss,"isbool(",7)) _cimg_mp_opcode1(53,compile(ss7,se1)); if (!std::strncmp(ss,"rol(",4) || !std::strncmp(ss,"ror(",4)) { unsigned int value = 0, nb = 1; char *s1 = ss4; while (s1<se2 && (*s1!=',' || level[s1-expr._data]!=clevel1)) ++s1; value = compile(ss4,s1==se2?++s1:s1); if (s1<se1) { char *s2 = s1+1; while (s2<se2 && (*s2!=',' || level[s2-expr._data]!=clevel1)) ++s2; nb = compile(s1+1,se1); } _cimg_mp_opcode2(*ss2=='l'?54:55,value,nb); } if (!std::strncmp(ss,"sinc(",5)) _cimg_mp_opcode1(56,compile(ss5,se1)); if (!std::strncmp(ss,"int(",4)) _cimg_mp_opcode1(70,compile(ss4,se1)); } // No known item found, assuming this is an already initialized variable. CImg<charT> variable_name(ss,(unsigned int)(se-ss+1)); variable_name.back() = 0; for (unsigned int i = 0; i<mempos; ++i) if (label[i]._data && !std::strcmp(variable_name,label[i])) _cimg_mp_return(i); *se = saved_char; throw CImgArgumentException("[_cimg_math_parser] " "CImg<%s>::%s(): Invalid item '%s' in specified expression '%s'.\n", pixel_type(),calling_function, variable_name._data,expr._data); return 0; } // Evaluation functions, known by the parser. double mp_u() { return mem[opcode(2)] + cimg::rand()*(mem[opcode(3)]-mem[opcode(2)]); } double mp_g() { return cimg::grand(); } double mp_i() { return (double)reference.atXYZC((int)mem[8],(int)mem[9],(int)mem[10],(int)mem[11],0); } double mp_xw() { return mem[8]/reference.width(); } double mp_yh() { return mem[9]/reference.height(); } double mp_zd() { return mem[10]/reference.depth(); } double mp_cs() { return mem[11]/reference.spectrum(); } double mp_equal() { return mem[opcode[2]]; } double mp_logical_and() { return (double)((bool)mem[opcode(2)] && (bool)mem[opcode(3)]); } double mp_logical_or() { return (double)((bool)mem[opcode(2)] || (bool)mem[opcode(3)]); } double mp_infeq() { return (double)(mem[opcode(2)]<=mem[opcode(3)]); } double mp_supeq() { return (double)(mem[opcode(2)]>=mem[opcode(3)]); } double mp_noteq() { return (double)(mem[opcode(2)]!=mem[opcode(3)]); } double mp_eqeq() { return (double)(mem[opcode(2)]==mem[opcode(3)]); } double mp_inf() { return (double)(mem[opcode(2)]<mem[opcode(3)]); } double mp_sup() { return (double)(mem[opcode(2)]>mem[opcode(3)]); } double mp_add() { return mem[opcode(2)] + mem[opcode(3)]; } double mp_sub() { return mem[opcode(2)] - mem[opcode(3)]; } double mp_mul() { return mem[opcode(2)] * mem[opcode(3)]; } double mp_div() { return mem[opcode(2)] / mem[opcode(3)]; } double mp_minus() { return -mem[opcode(2)]; } double mp_not() { return !mem[opcode(2)]; } double mp_logical_not() { return !mem[opcode(2)]; } double mp_bitwise_not() { return ~(unsigned long)mem[opcode(2)]; } double mp_modulo() { return cimg::mod(mem[opcode(2)],mem[opcode(3)]); } double mp_bitwise_and() { return ((unsigned long)mem[opcode(2)] & (unsigned long)mem[opcode(3)]); } double mp_bitwise_or() { return ((unsigned long)mem[opcode(2)] | (unsigned long)mem[opcode(3)]); } double mp_pow() { return std::pow(mem[opcode(2)],mem[opcode(3)]); } double mp_sin() { return std::sin(mem[opcode(2)]); } double mp_cos() { return std::cos(mem[opcode(2)]); } double mp_tan() { return std::tan(mem[opcode(2)]); } double mp_asin() { return std::asin(mem[opcode(2)]); } double mp_acos() { return std::acos(mem[opcode(2)]); } double mp_atan() { return std::atan(mem[opcode(2)]); } double mp_sinh() { return std::sinh(mem[opcode(2)]); } double mp_cosh() { return std::cosh(mem[opcode(2)]); } double mp_tanh() { return std::tanh(mem[opcode(2)]); } double mp_log10() { return std::log10(mem[opcode(2)]); } double mp_log2() { return cimg::log2(mem[opcode(2)]); } double mp_log() { return std::log(mem[opcode(2)]); } double mp_exp() { return std::exp(mem[opcode(2)]); } double mp_sqrt() { return std::sqrt(mem[opcode(2)]); } double mp_sign() { return cimg::sign(mem[opcode(2)]); } double mp_abs() { return cimg::abs(mem[opcode(2)]); } double mp_atan2() { return std::atan2(mem[opcode(2)],mem[opcode(3)]); } double mp_if() { return mem[opcode(2)]?mem[opcode(3)]:mem[opcode(4)]; } double mp_round() { return cimg::round(mem[opcode(2)],mem[opcode(3)],(int)mem[opcode(4)]); } double mp_ixyzc() { const int i = (int)mem[opcode(6)], b = (int)mem[opcode(7)]; if (i==0) { // Nearest neighbor interpolation. if (b==2) return (double)reference.atXYZC(cimg::mod((int)mem[opcode(2)],reference.width()), cimg::mod((int)mem[opcode(3)],reference.height()), cimg::mod((int)mem[opcode(4)],reference.depth()), cimg::mod((int)mem[opcode(5)],reference.spectrum())); if (b==1) return (double)reference.atXYZC((int)mem[opcode(2)], (int)mem[opcode(3)], (int)mem[opcode(4)], (int)mem[opcode(5)]); return (double)reference.atXYZC((int)mem[opcode(2)], (int)mem[opcode(3)], (int)mem[opcode(4)], (int)mem[opcode(5)],0); } else { // Linear interpolation. if (b==2) return (double)reference.linear_atXYZC(cimg::mod((float)mem[opcode(2)],(float)reference.width()), cimg::mod((float)mem[opcode(3)],(float)reference.height()), cimg::mod((float)mem[opcode(4)],(float)reference.depth()), cimg::mod((float)mem[opcode(5)],(float)reference.spectrum())); if (b==1) return (double)reference.linear_atXYZC((float)mem[opcode(2)], (float)mem[opcode(3)], (float)mem[opcode(4)], (float)mem[opcode(5)]); return (double)reference.linear_atXYZC((float)mem[opcode(2)], (float)mem[opcode(3)], (float)mem[opcode(4)], (float)mem[opcode(5)],0); } } double mp_min() { double val = mem[opcode(2)]; for (unsigned int i = 3; i<opcode._height; ++i) val = cimg::min(val,mem[opcode(i)]); return val; } double mp_max() { double val = mem[opcode(2)]; for (unsigned int i = 3; i<opcode._height; ++i) val = cimg::max(val,mem[opcode(i)]); return val; } double mp_isnan() { const double val = mem[opcode(2)]; return !(val==val); } double mp_isinf() { const double val = mem[opcode(2)]; return val==(val+1); } double mp_isint() { const double val = mem[opcode(2)]; return (double)(cimg::mod(val,1.0)==0); } double mp_isbool() { const double val = mem[opcode(2)]; return (val==0.0 || val==1.0); } double mp_rol() { return cimg::rol(mem[opcode(2)],(unsigned int)mem[opcode(3)]); } double mp_ror() { return cimg::ror(mem[opcode(2)],(unsigned int)mem[opcode(3)]); } double mp_lsl() { return (long)mem[opcode(2)]<<(unsigned int)mem[opcode(3)]; } double mp_lsr() { return (long)mem[opcode(2)]>>(unsigned int)mem[opcode(3)]; } double mp_sinc() { return cimg::sinc(mem[opcode(2)]); } double mp_im() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[0]:0; } double mp_iM() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[1]:0; } double mp_ia() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[2]:0; } double mp_iv() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[3]:0; } double mp_xm() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[4]:0; } double mp_ym() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[5]:0; } double mp_zm() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[6]:0; } double mp_cm() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[7]:0; } double mp_xM() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[8]:0; } double mp_yM() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[9]:0; } double mp_zM() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[10]:0; } double mp_cM() { if (!reference_stats) reference.get_stats().move_to(reference_stats); return reference_stats?reference_stats[11]:0; } double mp_arg() { const int _ind = (int)mem[opcode(2)]; const unsigned int nb_args = opcode._height-2, ind = _ind<0?_ind+nb_args:(unsigned int)_ind; if (ind>=nb_args) return 0; return mem[opcode(ind+2)]; } double mp_int() { return (double)(long)mem[opcode(2)]; } // Evaluation procedure, with image data. double eval(const double x, const double y, const double z, const double c) { typedef double (_cimg_math_parser::*mp_func)(); const mp_func mp_funcs[] = { &_cimg_math_parser::mp_u, // 0 &_cimg_math_parser::mp_g, // 1 &_cimg_math_parser::mp_i, // 2 &_cimg_math_parser::mp_xw, // 3 &_cimg_math_parser::mp_yh, // 4 &_cimg_math_parser::mp_zd, // 5 &_cimg_math_parser::mp_cs, // 6 &_cimg_math_parser::mp_equal, // 7 &_cimg_math_parser::mp_logical_or, // 8 &_cimg_math_parser::mp_logical_and, // 9 &_cimg_math_parser::mp_bitwise_or, // 10 &_cimg_math_parser::mp_bitwise_and, // 11 &_cimg_math_parser::mp_noteq, // 12 &_cimg_math_parser::mp_eqeq, // 13 &_cimg_math_parser::mp_infeq, // 14 &_cimg_math_parser::mp_supeq, // 15 &_cimg_math_parser::mp_inf, // 16 &_cimg_math_parser::mp_sup, // 17 &_cimg_math_parser::mp_lsl, // 18 &_cimg_math_parser::mp_lsr, // 19 &_cimg_math_parser::mp_sub, // 20 &_cimg_math_parser::mp_add, // 21 &_cimg_math_parser::mp_mul, // 22 &_cimg_math_parser::mp_div, // 23 &_cimg_math_parser::mp_modulo, // 24 &_cimg_math_parser::mp_pow, // 25 &_cimg_math_parser::mp_minus, // 26 &_cimg_math_parser::mp_logical_not, // 27 &_cimg_math_parser::mp_bitwise_not, // 28 &_cimg_math_parser::mp_sin, // 29 &_cimg_math_parser::mp_cos, // 30 &_cimg_math_parser::mp_tan, // 31 &_cimg_math_parser::mp_asin, // 32 &_cimg_math_parser::mp_acos, // 33 &_cimg_math_parser::mp_atan, // 34 &_cimg_math_parser::mp_sinh, // 35 &_cimg_math_parser::mp_cosh, // 36 &_cimg_math_parser::mp_tanh, // 37 &_cimg_math_parser::mp_log10, // 38 &_cimg_math_parser::mp_log, // 39 &_cimg_math_parser::mp_exp, // 40 &_cimg_math_parser::mp_sqrt, // 41 &_cimg_math_parser::mp_sign, // 42 &_cimg_math_parser::mp_abs, // 43 &_cimg_math_parser::mp_atan2, // 44 &_cimg_math_parser::mp_if, // 45 &_cimg_math_parser::mp_round, // 46 &_cimg_math_parser::mp_ixyzc, // 47 &_cimg_math_parser::mp_min, // 48 &_cimg_math_parser::mp_max, // 49 &_cimg_math_parser::mp_isnan, // 50 &_cimg_math_parser::mp_isinf, // 51 &_cimg_math_parser::mp_isint, // 52 &_cimg_math_parser::mp_isbool, // 53 &_cimg_math_parser::mp_rol, // 54 &_cimg_math_parser::mp_ror, // 55 &_cimg_math_parser::mp_sinc, // 56 &_cimg_math_parser::mp_im, // 57 &_cimg_math_parser::mp_iM, // 58 &_cimg_math_parser::mp_ia, // 59 &_cimg_math_parser::mp_iv, // 60 &_cimg_math_parser::mp_xm, // 61 &_cimg_math_parser::mp_ym, // 62 &_cimg_math_parser::mp_zm, // 63 &_cimg_math_parser::mp_cm, // 64 &_cimg_math_parser::mp_xM, // 65 &_cimg_math_parser::mp_yM, // 66 &_cimg_math_parser::mp_zM, // 67 &_cimg_math_parser::mp_cM, // 68 &_cimg_math_parser::mp_arg, // 69 &_cimg_math_parser::mp_int, // 70 &_cimg_math_parser::mp_log2 // 71 }; if (!mem) return 0; mem[8] = x; mem[9] = y; mem[10] = z; mem[11] = c; opcode._is_shared = true; opcode._width = opcode._depth = opcode._spectrum = 1; cimglist_for(code,l) { const CImg<uintT> &op = code[l]; opcode._data = op._data; opcode._height = op._height; // Allows to avoid parameter passing to evaluation functions. mem[opcode(1)] = (this->*mp_funcs[opcode[0]])(); } return mem[result]; } }; //! Compute the square value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square value \f$I_{(x,y,z,c)}^2\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqr().normalize(0,255)).display(); \endcode \image html ref_sqr.jpg **/ CImg<T>& sqr() { cimg_for(*this,ptrd,T) { const T val = *ptrd; *ptrd = (T)(val*val); }; return *this; } //! Compute the square value of each pixel value \newinstance. CImg<Tfloat> get_sqr() const { return CImg<Tfloat>(*this,false).sqr(); } //! Compute the square root of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its square root \f$\sqrt{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img("reference.jpg"); (img,img.get_sqrt().normalize(0,255)).display(); \endcode \image html ref_sqrt.jpg **/ CImg<T>& sqrt() { cimg_for(*this,ptrd,T) *ptrd = (T)std::sqrt((double)*ptrd); return *this; } //! Compute the square root of each pixel value \newinstance. CImg<Tfloat> get_sqrt() const { return CImg<Tfloat>(*this,false).sqrt(); } //! Compute the exponential of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its exponential \f$e^{I_{(x,y,z,c)}}\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& exp() { cimg_for(*this,ptrd,T) *ptrd = (T)std::exp((double)*ptrd); return *this; } //! Compute the exponential of each pixel value \newinstance. CImg<Tfloat> get_exp() const { return CImg<Tfloat>(*this,false).exp(); } //! Compute the logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its logarithm \f$\mathrm{log}_{e}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& log() { cimg_for(*this,ptrd,T) *ptrd = (T)std::log((double)*ptrd); return *this; } //! Compute the logarithm of each pixel value \newinstance. CImg<Tfloat> get_log() const { return CImg<Tfloat>(*this,false).log(); } //! Compute the base-2 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-2 logarithm \f$\mathrm{log}_{2}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& log2() { cimg_for(*this,ptrd,T) *ptrd = (T)cimg::log2((double)*ptrd); return *this; } //! Compute the base-10 logarithm of each pixel value \newinstance. CImg<Tfloat> get_log2() const { return CImg<Tfloat>(*this,false).log2(); } //! Compute the base-10 logarithm of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its base-10 logarithm \f$\mathrm{log}_{10}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& log10() { cimg_for(*this,ptrd,T) *ptrd = (T)std::log10((double)*ptrd); return *this; } //! Compute the base-10 logarithm of each pixel value \newinstance. CImg<Tfloat> get_log10() const { return CImg<Tfloat>(*this,false).log10(); } //! Compute the absolute value of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its absolute value \f$|I_{(x,y,z,c)}|\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& abs() { cimg_for(*this,ptrd,T) *ptrd = cimg::abs(*ptrd); return *this; } //! Compute the absolute value of each pixel value \newinstance. CImg<Tfloat> get_abs() const { return CImg<Tfloat>(*this,false).abs(); } //! Compute the sign of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sign \f$\mathrm{sign}(I_{(x,y,z,c)})\f$. \note - The sign is set to: - \c 1 if pixel value is strictly positive. - \c -1 if pixel value is strictly negative. - \c 0 if pixel value is equal to \c 0. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& sign() { cimg_for(*this,ptrd,T) *ptrd = cimg::sign(*ptrd); return *this; } //! Compute the sign of each pixel value \newinstance. CImg<Tfloat> get_sign() const { return CImg<Tfloat>(*this,false).sign(); } //! Compute the cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its cosine \f$\cos(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& cos() { cimg_for(*this,ptrd,T) *ptrd = (T)std::cos((double)*ptrd); return *this; } //! Compute the cosine of each pixel value \newinstance. CImg<Tfloat> get_cos() const { return CImg<Tfloat>(*this,false).cos(); } //! Compute the sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sine \f$\sin(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being in \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& sin() { cimg_for(*this,ptrd,T) *ptrd = (T)std::sin((double)*ptrd); return *this; } //! Compute the sine of each pixel value \newinstance. CImg<Tfloat> get_sin() const { return CImg<Tfloat>(*this,false).sin(); } //! Compute the sinc of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its sinc \f$\mathrm{sinc}(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& sinc() { cimg_for(*this,ptrd,T) *ptrd = (T)cimg::sinc((double)*ptrd); return *this; } //! Compute the sinc of each pixel value \newinstance. CImg<Tfloat> get_sinc() const { return CImg<Tfloat>(*this,false).sinc(); } //! Compute the tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its tangent \f$\tan(I_{(x,y,z,c)})\f$. \note - Pixel values are regarded as being exin \e radian. - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& tan() { cimg_for(*this,ptrd,T) *ptrd = (T)std::tan((double)*ptrd); return *this; } //! Compute the tangent of each pixel value \newinstance. CImg<Tfloat> get_tan() const { return CImg<Tfloat>(*this,false).tan(); } //! Compute the hyperbolic cosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic cosine \f$\mathrm{cosh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& cosh() { cimg_for(*this,ptrd,T) *ptrd = (T)std::cosh((double)*ptrd); return *this; } //! Compute the hyperbolic cosine of each pixel value \newinstance. CImg<Tfloat> get_cosh() const { return CImg<Tfloat>(*this,false).cosh(); } //! Compute the hyperbolic sine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic sine \f$\mathrm{sinh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& sinh() { cimg_for(*this,ptrd,T) *ptrd = (T)std::sinh((double)*ptrd); return *this; } //! Compute the hyperbolic sine of each pixel value \newinstance. CImg<Tfloat> get_sinh() const { return CImg<Tfloat>(*this,false).sinh(); } //! Compute the hyperbolic tangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its hyperbolic tangent \f$\mathrm{tanh}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& tanh() { cimg_for(*this,ptrd,T) *ptrd = (T)std::tanh((double)*ptrd); return *this; } //! Compute the hyperbolic tangent of each pixel value \newinstance. CImg<Tfloat> get_tanh() const { return CImg<Tfloat>(*this,false).tanh(); } //! Compute the arccosine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arccosine \f$\mathrm{acos}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& acos() { cimg_for(*this,ptrd,T) *ptrd = (T)std::acos((double)*ptrd); return *this; } //! Compute the arccosine of each pixel value \newinstance. CImg<Tfloat> get_acos() const { return CImg<Tfloat>(*this,false).acos(); } //! Compute the arcsine of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arcsine \f$\mathrm{asin}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& asin() { cimg_for(*this,ptrd,T) *ptrd = (T)std::asin((double)*ptrd); return *this; } //! Compute the arcsine of each pixel value \newinstance. CImg<Tfloat> get_asin() const { return CImg<Tfloat>(*this,false).asin(); } //! Compute the arctangent of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent \f$\mathrm{atan}(I_{(x,y,z,c)})\f$. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. **/ CImg<T>& atan() { cimg_for(*this,ptrd,T) *ptrd = (T)std::atan((double)*ptrd); return *this; } //! Compute the arctangent of each pixel value \newinstance. CImg<Tfloat> get_atan() const { return CImg<Tfloat>(*this,false).atan(); } //! Compute the arctangent2 of each pixel value. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its arctangent2 \f$\mathrm{atan2}(I_{(x,y,z,c)})\f$. \param img Image whose pixel values specify the second argument of the \c atan2() function. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img_x(100,100,1,1,"x-w/2",false), // Define an horizontal centered gradient, from '-width/2' to 'width/2'. img_y(100,100,1,1,"y-h/2",false), // Define a vertical centered gradient, from '-height/2' to 'height/2'. img_atan2 = img_y.get_atan2(img_x); // Compute atan2(y,x) for each pixel value. (img_x,img_y,img_atan2).display(); \endcode **/ template<typename t> CImg<T>& atan2(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return atan2(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::atan2((double)*ptrd,(double)*(ptrs++)); } return *this; } //! Compute the arctangent2 of each pixel value \newinstance. template<typename t> CImg<Tfloat> get_atan2(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).atan2(img); } //! In-place pointwise multiplication. /** Compute the pointwise multiplication between the image instance and the specified input image \c img. \param img Input image, as the second operand of the multiplication. \note - Similar to operator+=(const CImg<t>&), except that it performs a pointwise multiplication instead of an addition. - It does \e not perform a \e matrix multiplication. For this purpose, use operator*=(const CImg<t>&) instead. \par Example \code CImg<float> img("reference.jpg"), shade(img.width,img.height(),1,1,"-(x-w/2)^2-(y-h/2)^2",false); shade.normalize(0,1); (img,shade,img.get_mul(shade)).display(); \endcode **/ template<typename t> CImg<T>& mul(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return mul(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd * *(ptrs++)); } return *this; } //! In-place pointwise multiplication \newinstance. template<typename t> CImg<_cimg_Tt> get_mul(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).mul(img); } //! In-place pointwise division. /** Similar to mul(const CImg<t>&), except that it performs a pointwise division instead of a multiplication. **/ template<typename t> CImg<T>& div(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return div(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++)); } return *this; } //! In-place pointwise division \newinstance. template<typename t> CImg<_cimg_Tt> get_div(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).div(img); } //! Raise each pixel value to a specified power. /** Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by its power \f$I_{(x,y,z,c)}^p\f$. \param p Exponent value. \note - The \inplace of this method statically casts the computed values to the pixel type \c T. - The \newinstance returns a \c CImg<float> image, if the pixel type \c T is \e not float-valued. \par Example \code const CImg<float> img0("reference.jpg"), // Load reference color image. img1 = (img0/255).pow(1.8)*=255, // Compute gamma correction, with gamma = 1.8. img2 = (img0/255).pow(0.5)*=255; // Compute gamma correction, with gamma = 0.5. (img0,img1,img2).display(); \endcode **/ CImg<T>& pow(const double p) { if (p==0) return fill(1); if (p==0.5) { cimg_for(*this,ptrd,T) { const T val = *ptrd; *ptrd = (T)std::sqrt((double)val); } return *this; } if (p==1) return *this; if (p==2) { cimg_for(*this,ptrd,T) { const T val = *ptrd; *ptrd = val*val; } return *this; } if (p==3) { cimg_for(*this,ptrd,T) { const T val = *ptrd; *ptrd = val*val*val; } return *this; } if (p==4) { cimg_for(*this,ptrd,T) { const T val = *ptrd; *ptrd = val*val*val*val; } return *this; } cimg_for(*this,ptrd,T) *ptrd = (T)std::pow((double)*ptrd,p); return *this; } //! Raise each pixel value to a specified power \newinstance. CImg<Tfloat> get_pow(const double p) const { return CImg<Tfloat>(*this,false).pow(p); } //! Raise each pixel value to a power, specified from an expression. /** Similar to operator+=(const char*), except it performs a pointwise exponentiation instead of an addition. **/ CImg<T>& pow(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"pow"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)std::pow((double)*ptrd,mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { CImg<Tfloat> values(_width,_height,_depth,_spectrum); try { values.fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; values.load(expression); } pow(values); } cimg::exception_mode() = omode; return *this; } //! Raise each pixel value to a power, specified from an expression \newinstance. CImg<Tfloat> get_pow(const char *const expression) const { return CImg<Tfloat>(*this,false).pow(expression); } //! Raise each pixel value to a power, pointwisely specified from another image. /** Similar to operator+=(const CImg<t>& img), except that it performs an exponentiation instead of an addition. **/ template<typename t> CImg<T>& pow(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return pow(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)std::pow((double)*ptrd,(double)(*(ptrs++))); } return *this; } //! Raise each pixel value to a power, pointwisely specified from another image \newinstance. template<typename t> CImg<Tfloat> get_pow(const CImg<t>& img) const { return CImg<Tfloat>(*this,false).pow(img); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(unsigned int), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const unsigned int n=1) { cimg_for(*this,ptrd,T) *ptrd = (T)cimg::rol(*ptrd,n); return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const unsigned int n=1) const { return (+*this).rol(n); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const char*), except that it performs a left rotation instead of a left shift. **/ CImg<T>& rol(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"rol"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)cimg::rol(*ptrd,(unsigned int)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { CImg<Tfloat> values(_width,_height,_depth,_spectrum); try { values.fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; values.load(expression); } rol(values); } cimg::exception_mode() = omode; return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. CImg<T> get_rol(const char *const expression) const { return (+*this).rol(expression); } //! Compute the bitwise left rotation of each pixel value. /** Similar to operator<<=(const CImg<t>&), except that it performs a left rotation instead of a left shift. **/ template<typename t> CImg<T>& rol(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return rol(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::rol(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise left rotation of each pixel value \newinstance. template<typename t> CImg<T> get_rol(const CImg<t>& img) const { return (+*this).rol(img); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(unsigned int), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const unsigned int n=1) { cimg_for(*this,ptrd,T) *ptrd = (T)cimg::ror(*ptrd,n); return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const unsigned int n=1) const { return (+*this).ror(n); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const char*), except that it performs a right rotation instead of a right shift. **/ CImg<T>& ror(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"ror"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)cimg::ror(*ptrd,(unsigned int)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { CImg<Tfloat> values(_width,_height,_depth,_spectrum); try { values.fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; values.load(expression); } ror(values); } cimg::exception_mode() = omode; return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. CImg<T> get_ror(const char *const expression) const { return (+*this).ror(expression); } //! Compute the bitwise right rotation of each pixel value. /** Similar to operator>>=(const CImg<t>&), except that it performs a right rotation instead of a right shift. **/ template<typename t> CImg<T>& ror(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return ror(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)cimg::ror(*ptrd,(unsigned int)(*(ptrs++))); } return *this; } //! Compute the bitwise right rotation of each pixel value \newinstance. template<typename t> CImg<T> get_ror(const CImg<t>& img) const { return (+*this).ror(img); } //! Pointwise min operator between instance image and a value. /** \param val Value used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& min(const T val) { cimg_for(*this,ptrd,T) *ptrd = cimg::min(*ptrd,val); return *this; } //! Pointwise min operator between instance image and a value \newinstance. CImg<T> get_min(const T val) const { return (+*this).min(val); } //! Pointwise min operator between two images. /** \param img Image used as the reference argument of the min operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& min(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return min(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = cimg::min((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = cimg::min((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise min operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_min(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).min(img); } //! Pointwise min operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{min}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& min(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"min"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)cimg::min(*ptrd,(T)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { CImg<T> values(_width,_height,_depth,_spectrum); try { values.fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; values.load(expression); } min(values); } cimg::exception_mode() = omode; return *this; } //! Pointwise min operator between an image and an expression \newinstance. CImg<Tfloat> get_min(const char *const expression) const { return CImg<Tfloat>(*this,false).min(expression); } //! Pointwise max operator between instance image and a value. /** \param val Value used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{val})\f$. **/ CImg<T>& max(const T val) { cimg_for(*this,ptrd,T) *ptrd = cimg::max(*ptrd,val); return *this; } //! Pointwise max operator between instance image and a value \newinstance. CImg<T> get_max(const T val) const { return (+*this).max(val); } //! Pointwise max operator between two images. /** \param img Image used as the reference argument of the max operator. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{img}_{(x,y,z,c)})\f$. **/ template<typename t> CImg<T>& max(const CImg<t>& img) { const unsigned long siz = size(), isiz = img.size(); if (siz && isiz) { if (is_overlapped(img)) return max(+img); T *ptrd = _data, *const ptre = _data + siz; if (siz>isiz) for (unsigned long n = siz/isiz; n; --n) for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd) *ptrd = cimg::max((T)*(ptrs++),*ptrd); for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = cimg::max((T)*(ptrs++),*ptrd); } return *this; } //! Pointwise max operator between two images \newinstance. template<typename t> CImg<_cimg_Tt> get_max(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this,false).max(img); } //! Pointwise max operator between an image and an expression. /** \param expression Math formula as a C-string. \note Replace each pixel value \f$I_{(x,y,z,c)}\f$ of the image instance by \f$\mathrm{max}(I_{(x,y,z,c)},\mathrm{expr}_{(x,y,z,c)})\f$. **/ CImg<T>& max(const char *const expression) { const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"max"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) { *ptrd = (T)cimg::max(*ptrd,(T)mp.eval(x,y,z,c)); ++ptrd; } } catch (CImgException&) { CImg<T> values(_width,_height,_depth,_spectrum); try { values.fill(expression,true); } catch (CImgException&) { cimg::exception_mode() = omode; values.load(expression); } max(values); } cimg::exception_mode() = omode; return *this; } //! Pointwise max operator between an image and an expression \newinstance. CImg<Tfloat> get_max(const char *const expression) const { return CImg<Tfloat>(*this,false).max(expression); } //! Return a reference to the minimum pixel value. /** **/ T& min() { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the minimum pixel value \const. const T& min() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min; cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); return *ptr_min; } //! Return a reference to the maximum pixel value. /** **/ T& max() { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the maximum pixel value \const. const T& max() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max; cimg_for(*this,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); return *ptr_max; } //! Return a reference to the minimum pixel value as well as the maximum pixel value. /** \param[out] max_val Maximum pixel value. **/ template<typename t> T& min_max(t& max_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value as well as the maximum pixel value \const. template<typename t> const T& min_max(t& max_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "min_max(): Empty instance.", cimg_instance); const T *ptr_min = _data; T min_value = *ptr_min, max_value = min_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the maximum pixel value as well as the minimum pixel value. /** \param[out] min_val Minimum pixel value. **/ template<typename t> T& max_min(t& min_val) { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the maximum pixel value as well as the minimum pixel value \const. template<typename t> const T& max_min(t& min_val) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "max_min(): Empty instance.", cimg_instance); const T *ptr_max = _data; T max_value = *ptr_max, min_value = max_value; cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } min_val = (t)min_value; return *ptr_max; } //! Return the kth smallest pixel value. /** \param k Rank of the search smallest element. **/ T kth_smallest(const unsigned int k) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "kth_smallest(): Empty instance.", cimg_instance); CImg<T> arr(*this); unsigned int l = 0, ir = size() - 1; for (;;) { if (ir<=l+1) { if (ir==l+1 && arr[ir]<arr[l]) cimg::swap(arr[l],arr[ir]); return arr[k]; } else { const unsigned int mid = (l + ir)>>1; cimg::swap(arr[mid],arr[l+1]); if (arr[l]>arr[ir]) cimg::swap(arr[l],arr[ir]); if (arr[l+1]>arr[ir]) cimg::swap(arr[l+1],arr[ir]); if (arr[l]>arr[l+1]) cimg::swap(arr[l],arr[l+1]); unsigned int i = l + 1, j = ir; const T pivot = arr[l+1]; for (;;) { do ++i; while (arr[i]<pivot); do --j; while (arr[j]>pivot); if (j<i) break; cimg::swap(arr[i],arr[j]); } arr[l+1] = arr[j]; arr[j] = pivot; if (j>=k) ir = j - 1; if (j<=k) l = i; } } return 0; } //! Return the median pixel value. /** **/ T median() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "median(): Empty instance.", cimg_instance); const unsigned int s = size(); const T res = kth_smallest(s>>1); return (s%2)?res:((res+kth_smallest((s>>1)-1))/2); } //! Return the sum of all the pixel values. /** **/ Tdouble sum() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "sum(): Empty instance.", cimg_instance); Tdouble res = 0; cimg_for(*this,ptrs,T) res+=(Tdouble)*ptrs; return res; } //! Return the average pixel value. /** **/ Tdouble mean() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "mean(): Empty instance.", cimg_instance); Tdouble res = 0; cimg_for(*this,ptrs,T) res+=(Tdouble)*ptrs; return res/size(); } //! Return the variance of the pixel values. /** \param variance_method Method used to estimate the variance. Can be: - \c 0: Second moment, computed as \f$1/N \sum\limits_{k=1}^{N} (x_k - \bar x)^2 = 1/N \left( \sum\limits_{k=1}^N x_k^2 - \left( \sum\limits_{k=1}^N x_k \right)^2 / N \right)\f$ with \f$ \bar x = 1/N \sum\limits_{k=1}^N x_k \f$. - \c 1: Best unbiased estimator, computed as \f$\frac{1}{N-1} \sum\limits_{k=1}^{N} (x_k - \bar x)^2 \f$. - \c 2: Least median of squares. - \c 3: Least trimmed of squares. **/ Tdouble variance(const unsigned int variance_method=1) const { Tdouble foo; return variance_mean(variance_method,foo); } //! Return the variance as well as the average of the pixel values. /** \param variance_method Method used to estimate the variance (see variance(const unsigned int) const). \param[out] mean Average pixel value. **/ template<typename t> Tdouble variance_mean(const unsigned int variance_method, t& mean) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_mean(): Empty instance.", cimg_instance); Tdouble variance = 0, average = 0; const unsigned long siz = size(); switch (variance_method) { case 0 :{ // Least mean square (standard definition) Tdouble S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const Tdouble val = (Tdouble)*ptrs; S+=val; S2+=val*val; } variance = (S2 - S*S/siz)/siz; average = S; } break; case 1 : { // Least mean square (robust definition) Tdouble S = 0, S2 = 0; cimg_for(*this,ptrs,T) { const Tdouble val = (Tdouble)*ptrs; S+=val; S2+=val*val; } variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; average = S; } break; case 2 : { // Least Median of Squares (MAD) CImg<Tfloat> buf(*this); buf.sort(); const unsigned long siz2 = siz>>1; const Tdouble med_i = (double)buf[siz2]; cimg_for(buf,ptrs,Tfloat) { const Tdouble val = (Tdouble)*ptrs; *ptrs = (Tfloat)cimg::abs(val - med_i); average+=val; } buf.sort(); const Tdouble sig = (Tdouble)(1.4828*buf[siz2]); variance = sig*sig; } break; default : { // Least trimmed of Squares CImg<Tfloat> buf(*this); const unsigned long siz2 = siz>>1; cimg_for(buf,ptrs,Tfloat) { const Tdouble val = (Tdouble)*ptrs; (*ptrs)=(Tfloat)((*ptrs)*val); average+=val; } buf.sort(); Tdouble a = 0; const Tfloat *ptrs = buf._data; for (unsigned long j = 0; j<siz2; ++j) a+=(Tdouble)*(ptrs++); const Tdouble sig = (Tdouble)(2.6477*std::sqrt(a/siz2)); variance = sig*sig; } } mean = (t)(average/siz); return variance>0?variance:0; } //! Return estimated variance of the noise. /** \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \note Because of structures such as edges in images it is recommanded to use a robust variance estimation. The variance of the noise is estimated by computing the variance of the Laplacian \f$(\Delta I)^2 \f$ scaled by a factor \f$c\f$ insuring \f$ c E[(\Delta I)^2]= \sigma^2\f$ where \f$\sigma\f$ is the noise variance. **/ Tdouble variance_noise(const unsigned int variance_method=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "variance_noise(): Empty instance.", cimg_instance); const unsigned long siz = size(); if (!siz || !_data) return 0; if (variance_method>1) { // Compute a scaled version of the Laplacian. CImg<Tdouble> tmp(*this); if (_depth==1) { const Tdouble cste = 1.0/std::sqrt(20.0); // Depends on how the Laplacian is computed. CImg_3x3(I,T); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) { tmp(x,y,c) = cste*((Tdouble)Inc + (Tdouble)Ipc + (Tdouble)Icn + (Tdouble)Icp - 4*(Tdouble)Icc); } } else { const Tdouble cste = 1.0/std::sqrt(42.0); // Depends on how the Laplacian is computed. CImg_3x3x3(I,T); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,T) { tmp(x,y,z,c) = cste*( (Tdouble)Incc + (Tdouble)Ipcc + (Tdouble)Icnc + (Tdouble)Icpc + (Tdouble)Iccn + (Tdouble)Iccp - 6*(Tdouble)Iccc); } } return tmp.variance(variance_method); } // Version that doesn't need intermediate images. Tdouble variance = 0, S = 0, S2 = 0; if (_depth==1) { const Tdouble cste = 1.0/std::sqrt(20.0); CImg_3x3(I,T); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) { const Tdouble val = cste*((Tdouble)Inc + (Tdouble)Ipc + (Tdouble)Icn + (Tdouble)Icp - 4*(Tdouble)Icc); S+=val; S2+=val*val; } } else { const Tdouble cste = 1.0/std::sqrt(42.0); CImg_3x3x3(I,T); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,T) { const Tdouble val = cste * ((Tdouble)Incc + (Tdouble)Ipcc + (Tdouble)Icnc + (Tdouble)Icpc + (Tdouble)Iccn + (Tdouble)Iccp - 6*(Tdouble)Iccc); S+=val; S2+=val*val; } } if (variance_method) variance = siz>1?(S2 - S*S/siz)/(siz - 1):0; else variance = (S2 - S*S/siz)/siz; return variance>0?variance:0; } //! Compute the MSE (Mean-Squared Error) between two images. /** \param img Image used as the second argument of the MSE operator. **/ template<typename t> Tdouble MSE(const CImg<t>& img) const { if (img.size()!=size()) throw CImgArgumentException(_cimg_instance "MSE(): Instance and specified image (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); Tdouble vMSE = 0; const t* ptr2 = img._data; cimg_for(*this,ptr1,T) { const Tdouble diff = (Tdouble)*ptr1 - (Tdouble)*(ptr2++); vMSE+=diff*diff; } const unsigned long siz = img.size(); if (siz) vMSE/=siz; return vMSE; } //! Compute the PSNR (Peak Signal-to-Noise Ratio) between two images. /** \param img Image used as the second argument of the PSNR operator. \param max_value Maximum theoretical value of the signal. **/ template<typename t> Tdouble PSNR(const CImg<t>& img, const Tdouble max_value=255) const { const Tdouble vMSE = (Tdouble)std::sqrt(MSE(img)); return (vMSE!=0)?(Tdouble)(20*std::log10(max_value/vMSE)):(Tdouble)(cimg::type<Tdouble>::max()); } //! Evaluate math formula. /** \param expression Math formula, as a C-string. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \note Set \c expression to \c 0 to keep evaluating the last specified \c expression. **/ double eval(const char *const expression, const double x=0, const double y=0, const double z=0, const double c=0) const { static _cimg_math_parser *mp = 0; if (expression) { delete mp; mp = 0; mp = new _cimg_math_parser(*this,expression,"eval"); } return mp?mp->eval(x,y,z,c):0; } //! Compute statistics vector from the pixel values. /** \param variance_method Method used to compute the variance (see variance(const unsigned int) const). \return Statistics vector as <tt>[min; max; mean; variance; xmin; ymin; zmin; cmin; xmax; ymax; zmax; cmax]</tt>. **/ CImg<Tdouble> get_stats(const unsigned int variance_method=1) const { if (is_empty()) return CImg<doubleT>(); const unsigned long siz = size(); const T *const odata = _data; const T *pm = odata, *pM = odata; Tdouble S = 0, S2 = 0; T m = *pm, M = m; cimg_for(*this,ptrs,T) { const T val = *ptrs; const Tdouble _val = (Tdouble)val; if (val<m) { m = val; pm = ptrs; } if (val>M) { M = val; pM = ptrs; } S+=_val; S2+=_val*_val; } const Tdouble mean_value = S/siz, _variance_value = variance_method==0?(S2 - S*S/siz)/siz: (variance_method==1?(siz>1?(S2 - S*S/siz)/(siz - 1):0): variance(variance_method)), variance_value = _variance_value>0?_variance_value:0; int xm = 0, ym = 0, zm = 0, cm = 0, xM = 0, yM = 0, zM = 0, cM = 0; contains(*pm,xm,ym,zm,cm); contains(*pM,xM,yM,zM,cM); return CImg<Tdouble>(1,12).fill((Tdouble)m,(Tdouble)M,mean_value,variance_value, (Tdouble)xm,(Tdouble)ym,(Tdouble)zm,(Tdouble)cm, (Tdouble)xM,(Tdouble)yM,(Tdouble)zM,(Tdouble)cM); } //! Compute statistics vector from the pixel values \inplace. CImg<T>& stats(const unsigned int variance_method=1) { return get_stats(variance_method).move_to(*this); } //@} //------------------------------------- // //! \name Vector / Matrix Operations //@{ //------------------------------------- //! Compute norm of the image, viewed as a matrix. /** \param magnitude_type Norm type. Can be: - \c -1: Linf-norm - \c 0: L2-norm - \c 1: L1-norm **/ Tdouble magnitude(const int magnitude_type=2) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "magnitude(): Empty instance.", cimg_instance); Tdouble res = 0; switch (magnitude_type) { case -1 : { cimg_for(*this,ptrs,T) { const Tdouble val = (Tdouble)cimg::abs(*ptrs); if (val>res) res = val; } } break; case 1 : { cimg_for(*this,ptrs,T) res+=(Tdouble)cimg::abs(*ptrs); } break; default : { cimg_for(*this,ptrs,T) res+=(Tdouble)cimg::sqr(*ptrs); res = (Tdouble)std::sqrt(res); } } return res; } //! Compute the trace of the image, viewed as a matrix. /** **/ Tdouble trace() const { if (is_empty()) throw CImgInstanceException(_cimg_instance "trace(): Empty instance.", cimg_instance); Tdouble res = 0; cimg_forX(*this,k) res+=(Tdouble)(*this)(k,k); return res; } //! Compute the determinant of the image, viewed as a matrix. /** **/ Tdouble det() const { if (is_empty() || _width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "det(): Instance is not a square matrix.", cimg_instance); switch (_width) { case 1 : return (Tdouble)((*this)(0,0)); case 2 : return (Tdouble)((*this)(0,0))*(Tdouble)((*this)(1,1)) - (Tdouble)((*this)(0,1))*(Tdouble)((*this)(1,0)); case 3 : { const Tdouble a = (Tdouble)_data[0], d = (Tdouble)_data[1], g = (Tdouble)_data[2], b = (Tdouble)_data[3], e = (Tdouble)_data[4], h = (Tdouble)_data[5], c = (Tdouble)_data[6], f = (Tdouble)_data[7], i = (Tdouble)_data[8]; return i*a*e - a*h*f - i*b*d + b*g*f + c*d*h - c*g*e; } default : { CImg<Tfloat> lu(*this); CImg<uintT> indx; bool d; lu._LU(indx,d); Tdouble res = d?(Tdouble)1:(Tdouble)-1; cimg_forX(lu,i) res*=lu(i,i); return res; } } return 0; } //! Compute the dot product between instance and argument, viewed as matrices. /** \param img Image used as a second argument of the dot product. **/ template<typename t> Tdouble dot(const CImg<t>& img) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "dot(): Empty instance.", cimg_instance); if (!img) throw CImgArgumentException(_cimg_instance "dot(): Empty specified image.", cimg_instance); const unsigned int nb = cimg::min(size(),img.size()); Tdouble res = 0; for (unsigned int off = 0; off<nb; ++off) res+=(Tdouble)_data[off]*(Tdouble)img[off]; return res; } //! Get vector-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_vector_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { _cimg_static CImg<T> res; if (res._height!=_spectrum) res.assign(1,_spectrum); const unsigned long whd = (unsigned long)_width*_height*_depth; const T *ptrs = data(x,y,z); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get (square) matrix-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \note - The spectrum() of the image must be a square. **/ CImg<T> get_matrix_at(const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) const { const int n = (int)std::sqrt((double)_spectrum); const T *ptrs = data(x,y,z,0); const unsigned long whd = (unsigned long)_width*_height*_depth; CImg<T> res(n,n); T *ptrd = res._data; cimg_forC(*this,c) { *(ptrd++) = *ptrs; ptrs+=whd; } return res; } //! Get tensor-valued pixel located at specified position. /** \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ CImg<T> get_tensor_at(const unsigned int x, const unsigned int y=0, const unsigned int z=0) const { const T *ptrs = data(x,y,z,0); const unsigned long whd = (unsigned long)_width*_height*_depth; if (_spectrum==6) return tensor(*ptrs,*(ptrs+whd),*(ptrs+2*whd),*(ptrs+3*whd),*(ptrs+4*whd),*(ptrs+5*whd)); if (_spectrum==3) return tensor(*ptrs,*(ptrs+whd),*(ptrs+2*whd)); return tensor(*ptrs); } //! Set vector-valued pixel at specified position. /** \param vec Vector to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_vector_at(const CImg<t>& vec, const unsigned int x, const unsigned int y=0, const unsigned int z=0) { if (x<_width && y<_height && z<_depth) { const t *ptrs = vec._data; const unsigned long whd = (unsigned long)_width*_height*_depth; T *ptrd = data(x,y,z); for (unsigned int k = cimg::min((unsigned int)vec.size(),_spectrum); k; --k) { *ptrd = (T)*(ptrs++); ptrd+=whd; } } return *this; } //! Set (square) matrix-valued pixel at specified position. /** \param mat Matrix to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_matrix_at(const CImg<t>& mat, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { return set_vector_at(mat,x,y,z); } //! Set tensor-valued pixel at specified position. /** \param ten Tensor to put on the instance image. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. **/ template<typename t> CImg<T>& set_tensor_at(const CImg<t>& ten, const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { T *ptrd = data(x,y,z,0); const unsigned long siz = (unsigned long)_width*_height*_depth; if (ten._height==2) { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[3]; } else { *ptrd = (T)ten[0]; ptrd+=siz; *ptrd = (T)ten[1]; ptrd+=siz; *ptrd = (T)ten[2]; ptrd+=siz; *ptrd = (T)ten[4]; ptrd+=siz; *ptrd = (T)ten[5]; ptrd+=siz; *ptrd = (T)ten[8]; } return *this; } //! Unroll pixel values along axis \c y. /** \note Equivalent to \code unroll('y'); \endcode. **/ CImg<T>& vector() { return unroll('y'); } //! Unroll pixel values along axis \c y \newinstance. CImg<T> get_vector() const { return get_unroll('y'); } //! Resize image to become a scalar square matrix. /** **/ CImg<T>& matrix() { const unsigned long siz = size(); switch (siz) { case 1 : break; case 4 : _width = _height = 2; break; case 9 : _width = _height = 3; break; case 16 : _width = _height = 4; break; case 25 : _width = _height = 5; break; case 36 : _width = _height = 6; break; case 49 : _width = _height = 7; break; case 64 : _width = _height = 8; break; case 81 : _width = _height = 9; break; case 100 : _width = _height = 10; break; default : { unsigned long i = 11, i2 = i*i; while (i2<siz) { i2+=2*i + 1; ++i; } if (i2==siz) _width = _height = i; else throw CImgInstanceException(_cimg_instance "matrix(): Invalid instance size %u (should be a square integer).", cimg_instance, siz); } } return *this; } //! Resize image to become a scalar square matrix \newinstance. CImg<T> get_matrix() const { return (+*this).matrix(); } //! Resize image to become a symmetric tensor. /** **/ CImg<T>& tensor() { return get_tensor().move_to(*this); } //! Resize image to become a symmetric tensor \newinstance. CImg<T> get_tensor() const { CImg<T> res; const unsigned long siz = size(); switch (siz) { case 1 : break; case 3 : res.assign(2,2); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(1,1) = (*this)(2); break; case 6 : res.assign(3,3); res(0,0) = (*this)(0); res(1,0) = res(0,1) = (*this)(1); res(2,0) = res(0,2) = (*this)(2); res(1,1) = (*this)(3); res(2,1) = res(1,2) = (*this)(4); res(2,2) = (*this)(5); break; default : throw CImgInstanceException(_cimg_instance "tensor(): Invalid instance size (does not define a 1x1, 2x2 or 3x3 tensor).", cimg_instance); } return res; } //! Resize image to become a diagonal matrix. /** \note Transform the image as a diagonal matrix so that each of its initial value becomes a diagonal coefficient. **/ CImg<T>& diagonal() { return get_diagonal().move_to(*this); } //! Resize image to become a diagonal matrix \newinstance. CImg<T> get_diagonal() const { if (is_empty()) return *this; CImg<T> res(size(),size(),1,1,0); cimg_foroff(*this,off) res(off,off) = (*this)(off); return res; } //! Replace the image by an identity matrix. /** \note If the instance image is not square, it is resized to a square matrix using its maximum dimension as a reference. **/ CImg<T>& identity_matrix() { return identity_matrix(cimg::max(_width,_height)).move_to(*this); } //! Replace the image by an identity matrix \newinstance. CImg<T> get_identity_matrix() const { return identity_matrix(cimg::max(_width,_height)); } //! Fill image with a linear sequence of values. /** \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ CImg<T>& sequence(const T a0, const T a1) { if (is_empty()) return *this; const unsigned int siz = size() - 1; T* ptr = _data; if (siz) { const Tdouble delta = (Tdouble)a1 - (Tdouble)a0; cimg_foroff(*this,l) *(ptr++) = (T)(a0 + delta*l/siz); } else *ptr = a0; return *this; } //! Fill image with a linear sequence of values \newinstance. CImg<T> get_sequence(const T a0, const T a1) const { return (+*this).sequence(a0,a1); } //! Transpose the image, viewed as a matrix. /** \note Equivalent to \code permute_axes("yxzc"); \endcode **/ CImg<T>& transpose() { if (_width==1) { _width = _height; _height = 1; return *this; } if (_height==1) { _height = _width; _width = 1; return *this; } if (_width==_height) { cimg_forYZC(*this,y,z,c) for (int x = y; x<width(); ++x) cimg::swap((*this)(x,y,z,c),(*this)(y,x,z,c)); return *this; } return get_transpose().move_to(*this); } //! Transpose the image, viewed as a matrix \newinstance. CImg<T> get_transpose() const { return get_permute_axes("yxzc"); } //! Compute the cross product between two \c 1x3 images, viewed as 3d vectors. /** \param img Image used as the second argument of the cross product. \note The first argument of the cross product is \c *this. **/ template<typename t> CImg<T>& cross(const CImg<t>& img) { if (_width!=1 || _height<3 || img._width!=1 || img._height<3) throw CImgInstanceException(_cimg_instance "cross(): Instance and/or specified image (%u,%u,%u,%u,%p) are not 3d vectors.", cimg_instance, img._width,img._height,img._depth,img._spectrum,img._data); const T x = (*this)[0], y = (*this)[1], z = (*this)[2]; (*this)[0] = (T)(y*img[2] - z*img[1]); (*this)[1] = (T)(z*img[0] - x*img[2]); (*this)[2] = (T)(x*img[1] - y*img[0]); return *this; } //! Compute the cross product between two \c 1x3 images, viewed as 3d vectors \newinstance. template<typename t> CImg<_cimg_Tt> get_cross(const CImg<t>& img) const { return CImg<_cimg_Tt>(*this).cross(img); } //! Invert the instance image, viewed as a matrix. /** \param use_LU Choose the inverting algorithm. Can be: - \c true: LU-based matrix inversion. - \c false: SVD-based matrix inversion. **/ CImg<T>& invert(const bool use_LU=true) { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "invert(): Instance is not a square matrix.", cimg_instance); #ifdef cimg_use_lapack int INFO = (int)use_LU, N = _width, LWORK = 4*N, *const IPIV = new int[N]; Tfloat *const lapA = new Tfloat[N*N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N+l] = (Tfloat)((*this)(k,l)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetrf_() returned error code %d.", cimg_instance, INFO); else { cimg::getri(N,lapA,IPIV,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "invert(): LAPACK function dgetri_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)(lapA[k*N+l]); else fill(0); delete[] IPIV; delete[] lapA; delete[] WORK; #else const double dete = _width>3?-1.0:det(); if (dete!=0.0 && _width==2) { const double a = _data[0], c = _data[1], b = _data[2], d = _data[3]; _data[0] = (T)(d/dete); _data[1] = (T)(-c/dete); _data[2] = (T)(-b/dete); _data[3] = (T)(a/dete); } else if (dete!=0.0 && _width==3) { const double a = _data[0], d = _data[1], g = _data[2], b = _data[3], e = _data[4], h = _data[5], c = _data[6], f = _data[7], i = _data[8]; _data[0] = (T)((i*e-f*h)/dete), _data[1] = (T)((g*f-i*d)/dete), _data[2] = (T)((d*h-g*e)/dete); _data[3] = (T)((h*c-i*b)/dete), _data[4] = (T)((i*a-c*g)/dete), _data[5] = (T)((g*b-a*h)/dete); _data[6] = (T)((b*f-e*c)/dete), _data[7] = (T)((d*c-a*f)/dete), _data[8] = (T)((a*e-d*b)/dete); } else { if (use_LU) { // LU-based inverse computation CImg<Tfloat> A(*this), indx, col(1,_width); bool d; A._LU(indx,d); cimg_forX(*this,j) { col.fill(0); col(j) = 1; col._solve(A,indx); cimg_forX(*this,i) (*this)(j,i) = (T)col(i); } } else { // SVD-based inverse computation CImg<Tfloat> U(_width,_width), S(1,_width), V(_width,_width); SVD(U,S,V,false); U.transpose(); cimg_forY(S,k) if (S[k]!=0) S[k]=1/S[k]; S.diagonal(); *this = V*S*U; } } #endif return *this; } //! Invert the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_invert(const bool use_LU=true) const { return CImg<Tfloat>(*this,false).invert(use_LU); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix. /** **/ CImg<T>& pseudoinvert() { return get_pseudoinvert().move_to(*this); } //! Compute the Moore-Penrose pseudo-inverse of the instance image, viewed as a matrix \newinstance. CImg<Tfloat> get_pseudoinvert() const { CImg<Tfloat> U, S, V; SVD(U,S,V); const Tfloat tolerance = (sizeof(Tfloat)<=4?5.96e-8f:1.11e-16f)*cimg::max(_width,_height)*S.max(); cimg_forX(V,x) { const Tfloat s = S(x), invs = s>tolerance?1/s:(Tfloat)0; cimg_forY(V,y) V(x,y)*=invs; } return V*U.transpose(); } //! Solve a system of linear equations. /** \param A Matrix of the linear system. \note Solve \c AX=B where \c B=*this. **/ template<typename t> CImg<T>& solve(const CImg<t>& A) { if (_width!=1 || _depth!=1 || _spectrum!=1 || _height!=A._height || A._depth!=1 || A._spectrum!=1) throw CImgArgumentException(_cimg_instance "solve(): Instance and specified matrix (%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; if (A._width==A._height) { #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = _height, LWORK = 4*N, *const IPIV = new int[N]; Ttfloat *const lapA = new Ttfloat[N*N], *const lapB = new Ttfloat[N], *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*N+l] = (Ttfloat)(A(k,l)); cimg_forY(*this,i) lapB[i] = (Ttfloat)((*this)(i)); cimg::getrf(N,lapA,IPIV,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrf_() returned error code %d.", cimg_instance, INFO); if (!INFO) { cimg::getrs(TRANS,N,lapA,IPIV,lapB,INFO); if (INFO) cimg::warn(_cimg_instance "solve(): LAPACK library function dgetrs_() returned error code %d.", cimg_instance, INFO); } if (!INFO) cimg_forY(*this,i) (*this)(i) = (T)(lapB[i]); else fill(0); delete[] IPIV; delete[] lapA; delete[] lapB; delete[] WORK; #else CImg<Ttfloat> lu(A,false); CImg<Ttfloat> indx; bool d; lu._LU(indx,d); _solve(lu,indx); #endif } else { // Least-square solution for non-square systems. #ifdef cimg_use_lapack char TRANS = 'N'; int INFO, N = A._width, M = A._height, LWORK = -1, LDA = M, LDB = M, NRHS = _width; Ttfloat WORK_QUERY; Ttfloat * const lapA = new Ttfloat[M*N], * const lapB = new Ttfloat[M*NRHS]; cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, &WORK_QUERY, LWORK, INFO); LWORK = (int) WORK_QUERY; Ttfloat *const WORK = new Ttfloat[LWORK]; cimg_forXY(A,k,l) lapA[k*M+l] = (Ttfloat)(A(k,l)); cimg_forXY(*this,k,l) lapB[k*M+l] = (Ttfloat)((*this)(k,l)); cimg::sgels(TRANS, M, N, NRHS, lapA, LDA, lapB, LDB, WORK, LWORK, INFO); if (INFO != 0) cimg::warn(_cimg_instance "solve(): LAPACK library function sgels() returned error code %d.", cimg_instance, INFO); assign(NRHS, N); if (!INFO != 0) cimg_forXY(*this,k,l) (*this)(k,l) = (T) lapB[k*M+l]; else assign(A.get_pseudoinvert()*(*this)); delete[] lapA; delete[] lapB; delete[] WORK; #else assign(A.get_pseudoinvert()*(*this)); #endif } return *this; } //! Solve a system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve(const CImg<t>& A) const { return CImg<_cimg_Ttfloat>(*this,false).solve(A); } template<typename t, typename ti> CImg<T>& _solve(const CImg<t>& A, const CImg<ti>& indx) { typedef _cimg_Ttfloat Ttfloat; const int N = size(); int ii = -1; Ttfloat sum; for (int i = 0; i<N; ++i) { const int ip = (int)indx[i]; Ttfloat sum = (*this)(ip); (*this)(ip) = (*this)(i); if (ii>=0) for (int j = ii; j<=i-1; ++j) sum-=A(j,i)*(*this)(j); else if (sum!=0) ii = i; (*this)(i) = (T)sum; } for (int i = N - 1; i>=0; --i) { sum = (*this)(i); for (int j = i + 1; j<N; ++j) sum-=A(j,i)*(*this)(j); (*this)(i) = (T)(sum/A(i,i)); } return *this; } //! Solve a tridiagonal system of linear equations. /** \param A Coefficients of the tridiagonal system. A is a tridiagonal matrix A = [ b0,c0,0,...; a1,b1,c1,0,... ; ... ; ...,0,aN,bN ], stored as a 3 columns matrix \note Solve AX=B where \c B=*this, using the Thomas algorithm. **/ template<typename t> CImg<T>& solve_tridiagonal(const CImg<t>& A) { const unsigned int siz = (int)size(); if (A._width!=3 || A._height!=siz) throw CImgArgumentException(_cimg_instance "solve_tridiagonal(): Instance and tridiagonal matrix " "(%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, A._width,A._height,A._depth,A._spectrum,A._data); typedef _cimg_Ttfloat Ttfloat; const Ttfloat epsilon = 1e-4; CImg<Ttfloat> B = A.get_column(1), V(*this,false); for (int i = 1; i<(int)siz; ++i) { const Ttfloat m = A(0,i)/(B[i-1]?B[i-1]:epsilon); B[i] -= m*A(2,i-1); V[i] -= m*V[i-1]; } (*this)[siz-1] = (T)(V[siz-1]/(B[siz-1]?B[siz-1]:epsilon)); for (int i = (int)siz - 2; i>=0; --i) (*this)[i] = (T)((V[i] - A(2,i)*(*this)[i+1])/(B[i]?B[i]:epsilon)); return *this; } //! Solve a tridiagonal system of linear equations \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_solve_tridiagonal(const CImg<t>& A) const { return CImg<_cimg_Ttfloat>(*this,false).solve_tridiagonal(A); } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvalues, sorted by columns. **/ template<typename t> const CImg<T>& eigen(CImg<t>& val, CImg<t> &vec) const { if (is_empty()) { val.assign(); vec.assign(); } else { if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); if (val.size()<(unsigned long)_width) val.assign(1,_width); if (vec.size()<(unsigned long)_width*_width) vec.assign(_width,_width); switch (_width) { case 1 : { val[0] = (t)(*this)[0]; vec[0] = (t)1; } break; case 2 : { const double a = (*this)[0], b = (*this)[1], c = (*this)[2], d = (*this)[3], e = a + d; double f = e*e - 4*(a*d - b*c); if (f<0) cimg::warn(_cimg_instance "eigen(): Complex eigenvalues found.", cimg_instance); f = std::sqrt(f); const double l1 = 0.5*(e-f), l2 = 0.5*(e+f); const double theta1 = std::atan2(l2-a,b), theta2 = std::atan2(l1-a,b); val[0] = (t)l2; val[1] = (t)l1; vec(0,0) = (t)std::cos(theta1); vec(0,1) = (t)std::sin(theta1); vec(1,0) = (t)std::cos(theta2); vec(1,1) = (t)std::sin(theta2); } break; default : throw CImgInstanceException(_cimg_instance "eigen(): Eigenvalues computation of general matrices is limited to 2x2 matrices.", cimg_instance); } } return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning is similar as in eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_eigen() const { CImgList<Tfloat> res(2); eigen(res[0],res[1]); return res; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \param[out] val Vector of the estimated eigenvalues, in decreasing order. \param[out] vec Matrix of the estimated eigenvalues, sorted by columns. **/ template<typename t> const CImg<T>& symmetric_eigen(CImg<t>& val, CImg<t>& vec) const { if (is_empty()) { val.assign(); vec.assign(); } else { #ifdef cimg_use_lapack char JOB = 'V', UPLO = 'U'; int N = _width, LWORK = 4*N, INFO; Tfloat *const lapA = new Tfloat[N*N], *const lapW = new Tfloat[N], *const WORK = new Tfloat[LWORK]; cimg_forXY(*this,k,l) lapA[k*N+l] = (Tfloat)((*this)(k,l)); cimg::syev(JOB,UPLO,N,lapA,lapW,WORK,LWORK,INFO); if (INFO) cimg::warn(_cimg_instance "symmetric_eigen(): LAPACK library function dsyev_() returned error code %d.", cimg_instance, INFO); val.assign(1,N); vec.assign(N,N); if (!INFO) { cimg_forY(val,i) val(i) = (T)lapW[N-1-i]; cimg_forXY(vec,k,l) vec(k,l) = (T)(lapA[(N-1-k)*N+l]); } else { val.fill(0); vec.fill(0); } delete[] lapA; delete[] lapW; delete[] WORK; #else if (_width!=_height || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "eigen(): Instance is not a square matrix.", cimg_instance); val.assign(1,_width); if (vec._data) vec.assign(_width,_width); if (_width<3) { eigen(val,vec); if (_width==2) { vec[1] = -vec[2]; vec[3] = vec[0]; } // Force orthogonality for 2x2 matrices. return *this; } CImg<t> V(_width,_width); SVD(vec,val,V,false); bool is_ambiguous = false; float eig = 0; cimg_forY(val,p) { // check for ambiguous cases. if (val[p]>eig) eig = (float)val[p]; t scal = 0; cimg_forY(vec,y) scal+=vec(p,y)*V(p,y); if (cimg::abs(scal)<0.9f) is_ambiguous = true; if (scal<0) val[p] = -val[p]; } if (is_ambiguous) { ++(eig*=2); SVD(vec,val,V,false,40,eig); val-=eig; } CImg<intT> permutations; // sort eigenvalues in decreasing order CImg<t> tmp(_width); val.sort(permutations,false); cimg_forY(vec,k) { cimg_forY(permutations,y) tmp(y) = vec(permutations(y),k); std::memcpy(vec.data(0,k),tmp._data,sizeof(t)*_width); } #endif } return *this; } //! Compute eigenvalues and eigenvectors of the instance image, viewed as a symmetric matrix. /** \return A list of two images <tt>[val; vec]</tt>, whose meaning are similar as in symmetric_eigen(CImg<t>&,CImg<t>&) const. **/ CImgList<Tfloat> get_symmetric_eigen() const { CImgList<Tfloat> res(2); symmetric_eigen(res[0],res[1]); return res; } //! Sort pixel values and get sorting permutations. /** \param[out] permutations Permutation map used for the sorting. \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. **/ template<typename t> CImg<T>& sort(CImg<t>& permutations, const bool is_increasing=true) { permutations.assign(_width,_height,_depth,_spectrum); if (is_empty()) return *this; cimg_foroff(permutations,off) permutations[off] = (t)off; return _quicksort(0,size()-1,permutations,is_increasing,true); } //! Sort pixel values and get sorting permutations \newinstance. template<typename t> CImg<T> get_sort(CImg<t>& permutations, const bool is_increasing=true) const { return (+*this).sort(permutations,is_increasing); } //! Sort pixel values. /** \param is_increasing Tells if pixel values are sorted in an increasing (\c true) or decreasing (\c false) way. \param axis Tells if the value sorting must be done along a specific axis. Can be: - \c 0: All pixel values are sorted, independently on their initial position. - \c 'x': Image columns are sorted, according to the first value in each column. - \c 'y': Image rows are sorted, according to the first value in each row. - \c 'z': Image slices are sorted, according to the first value in each slice. - \c 'c': Image channels are sorted, according to the first value in each channel. **/ CImg<T>& sort(const bool is_increasing=true, const char axis=0) { if (is_empty()) return *this; CImg<uintT> perm; switch (cimg::uncase(axis)) { case 0 : _quicksort(0,size()-1,perm,is_increasing,false); break; case 'x' : { perm.assign(_width); get_crop(0,0,0,0,_width-1,0,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(perm[x],y,z,c); } break; case 'y' : { perm.assign(_height); get_crop(0,0,0,0,0,_height-1,0,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,perm[y],z,c); } break; case 'z' : { perm.assign(_depth); get_crop(0,0,0,0,0,0,_depth-1,0).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,perm[z],c); } break; case 'c' : { perm.assign(_spectrum); get_crop(0,0,0,0,0,0,0,_spectrum-1).sort(perm,is_increasing); CImg<T> img(*this,false); cimg_forXYZC(*this,x,y,z,c) (*this)(x,y,z,c) = img(x,y,z,perm[c]); } break; default : throw CImgArgumentException(_cimg_instance "sort(): Invalid specified axis '%c' " "(should be { x | y | z | c }).", cimg_instance,axis); } return *this; } //! Sort pixel values \newinstance. CImg<T> get_sort(const bool is_increasing=true, const char axis=0) const { return (+*this).sort(is_increasing,axis); } template<typename t> CImg<T>& _quicksort(const int indm, const int indM, CImg<t>& permutations, const bool is_increasing, const bool is_permutations) { if (indm<indM) { const int mid = (indm + indM)/2; if (is_increasing) { if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]>(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]>(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } else { if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } if ((*this)[mid]<(*this)[indM]) { cimg::swap((*this)[indM],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indM],permutations[mid]); } if ((*this)[indm]<(*this)[mid]) { cimg::swap((*this)[indm],(*this)[mid]); if (is_permutations) cimg::swap(permutations[indm],permutations[mid]); } } if (indM - indm>=3) { const T pivot = (*this)[mid]; int i = indm, j = indM; if (is_increasing) { do { while ((*this)[i]<pivot) ++i; while ((*this)[j]>pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } else { do { while ((*this)[i]>pivot) ++i; while ((*this)[j]<pivot) --j; if (i<=j) { if (is_permutations) cimg::swap(permutations[i],permutations[j]); cimg::swap((*this)[i++],(*this)[j--]); } } while (i<=j); } if (indm<j) _quicksort(indm,j,permutations,is_increasing,is_permutations); if (i<indM) _quicksort(i,indM,permutations,is_increasing,is_permutations); } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** Compute the SVD decomposition \c *this=U*S*V' where \c U and \c V are orthogonal matrices and \c S is a diagonal matrix. \c V' denotes the matrix transpose of \c V. \param[out] U First matrix of the SVD product. \param[out] S Coefficients of the second (diagonal) matrix of the SVD product. These coefficients are stored as a vector. \param[out] V Third matrix of the SVD product. \param sorting Tells if the diagonal coefficients are sorted (in decreasing order). \param max_iteration Maximum number of iterations considered for the algorithm convergence. \param lambda Epsilon used for the algorithm convergence. \note The instance matrix can be computed from \c U,\c S and \c V by \code const CImg<> A; // Input matrix (assumed to contain some values). CImg<> U,S,V; A.SVD(U,S,V) \endcode **/ template<typename t> const CImg<T>& SVD(CImg<t>& U, CImg<t>& S, CImg<t>& V, const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { if (is_empty()) { U.assign(); S.assign(); V.assign(); } else { U = *this; if (lambda!=0) { const unsigned int delta = cimg::min(U._width,U._height); for (unsigned int i = 0; i<delta; ++i) U(i,i) = (t)(U(i,i) + lambda); } if (S.size()<_width) S.assign(1,_width); if (V._width<_width || V._height<_height) V.assign(_width,_width); CImg<t> rv1(_width); t anorm = 0, c, f, g = 0, h, s, scale = 0; int l = 0, nm = 0; cimg_forX(U,i) { l = i+1; rv1[i] = scale*g; g = s = scale = 0; if (i<height()) { for (int k = i; k<height(); ++k) scale+= cimg::abs(U(i,k)); if (scale) { for (int k = i; k<height(); ++k) { U(i,k)/=scale; s+= U(i,k)*U(i,k); } f = U(i,i); g = (t)((f>=0?-1:1)*std::sqrt(s)); h=f*g-s; U(i,i) = f-g; for (int j = l; j<width(); ++j) { s = 0; for (int k=i; k<height(); ++k) s+= U(i,k)*U(j,k); f = s/h; for (int k = i; k<height(); ++k) U(j,k)+= f*U(i,k); } for (int k = i; k<height(); ++k) U(i,k)*= scale; } } S[i]=scale*g; g = s = scale = 0; if (i<height() && i!=width()-1) { for (int k = l; k<width(); ++k) scale+=cimg::abs(U(k,i)); if (scale) { for (int k = l; k<width(); ++k) { U(k,i)/= scale; s+= U(k,i)*U(k,i); } f = U(l,i); g = (t)((f>=0?-1:1)*std::sqrt(s)); h = f*g-s; U(l,i) = f-g; for (int k = l; k<width(); ++k) rv1[k]=U(k,i)/h; for (int j = l; j<height(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+= U(k,j)*U(k,i); for (int k = l; k<width(); ++k) U(k,j)+= s*rv1[k]; } for (int k = l; k<width(); ++k) U(k,i)*= scale; } } anorm = (t)cimg::max((float)anorm,(float)(cimg::abs(S[i])+cimg::abs(rv1[i]))); } for (int i = width()-1; i>=0; --i) { if (i<width()-1) { if (g) { for (int j = l; j<width(); ++j) V(i,j) =(U(j,i)/U(l,i))/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<width(); ++k) s+= U(k,i)*V(j,k); for (int k = l; k<width(); ++k) V(j,k)+= s*V(i,k); } } for (int j = l; j<width(); ++j) V(j,i) = V(i,j) = (t)0.0; } V(i,i) = (t)1.0; g = rv1[i]; l = i; } for (int i = cimg::min(width(),height())-1; i>=0; --i) { l = i+1; g = S[i]; for (int j = l; j<width(); ++j) U(j,i) = 0; if (g) { g = 1/g; for (int j = l; j<width(); ++j) { s = 0; for (int k = l; k<height(); ++k) s+= U(i,k)*U(j,k); f = (s/U(i,i))*g; for (int k = i; k<height(); ++k) U(j,k)+= f*U(i,k); } for (int j = i; j<height(); ++j) U(i,j)*= g; } else for (int j = i; j<height(); ++j) U(i,j) = 0; ++U(i,i); } for (int k = width()-1; k>=0; --k) { for (unsigned int its = 0; its<max_iteration; ++its) { bool flag = true; for (l = k; l>=1; --l) { nm = l-1; if ((cimg::abs(rv1[l])+anorm)==anorm) { flag = false; break; } if ((cimg::abs(S[nm])+anorm)==anorm) break; } if (flag) { c = 0; s = 1; for (int i = l; i<=k; ++i) { f = s*rv1[i]; rv1[i] = c*rv1[i]; if ((cimg::abs(f)+anorm)==anorm) break; g = S[i]; h = (t)cimg::_pythagore(f,g); S[i] = h; h = 1/h; c = g*h; s = -f*h; cimg_forY(U,j) { const t y = U(nm,j), z = U(i,j); U(nm,j) = y*c + z*s; U(i,j) = z*c - y*s; } } } const t z = S[k]; if (l==k) { if (z<0) { S[k] = -z; cimg_forX(U,j) V(k,j) = -V(k,j); } break; } nm = k-1; t x = S[l], y = S[nm]; g = rv1[nm]; h = rv1[k]; f = ((y-z)*(y+z)+(g-h)*(g+h))/(2*h*y); g = (t)cimg::_pythagore(f,1.0); f = ((x-z)*(x+z)+h*((y/(f+ (f>=0?g:-g)))-h))/x; c = s = 1; for (int j = l; j<=nm; ++j) { const int i = j+1; g = rv1[i]; h = s*g; g = c*g; t y = S[i]; t z = (t)cimg::_pythagore(f,h); rv1[j] = z; c = f/z; s = h/z; f = x*c+g*s; g = g*c-x*s; h = y*s; y*=c; cimg_forX(U,jj) { const t x = V(j,jj), z = V(i,jj); V(j,jj) = x*c + z*s; V(i,jj) = z*c - x*s; } z = (t)cimg::_pythagore(f,h); S[j] = z; if (z) { z = 1/z; c = f*z; s = h*z; } f = c*g+s*y; x = c*y-s*g; cimg_forY(U,jj) { const t y = U(j,jj); z = U(i,jj); U(j,jj) = y*c + z*s; U(i,jj) = z*c - y*s; } } rv1[l] = 0; rv1[k]=f; S[k]=x; } } if (sorting) { CImg<intT> permutations; CImg<t> tmp(_width); S.sort(permutations,false); cimg_forY(U,k) { cimg_forY(permutations,y) tmp(y) = U(permutations(y),k); std::memcpy(U.data(0,k),tmp._data,sizeof(t)*_width); } cimg_forY(V,k) { cimg_forY(permutations,y) tmp(y) = V(permutations(y),k); std::memcpy(V.data(0,k),tmp._data,sizeof(t)*_width); } } } return *this; } //! Compute the SVD of the instance image, viewed as a general matrix. /** \return A list of three images <tt>[U; S; V]</tt>, whose meaning is similar as in SVD(CImg<t>&,CImg<t>&,CImg<t>&,bool,unsigned int,float) const. **/ CImgList<Tfloat> get_SVD(const bool sorting=true, const unsigned int max_iteration=40, const float lambda=0) const { CImgList<Tfloat> res(3); SVD(res[0],res[1],res[2],sorting,max_iteration,lambda); return res; } // [internal] Compute the LU decomposition of a permuted matrix. template<typename t> CImg<T>& _LU(CImg<t>& indx, bool& d) { const int N = width(); int imax = 0; CImg<Tfloat> vv(N); indx.assign(N); d = true; cimg_forX(*this,i) { Tfloat vmax = 0; cimg_forX(*this,j) { const Tfloat tmp = cimg::abs((*this)(j,i)); if (tmp>vmax) vmax = tmp; } if (vmax==0) { indx.fill(0); return fill(0); } vv[i] = 1/vmax; } cimg_forX(*this,j) { for (int i = 0; i<j; ++i) { Tfloat sum=(*this)(j,i); for (int k = 0; k<i; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; } Tfloat vmax = 0; for (int i = j; i<width(); ++i) { Tfloat sum=(*this)(j,i); for (int k = 0; k<j; ++k) sum-=(*this)(k,i)*(*this)(j,k); (*this)(j,i) = (T)sum; const Tfloat tmp = vv[i]*cimg::abs(sum); if (tmp>=vmax) { vmax=tmp; imax=i; } } if (j!=imax) { cimg_forX(*this,k) cimg::swap((*this)(k,imax),(*this)(k,j)); d =!d; vv[imax] = vv[j]; } indx[j] = (t)imax; if ((*this)(j,j)==0) (*this)(j,j) = (T)1e-20; if (j<N) { const Tfloat tmp = 1/(Tfloat)(*this)(j,j); for (int i=j+1; i<N; ++i) (*this)(j,i) = (T)((*this)(j,i)*tmp); } } return *this; } //! Compute minimal path in a graph, using the Dijkstra algorithm. /** \param distance An object having operator()(unsigned int i, unsigned int j) which returns distance between two nodes (i,j). \param nb_nodes Number of graph nodes. \param starting_node Indice of the starting node. \param ending_node Indice of the ending node (set to ~0U to ignore ending node). \param previous_node Array that gives the previous node indice in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. **/ template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { if (starting_node>=nb_nodes) throw CImgArgumentException("CImg<%s>::dijkstra(): Specified indice of starting node %u is higher than number of nodes %u.", pixel_type(),starting_node,nb_nodes); CImg<T> dist(1,nb_nodes,1,1,cimg::type<T>::max()); dist(starting_node) = 0; previous_node.assign(1,nb_nodes,1,1,(t)-1); previous_node(starting_node) = (t)starting_node; CImg<uintT> Q(nb_nodes); cimg_forX(Q,u) Q(u) = u; cimg::swap(Q(starting_node),Q(0)); unsigned int sizeQ = nb_nodes; while (sizeQ) { // Update neighbors from minimal vertex const unsigned int umin = Q(0); if (umin==ending_node) sizeQ = 0; else { const T dmin = dist(umin); const T infty = cimg::type<T>::max(); for (unsigned int q = 1; q<sizeQ; ++q) { const unsigned int v = Q(q); const T d = (T)distance(v,umin); if (d<infty) { const T alt = dmin + d; if (alt<dist(v)) { dist(v) = alt; previous_node(v) = (t)umin; const T distpos = dist(Q(q)); for (unsigned int pos = q, par = 0; pos && distpos<dist(Q(par=(pos+1)/2-1)); pos=par) cimg::swap(Q(pos),Q(par)); } } } // Remove minimal vertex from queue Q(0) = Q(--sizeQ); const T distpos = dist(Q(0)); for (unsigned int pos = 0, left = 0, right = 0; ((right=2*(pos+1),(left=right-1))<sizeQ && distpos>dist(Q(left))) || (right<sizeQ && distpos>dist(Q(right)));) { if (right<sizeQ) { if (dist(Q(left))<dist(Q(right))) { cimg::swap(Q(pos),Q(left)); pos = left; } else { cimg::swap(Q(pos),Q(right)); pos = right; } } else { cimg::swap(Q(pos),Q(left)); pos = left; } } } } return dist; } //! Return minimal path in a graph, using the Dijkstra algorithm. template<typename tf, typename t> static CImg<T> dijkstra(const tf& distance, const unsigned int nb_nodes, const unsigned int starting_node, const unsigned int ending_node=~0U) { CImg<uintT> foo; return dijkstra(distance,nb_nodes,starting_node,ending_node,foo); } //! Return minimal path in a graph, using the Dijkstra algorithm. /** \param starting_node Indice of the starting node. \param ending_node Indice of the ending node. \param previous_node Array that gives the previous node indice in the path to the starting node (optional parameter). \return Array of distances of each node to the starting node. \note image instance corresponds to the adjacency matrix of the graph. **/ template<typename t> CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) { return get_dijkstra(starting_node,ending_node,previous_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. template<typename t> CImg<T> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node, CImg<t>& previous_node) const { if (_width!=_height || _depth!=1 || _spectrum!=1) throw CImgInstanceException(_cimg_instance "dijkstra(): Instance is not a graph adjacency matrix.", cimg_instance); return dijkstra(*this,_width,starting_node,ending_node,previous_node); } //! Return minimal path in a graph, using the Dijkstra algorithm. CImg<T>& dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) { return get_dijkstra(starting_node,ending_node).move_to(*this); } //! Return minimal path in a graph, using the Dijkstra algorithm \newinstance. CImg<Tfloat> get_dijkstra(const unsigned int starting_node, const unsigned int ending_node=~0U) const { CImg<uintT> foo; return get_dijkstra(starting_node,ending_node,foo); } //! Return an image containing the ascii codes of the specified string. /** \param str input C-string to encode as an image. \param is_last_zero Tells if the ending \c '0' character appear in the resulting image. **/ static CImg<T> string(const char *const str, const bool is_last_zero=true) { if (!str) return CImg<T>(); return CImg<T>(str,std::strlen(str)+(is_last_zero?1:0)); } //! Return a \c 1x1 image containing specified value. /** \param a0 First vector value. **/ static CImg<T> vector(const T& a0) { _cimg_static CImg<T> r(1,1); r[0] = a0; return r; } //! Return a \c 1x2 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. **/ static CImg<T> vector(const T& a0, const T& a1) { _cimg_static CImg<T> r(1,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; return r; } //! Return a \c 1x3 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2) { _cimg_static CImg<T> r(1,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; return r; } //! Return a \c 1x4 image containing specified values. /** \param a0 First vector value. \param a1 Second vector value. \param a2 Third vector value. \param a3 Fourth vector value. **/ static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3) { _cimg_static CImg<T> r(1,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a \c 1x5 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { _cimg_static CImg<T> r(1,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; return r; } //! Return a \c 1x6 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { _cimg_static CImg<T> r(1,6); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; return r; } //! Return a \c 1x7 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6) { _cimg_static CImg<T> r(1,7); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; return r; } //! Return a \c 1x8 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7) { _cimg_static CImg<T> r(1,8); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; return r; } //! Return a \c 1x9 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { _cimg_static CImg<T> r(1,9); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a \c 1x10 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9) { _cimg_static CImg<T> r(1,10); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; return r; } //! Return a \c 1x11 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10) { _cimg_static CImg<T> r(1,11); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; return r; } //! Return a \c 1x12 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11) { _cimg_static CImg<T> r(1,12); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; return r; } //! Return a \c 1x13 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12) { _cimg_static CImg<T> r(1,13); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; return r; } //! Return a \c 1x14 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13) { _cimg_static CImg<T> r(1,14); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; return r; } //! Return a \c 1x15 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14) { _cimg_static CImg<T> r(1,15); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; return r; } //! Return a \c 1x16 image containing specified values. static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { _cimg_static CImg<T> r(1,16); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 1x1 matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> matrix(const T& a0) { return vector(a0); } //! Return a 2x2 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3) { _cimg_static CImg<T> r(2,2); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; return r; } //! Return a 3x3 matrix containing specified coefficients. /** \param a0 First matrix value. \param a1 Second matrix value. \param a2 Third matrix value. \param a3 Fourth matrix value. \param a4 Fifth matrix value. \param a5 Sixth matrix value. \param a6 Seventh matrix value. \param a7 Eighth matrix value. \param a8 Nineth matrix value. **/ static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8) { _cimg_static CImg<T> r(3,3); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; return r; } //! Return a 4x4 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15) { _cimg_static CImg<T> r(4,4); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; return r; } //! Return a 5x5 matrix containing specified coefficients. static CImg<T> matrix(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5, const T& a6, const T& a7, const T& a8, const T& a9, const T& a10, const T& a11, const T& a12, const T& a13, const T& a14, const T& a15, const T& a16, const T& a17, const T& a18, const T& a19, const T& a20, const T& a21, const T& a22, const T& a23, const T& a24) { _cimg_static CImg<T> r(5,5); T *ptr = r._data; *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6; *(ptr++) = a7; *(ptr++) = a8; *(ptr++) = a9; *(ptr++) = a10; *(ptr++) = a11; *(ptr++) = a12; *(ptr++) = a13; *(ptr++) = a14; *(ptr++) = a15; *(ptr++) = a16; *(ptr++) = a17; *(ptr++) = a18; *(ptr++) = a19; *(ptr++) = a20; *(ptr++) = a21; *(ptr++) = a22; *(ptr++) = a23; *(ptr++) = a24; return r; } //! Return a 1x1 symmetric matrix containing specified coefficients. /** \param a0 First matrix value. \note Equivalent to vector(const T&). **/ static CImg<T> tensor(const T& a0) { return matrix(a0); } //! Return a 2x2 symmetric matrix tensor containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2) { return matrix(a0,a1,a1,a2); } //! Return a 3x3 symmetric matrix containing specified coefficients. static CImg<T> tensor(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4, const T& a5) { return matrix(a0,a1,a2,a1,a3,a4,a2,a4,a5); } //! Return a 1x1 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0) { return matrix(a0); } //! Return a 2x2 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1) { return matrix(a0,0,0,a1); } //! Return a 3x3 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2) { return matrix(a0,0,0,0,a1,0,0,0,a2); } //! Return a 4x4 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3) { return matrix(a0,0,0,0,0,a1,0,0,0,0,a2,0,0,0,0,a3); } //! Return a 5x5 diagonal matrix containing specified coefficients. static CImg<T> diagonal(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) { return matrix(a0,0,0,0,0,0,a1,0,0,0,0,0,a2,0,0,0,0,0,a3,0,0,0,0,0,a4); } //! Return a NxN identity matrix. /** \param N Dimension of the matrix. **/ static CImg<T> identity_matrix(const unsigned int N) { CImg<T> res(N,N,1,1,0); cimg_forX(res,x) res(x,x) = 1; return res; } //! Return a N-numbered sequence vector from \p a0 to \p a1. /** \param N Size of the resulting vector. \param a0 Starting value of the sequence. \param a1 Ending value of the sequence. **/ static CImg<T> sequence(const unsigned int N, const T a0, const T a1) { if (N) return CImg<T>(1,N).sequence(a0,a1); return CImg<T>(); } //! Return a 3x3 rotation matrix along the (x,y,z)-axis with an angle w. /** \param x X-coordinate of the rotation axis, or first quaternion coordinate. \param y Y-coordinate of the rotation axis, or second quaternion coordinate. \param z Z-coordinate of the rotation axis, or third quaternion coordinate. \param w Angle of the rotation axis, or fourth quaternion coordinate. \param is_quaternion Tell is the four arguments denotes a set { axis + angle } or a quaternion. **/ static CImg<T> rotation_matrix(const float x, const float y, const float z, const float w, const bool is_quaternion=false) { float X,Y,Z,W; if (!is_quaternion) { const float norm = (float)std::sqrt(x*x + y*y + z*z), nx = norm>0?x/norm:0, ny = norm>0?y/norm:0, nz = norm>0?z/norm:1, nw = norm>0?w:0, sina = (float)std::sin(nw/2), cosa = (float)std::cos(nw/2); X = nx*sina; Y = ny*sina; Z = nz*sina; W = cosa; } else { const float norm = (float)std::sqrt(x*x + y*y + z*z + w*w); if (norm>0) { X = x/norm; Y = y/norm; Z = z/norm; W = w/norm; } else { X = Y = Z = 0; W = 1; } } const float xx = X*X, xy = X*Y, xz = X*Z, xw = X*W, yy = Y*Y, yz = Y*Z, yw = Y*W, zz = Z*Z, zw = Z*W; return CImg<T>::matrix((T)(1-2*(yy+zz)), (T)(2*(xy+zw)), (T)(2*(xz-yw)), (T)(2*(xy-zw)), (T)(1-2*(xx+zz)), (T)(2*(yz+xw)), (T)(2*(xz+yw)), (T)(2*(yz-xw)), (T)(1-2*(xx+yy))); } //@} //----------------------------------- // //! \name Value Manipulation //@{ //----------------------------------- //! Fill all pixel values with specified value. /** \param val Fill value. **/ CImg<T>& fill(const T val) { if (is_empty()) return *this; if (val && sizeof(T)!=1) cimg_for(*this,ptrd,T) *ptrd = val; else std::memset(_data,(int)val,sizeof(T)*size()); return *this; } //! Fill all pixel values with specified value \newinstance. CImg<T> get_fill(const T val) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val); } //! Fill sequentially all pixel values with specified values. /** \param val0 First fill value. \param val1 Second fill value. **/ CImg<T>& fill(const T val0, const T val1) { if (is_empty()) return *this; T *ptrd, *ptre = end()-1; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; } if (ptrd!=ptre+1) *(ptrd++) = val0; return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2) { if (is_empty()) return *this; T *ptrd, *ptre = end()-2; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; } ptre+=2; switch (ptre - ptrd) { case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3) { if (is_empty()) return *this; T *ptrd, *ptre = end()-3; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; } ptre+=3; switch (ptre - ptrd) { case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4) { if (is_empty()) return *this; T *ptrd, *ptre = end()-4; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; } ptre+=4; switch (ptre - ptrd) { case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5) { if (is_empty()) return *this; T *ptrd, *ptre = end()-5; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; } ptre+=5; switch (ptre - ptrd) { case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6) { if (is_empty()) return *this; T *ptrd, *ptre = end()-6; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; } ptre+=6; switch (ptre - ptrd) { case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7) { if (is_empty()) return *this; T *ptrd, *ptre = end()-7; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; } ptre+=7; switch (ptre - ptrd) { case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8) { if (is_empty()) return *this; T *ptrd, *ptre = end()-8; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; } ptre+=8; switch (ptre - ptrd) { case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9) { if (is_empty()) return *this; T *ptrd, *ptre = end()-9; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; } ptre+=9; switch (ptre - ptrd) { case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10) { if (is_empty()) return *this; T *ptrd, *ptre = end()-10; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; } ptre+=10; switch (ptre - ptrd) { case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11) { if (is_empty()) return *this; T *ptrd, *ptre = end()-11; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; } ptre+=11; switch (ptre - ptrd) { case 11 : *(--ptre) = val10; case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12) { if (is_empty()) return *this; T *ptrd, *ptre = end()-12; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; } ptre+=12; switch (ptre - ptrd) { case 12 : *(--ptre) = val11; case 11 : *(--ptre) = val10; case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13) { if (is_empty()) return *this; T *ptrd, *ptre = end()-13; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; } ptre+=13; switch (ptre - ptrd) { case 13 : *(--ptre) = val12; case 12 : *(--ptre) = val11; case 11 : *(--ptre) = val10; case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12, val13); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13, const T val14) { if (is_empty()) return *this; T *ptrd, *ptre = end()-14; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; } ptre+=14; switch (ptre - ptrd) { case 14 : *(--ptre) = val13; case 13 : *(--ptre) = val12; case 12 : *(--ptre) = val11; case 11 : *(--ptre) = val10; case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13, const T val14) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12, val13,val14); } //! Fill sequentially all pixel values with specified values \overloading. CImg<T>& fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13, const T val14, const T val15) { if (is_empty()) return *this; T *ptrd, *ptre = end()-15; for (ptrd = _data; ptrd<ptre; ) { *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5; *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11; *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; *(ptrd++) = val15; } ptre+=15; switch (ptre - ptrd) { case 15 : *(--ptre) = val14; case 14 : *(--ptre) = val13; case 13 : *(--ptre) = val12; case 12 : *(--ptre) = val11; case 11 : *(--ptre) = val10; case 10 : *(--ptre) = val9; case 9 : *(--ptre) = val8; case 8 : *(--ptre) = val7; case 7 : *(--ptre) = val6; case 6 : *(--ptre) = val5; case 5 : *(--ptre) = val4; case 4 : *(--ptre) = val3; case 3 : *(--ptre) = val2; case 2 : *(--ptre) = val1; case 1 : *(--ptre) = val0; } return *this; } //! Fill sequentially all pixel values with specified values \newinstance. CImg<T> get_fill(const T val0, const T val1, const T val2, const T val3, const T val4, const T val5, const T val6, const T val7, const T val8, const T val9, const T val10, const T val11, const T val12, const T val13, const T val14, const T val15) const { return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3,val4,val5,val6,val7,val8,val9,val10,val11,val12, val13,val14,val15); } //! Fill sequentially pixel values according to a given expression. /** \param expression C-string describing a math formula, or a list of values. \param repeat_flag In case a list of values is provided, tells if this list must be repeated for the filling. **/ CImg<T>& fill(const char *const expression, const bool repeat_flag) { if (is_empty() || !expression || !*expression) return *this; const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { // Try to fill values according to a formula. const CImg<T> _base = std::strstr(expression,"i(")?+*this:CImg<T>(), &base = _base?_base:*this; _cimg_math_parser mp(base,expression,"fill"); T *ptrd = _data; cimg_forXYZC(*this,x,y,z,c) *(ptrd++) = (T)mp.eval((double)x,(double)y,(double)z,(double)c); } catch (CImgException& e) { // If failed, try to recognize a list of values. char item[16384] = { 0 }, sep = 0; const char *nexpression = expression; unsigned long nb = 0; const unsigned long siz = size(); T *ptrd = _data; for (double val = 0; *nexpression && nb<siz; ++nb) { sep = 0; const int err = std::sscanf(nexpression,"%4095[ \n\t0-9.e+-]%c",item,&sep); if (err>0 && std::sscanf(item,"%lf",&val)==1) { nexpression+=std::strlen(item) + (err>1?1:0); *(ptrd++) = (T)val; } else break; } cimg::exception_mode() = omode; if (nb<siz && (sep || *nexpression)) throw CImgArgumentException(e.what(),pixel_type(),expression); if (repeat_flag && nb && nb<siz) for (T *ptrs = _data, *const ptre = _data + siz; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; } cimg::exception_mode() = omode; return *this; } //! Fill sequentially pixel values according to a given expression \newinstance. CImg<T> get_fill(const char *const values, const bool repeat_values) const { return (+*this).fill(values,repeat_values); } //! Fill sequentially pixel values according to the values found in another image. /** \param values Image containing the values used for the filling. \param repeat_values In case there are less values than necessary in \c values, tells if these values must be repeated for the filling. **/ template<typename t> CImg<T>& fill(const CImg<t>& values, const bool repeat_values=true) { if (is_empty() || !values) return *this; T *ptrd = _data, *ptre = ptrd + size(); for (t *ptrs = values._data, *ptrs_end = ptrs + values.size(); ptrs<ptrs_end && ptrd<ptre; ++ptrs) *(ptrd++) = (T)*ptrs; if (repeat_values && ptrd<ptre) for (T *ptrs = _data; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs; return *this; } //! Fill sequentially pixel values according to the values found in another image \newinstance. template<typename t> CImg<T> get_fill(const CImg<t>& values, const bool repeat_values=true) const { return repeat_values?CImg<T>(_width,_height,_depth,_spectrum).fill(values,repeat_values):(+*this).fill(values,repeat_values); } //! Fill pixel values along the X-axis at a specified pixel position. /** \param y Y-coordinate of the filled column. \param z Z-coordinate of the filled column. \param c C-coordinate of the filled column. \param a0 First fill value. **/ CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const int a0, ...) { #define _cimg_fill1(x,y,z,c,off,siz,t) { \ va_list ap; va_start(ap,a0); T *ptrd = data(x,y,z,c); *ptrd = (T)a0; \ for (unsigned long k = 1; k<siz; ++k) { ptrd+=off; *ptrd = (T)va_arg(ap,t); } \ va_end(ap); } if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,int); return *this; } //! Fill pixel values along the X-axis at a specified pixel position \overloading. CImg<T>& fillX(const unsigned int y, const unsigned int z, const unsigned int c, const double a0, ...) { if (y<_height && z<_depth && c<_spectrum) _cimg_fill1(0,y,z,c,1,_width,double); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position. /** \param x X-coordinate of the filled row. \param z Z-coordinate of the filled row. \param c C-coordinate of the filled row. \param a0 First fill value. **/ CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const int a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,int); return *this; } //! Fill pixel values along the Y-axis at a specified pixel position \overloading. CImg<T>& fillY(const unsigned int x, const unsigned int z, const unsigned int c, const double a0, ...) { if (x<_width && z<_depth && c<_spectrum) _cimg_fill1(x,0,z,c,_width,_height,double); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position. /** \param x X-coordinate of the filled slice. \param y Y-coordinate of the filled slice. \param c C-coordinate of the filled slice. \param a0 First fill value. **/ CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const int a0, ...) { const unsigned long wh = (unsigned long)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,int); return *this; } //! Fill pixel values along the Z-axis at a specified pixel position \overloading. CImg<T>& fillZ(const unsigned int x, const unsigned int y, const unsigned int c, const double a0, ...) { const unsigned long wh = (unsigned long)_width*_height; if (x<_width && y<_height && c<_spectrum) _cimg_fill1(x,y,0,c,wh,_depth,double); return *this; } //! Fill pixel values along the C-axis at a specified pixel position. /** \param x X-coordinate of the filled channel. \param y Y-coordinate of the filled channel. \param z Z-coordinate of the filled channel. \param a0 First filling value. **/ CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const int a0, ...) { const unsigned long whd = (unsigned long)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,int); return *this; } //! Fill pixel values along the C-axis at a specified pixel position \overloading. CImg<T>& fillC(const unsigned int x, const unsigned int y, const unsigned int z, const double a0, ...) { const unsigned long whd = (unsigned long)_width*_height*_depth; if (x<_width && y<_height && z<_depth) _cimg_fill1(x,y,z,0,whd,_spectrum,double); return *this; } //! Discard specified value in the image buffer. /** \param value Value to discard. \note Discarded values will change the image geometry, so the resulting image is returned as a one-column vector. **/ CImg<T>& discard(const T value) { return get_discard(value).move_to(*this); } //! Discard specified value in the image buffer \newinstance. CImg<T> get_discard(const T value) const { CImg<T> res(1,size()); T *pd = res._data; for (const T *ps = _data, *const pse = end(); ps<pse; ++ps) if (*ps!=value) *(pd++) = *ps; if (pd==res._data) return CImg<T>(); return res.resize(1,pd-res._data,1,1,-1); } //! Discard specified sequence of values in the image buffer. /** \param values Sequence of values to discard. \note Discarded values will change the image geometry, so the resulting image is returned as a one-column vector. **/ template<typename t> CImg<T>& discard(const CImg<t>& values) { return get_discard(values).move_to(*this); } //! Discard specified sequence of values in the image buffer \newinstance. template<typename t> CImg<T> get_discard(const CImg<t>& values) const { if (!values) return *this; if (values.size()==1) return get_discard(*values); CImg<T> res(1,size()); T *pd = res._data; const t *const pve = values.end(); for (const T *ps = _data, *const pse = end(); ps<pse; ) { const T *_ps = ps; const t *pv = values._data; while (_ps<pse && pv<pve) { if (*(_ps++)!=(T)*pv) break; ++pv; } if (pv!=pve) { const unsigned int l = _ps - ps; if (l==1) *(pd++) = *ps; else { std::memcpy(pd,ps,sizeof(T)*l); pd+=l; } } ps = _ps; } if (pd==res._data) return CImg<T>(); return res.resize(1,pd-res._data,1,1,-1); } //! Invert endianness of all pixel values. /** **/ CImg<T>& invert_endianness() { cimg::invert_endianness(_data,size()); return *this; } //! Invert endianness of all pixel values \newinstance. CImg<T> get_invert_endianness() const { return (+*this).invert_endianness(); } //! Fill image with random values in specified range. /** \param val_min Minimal random value. \param val_max Maximal random value. \note Random samples are following a uniform distribution. **/ CImg<T>& rand(const T val_min, const T val_max) { const float delta = (float)val_max - (float)val_min; cimg_for(*this,ptrd,T) *ptrd = (T)(val_min + cimg::rand()*delta); return *this; } //! Fill image with random values in specified range \newinstance. CImg<T> get_rand(const T val_min, const T val_max) const { return (+*this).rand(val_min,val_max); } //! Round pixel values. /** \param y Rounding precision. \param rounding_type Rounding type. Can be: - \c -1: Backward. - \c 0: Nearest. - \c 1: Forward. **/ CImg<T>& round(const double y=1, const int rounding_type=0) { if (y>0) cimg_for(*this,ptrd,T) *ptrd = cimg::round(*ptrd,y,rounding_type); return *this; } //! Round pixel values \newinstance. CImg<T> get_round(const double y=1, const unsigned int rounding_type=0) const { return (+*this).round(y,rounding_type); } //! Add random noise to pixel values. /** \param sigma Amplitude of the random additive noise. If \p sigma<0, it stands for a percentage of the global value range. \param noise_type Type of additive noise (can be \p 0=gaussian, \p 1=uniform, \p 2=Salt and Pepper, \p 3=Poisson or \p 4=Rician). \return A reference to the modified image instance. \note - For Poisson noise (\p noise_type=3), parameter \p sigma is ignored, as Poisson noise only depends on the image value itself. - Function \p CImg<T>::get_noise() is also defined. It returns a non-shared modified copy of the image instance. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_noise(40); (img,res.normalize(0,255)).display(); \endcode \image html ref_noise.jpg **/ CImg<T>& noise(const double sigma, const unsigned int noise_type=0) { if (!is_empty()) { const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); Tfloat nsigma = (Tfloat)sigma, m = 0, M = 0; if (nsigma==0 && noise_type!=3) return *this; if (nsigma<0 || noise_type==2) m = (Tfloat)min_max(M); if (nsigma<0) nsigma = (Tfloat)(-nsigma*(M-m)/100.0); switch (noise_type) { case 0 : { // Gaussian noise cimg_for(*this,ptrd,T) { Tfloat val = (Tfloat)(*ptrd + nsigma*cimg::grand()); if (val>vmax) val = vmax; if (val<vmin) val = vmin; *ptrd = (T)val; } } break; case 1 : { // Uniform noise cimg_for(*this,ptrd,T) { Tfloat val = (Tfloat)(*ptrd + nsigma*cimg::crand()); if (val>vmax) val = vmax; if (val<vmin) val = vmin; *ptrd = (T)val; } } break; case 2 : { // Salt & Pepper noise if (nsigma<0) nsigma = -nsigma; if (M==m) { m = 0; M = (Tfloat)(cimg::type<T>::is_float()?1:cimg::type<T>::max()); } cimg_for(*this,ptrd,T) if (cimg::rand()*100<nsigma) *ptrd = (T)(cimg::rand()<0.5?M:m); } break; case 3 : { // Poisson Noise cimg_for(*this,ptrd,T) *ptrd = (T)cimg::prand(*ptrd); } break; case 4 : { // Rice noise const Tfloat sqrt2 = (Tfloat)std::sqrt(2.0); cimg_for(*this,ptrd,T) { const Tfloat val0 = (Tfloat)*ptrd/sqrt2, re = (Tfloat)(val0 + nsigma*cimg::grand()), im = (Tfloat)(val0 + nsigma*cimg::grand()); Tfloat val = (Tfloat)std::sqrt(re*re + im*im); if (val>vmax) val = vmax; if (val<vmin) val = vmin; *ptrd = (T)val; } } break; default : throw CImgArgumentException(_cimg_instance "noise(): Invalid specified noise type %d " "(should be { 0=gaussian | 1=uniform | 2=salt&Pepper | 3=poisson }).", cimg_instance, noise_type); } } return *this; } //! Add random noise to pixel values \newinstance. CImg<T> get_noise(const double sigma, const unsigned int noise_type=0) const { return (+*this).noise(sigma,noise_type); } //! Linearly normalize pixel values. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(160,220); (img,res).display(); \endcode \image html ref_normalize2.jpg **/ CImg<T>& normalize(const T min_value, const T max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; T m, M = max_min(m); const Tfloat fm = (Tfloat)m, fM = (Tfloat)M; if (m==M) return fill(min_value); if (m!=a || M!=b) cimg_for(*this,ptrd,T) *ptrd = (T)((*ptrd-fm)/(fM-fm)*(b-a)+a); return *this; } //! Linearly normalize pixel values \newinstance. CImg<Tfloat> get_normalize(const T min_value, const T max_value) const { return CImg<Tfloat>(*this,false).normalize((Tfloat)min_value,(Tfloat)max_value); } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm. /** \par Example \code const CImg<float> img("reference.jpg"), res = img.get_normalize(); (img,res.normalize(0,255)).display(); \endcode \image html ref_normalize.jpg **/ CImg<T>& normalize() { T *ptrd = _data; const unsigned long whd = (unsigned long)_width*_height*_depth; cimg_forXYZ(*this,x,y,z) { const T *ptrs = ptrd; float n = 0; cimg_forC(*this,c) { n+=cimg::sqr((float)*ptrs); ptrs+=whd; } n = (float)std::sqrt(n); T *_ptrd = ptrd++; if (n>0) cimg_forC(*this,c) { *_ptrd = (T)(*_ptrd/n); _ptrd+=whd; } else cimg_forC(*this,c) { *_ptrd = (T)0; _ptrd+=whd; } } return *this; } //! Normalize multi-valued pixels of the image instance, with respect to their L2-norm \newinstance. CImg<Tfloat> get_normalize() const { return CImg<Tfloat>(*this,false).normalize(); } //! Compute L2-norm of each multi-valued pixel of the image instance. /** \param norm_type Type of computed vector norm (can be \p 0=Linf, \p 1=L1 or \p 2=L2). \par Example \code const CImg<float> img("reference.jpg"), res = img.get_norm(); (img,res.normalize(0,255)).display(); \endcode \image html ref_norm.jpg **/ CImg<T>& norm(const int norm_type=2) { if (_spectrum==1) return abs(); return get_norm(norm_type).move_to(*this); } //! Compute L2-norm of each multi-valued pixel of the image instance \newinstance. CImg<Tfloat> get_norm(const int norm_type=2) const { if (is_empty()) return *this; if (_spectrum==1) return get_abs(); const T *ptrs = _data; const unsigned long whd = (unsigned long)_width*_height*_depth; CImg<Tfloat> res(_width,_height,_depth); Tfloat *ptrd = res._data; switch (norm_type) { case -1 : { // Linf norm cimg_forXYZ(*this,x,y,z) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { const Tfloat val = (Tfloat)cimg::abs(*_ptrs); if (val>n) n = val; _ptrs+=whd; } *(ptrd++) = n; } } break; case 1 : { // L1 norm cimg_forXYZ(*this,x,y,z) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::abs(*_ptrs); _ptrs+=whd; } *(ptrd++) = n; } } break; default : { // L2 norm cimg_forXYZ(*this,x,y,z) { Tfloat n = 0; const T *_ptrs = ptrs++; cimg_forC(*this,c) { n+=cimg::sqr((Tfloat)*_ptrs); _ptrs+=whd; } *(ptrd++) = (Tfloat)std::sqrt((Tfloat)n); } } } return res; } //! Cut pixel values in specified range. /** \param min_value Minimum desired value of the resulting image. \param max_value Maximum desired value of the resulting image. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_cut(160,220); (img,res).display(); \endcode \image html ref_cut.jpg **/ CImg<T>& cut(const T min_value, const T max_value) { if (is_empty()) return *this; const T a = min_value<max_value?min_value:max_value, b = min_value<max_value?max_value:min_value; cimg_for(*this,ptrd,T) *ptrd = (*ptrd<a)?a:((*ptrd>b)?b:*ptrd); return *this; } //! Cut pixel values in specified range \newinstance. CImg<T> get_cut(const T min_value, const T max_value) const { return (+*this).cut(min_value,max_value); } //! Uniformly quantize pixel values. /** \param nb_levels Number of quantization levels. \param keep_range Tells if resulting values keep the same range as the original ones. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_quantize(4); (img,res).display(); \endcode \image html ref_quantize.jpg **/ CImg<T>& quantize(const unsigned int nb_levels, const bool keep_range=true) { if (!nb_levels) throw CImgArgumentException(_cimg_instance "quantize(): Invalid quantization request with 0 values.", cimg_instance); if (is_empty()) return *this; Tfloat m, M = (Tfloat)max_min(m), range = M - m; if (range>0) { if (keep_range) cimg_for(*this,ptrd,T) { const unsigned int val = (unsigned int)((*ptrd-m)*nb_levels/range); *ptrd = (T)(m + cimg::min(val,nb_levels-1)*range/nb_levels); } else cimg_for(*this,ptrd,T) { const unsigned int val = (unsigned int)((*ptrd-m)*nb_levels/range); *ptrd = (T)cimg::min(val,nb_levels-1); } } return *this; } //! Uniformly quantize pixel values \newinstance. CImg<T> get_quantize(const unsigned int n, const bool keep_range=true) const { return (+*this).quantize(n,keep_range); } //! Threshold pixel values. /** \param value Threshold value \param soft_threshold Tells if soft thresholding must be applied (instead of hard one). \param strict_threshold Tells if threshold value is strict. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_threshold(128); (img,res.normalize(0,255)).display(); \endcode \image html ref_threshold.jpg **/ CImg<T>& threshold(const T value, const bool soft_threshold=false, const bool strict_threshold=false) { if (is_empty()) return *this; if (strict_threshold) { if (soft_threshold) cimg_for(*this,ptrd,T) { const T v = *ptrd; *ptrd = v>value?(T)(v-value):v<-(float)value?(T)(v+value):(T)0; } else cimg_for(*this,ptrd,T) *ptrd = *ptrd>value?(T)1:(T)0; } else { if (soft_threshold) cimg_for(*this,ptrd,T) { const T v = *ptrd; *ptrd = v>=value?(T)(v-value):v<=-(float)value?(T)(v+value):(T)0; } else cimg_for(*this,ptrd,T) *ptrd = *ptrd>=value?(T)1:(T)0; } return *this; } //! Threshold pixel values \newinstance. CImg<T> get_threshold(const T value, const bool soft_threshold=false, const bool strict_threshold=false) const { return (+*this).threshold(value,soft_threshold,strict_threshold); } //! Compute the histogram of pixel values. /** \param nb_levels Number of desired histogram levels. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \note - The histogram H of an image I is the 1d function where H(x) counts the number of occurences of the value x in the image I. - If \p min_value==max_value==0 (default behavior), the function first estimates the whole range of pixel values then uses it to compute the histogram. - The resulting histogram is always defined in 1d. Histograms of multi-valued images are not multi-dimensional. \par Example \code const CImg<float> img = CImg<float>("reference.jpg").histogram(256); img.display_graph(0,3); \endcode \image html ref_histogram.jpg **/ CImg<T>& histogram(const unsigned int nb_levels, const T min_value=(T)0, const T max_value=(T)0) { return get_histogram(nb_levels,min_value,max_value).move_to(*this); } //! Compute the histogram of pixel values \newinstance. CImg<floatT> get_histogram(const unsigned int nb_levels, const T min_value=(T)0, const T max_value=(T)0) const { if (!nb_levels || is_empty()) return CImg<floatT>(); T vmin = min_value<max_value?min_value:max_value, vmax = min_value<max_value?max_value:min_value; if (vmin==vmax && vmin==0) vmin = min_max(vmax); CImg<floatT> res(nb_levels,1,1,1,0); cimg_for(*this,ptrs,T) { const T val = *ptrs; if (val>=vmin && val<=vmax) ++res[val==vmax?nb_levels-1:(unsigned int)((val-vmin)*nb_levels/(vmax-vmin))]; } return res; } //! Equalize histogram of pixel values. /** \param nb_levels Number of histogram levels used for the equalization. \param min_value Minimum pixel value considered for the histogram computation. All pixel values lower than \p min_value will not be counted. \param max_value Maximum pixel value considered for the histogram computation. All pixel values higher than \p max_value will not be counted. \note - If \p min_value==max_value==0 (default behavior), the function first estimates the whole range of pixel values then uses it to equalize the histogram. \par Example \code const CImg<float> img("reference.jpg"), res = img.get_equalize(256); (img,res).display(); \endcode \image html ref_equalize.jpg **/ CImg<T>& equalize(const unsigned int nb_levels, const T min_value=(T)0, const T max_value=(T)0) { if (is_empty()) return *this; T vmin = min_value, vmax = max_value; if (vmin==vmax && vmin==0) vmin = min_max(vmax); if (vmin<vmax) { CImg<floatT> hist = get_histogram(nb_levels,vmin,vmax); float cumul = 0; cimg_forX(hist,pos) { cumul+=hist[pos]; hist[pos] = cumul; } cimg_for(*this,ptrd,T) { const int pos = (unsigned int)((*ptrd-vmin)*(nb_levels-1)/(vmax-vmin)); if (pos>=0 && pos<(int)nb_levels) *ptrd = (T)(vmin + (vmax-vmin)*hist[pos]/size()); } } return *this; } //! Equalize histogram of pixel values \newinstance. CImg<T> get_equalize(const unsigned int nblevels, const T val_min=(T)0, const T val_max=(T)0) const { return (+*this).equalize(nblevels,val_min,val_max); } //! Index multi-valued pixels regarding to a specified colormap. /** \param colormap Multi-valued colormap used as the basis for multi-valued pixel indexing. \param dithering Level of dithering (0=disable, 1=standard level). \param map_indexes Tell if the values of the resulting image are the colormap indices or the colormap vectors. \note - \p img.index(colormap,dithering,1) is equivalent to <tt>img.index(colormap,dithering,0).map(colormap)</tt>. \par Example \code const CImg<float> img("reference.jpg"), colormap(3,1,1,3, 0,128,255, 0,128,255, 0,128,255); const CImg<float> res = img.get_index(colormap,1,true); (img,res).display(); \endcode \image html ref_index.jpg **/ template<typename t> CImg<T>& index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=false) { return get_index(colormap,dithering,map_indexes).move_to(*this); } //! Index multi-valued pixels regarding to a specified colormap \newinstance. template<typename t> CImg<typename CImg<t>::Tuint> get_index(const CImg<t>& colormap, const float dithering=1, const bool map_indexes=true) const { if (colormap._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "index(): Instance and specified colormap (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); typedef typename CImg<t>::Tuint tuint; if (is_empty()) return CImg<tuint>(); const unsigned long whd = (unsigned long)_width*_height*_depth, pwhd = (unsigned long)colormap._width*colormap._height*colormap._depth; CImg<tuint> res(_width,_height,_depth,map_indexes?_spectrum:1); tuint *ptrd = res._data; if (dithering>0) { // Dithered versions. const float ndithering = (dithering<0?0:dithering>1?1:dithering)/16; Tfloat valm = 0, valM = (Tfloat)max_min(valm); if (valm==valM && valm>=0 && valM<=255) { valm = 0; valM = 255; } CImg<Tfloat> cache = get_crop(-1,0,0,0,_width,1,0,_spectrum-1); Tfloat *cache_current = cache.data(1,0,0,0), *cache_next = cache.data(1,1,0,0); const unsigned long cwhd = (unsigned long)cache._width*cache._height*cache._depth; switch (_spectrum) { case 1 : { // Optimized for scalars. cimg_forYZ(*this,y,z) { if (y<height()-2) { Tfloat *ptrc0 = cache_next; const T *ptrs0 = data(0,y+1,z,0); cimg_forX(*this,x) *(ptrc0++) = (Tfloat)*(ptrs0++); } Tfloat *ptrs0 = cache_current, *ptrsn0 = cache_next; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering; *ptrs0+=7*err0; *(ptrsn0-1)+=3*err0; *(ptrsn0++)+=5*err0; *ptrsn0+=err0; if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 2 : { // Optimized for 2d vectors. tuint *ptrd1 = ptrd + whd; cimg_forYZ(*this,y,z) { if (y<height()-2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd; const T *ptrs0 = data(0,y+1,z,0), *ptrs1 = ptrs0 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *(ptrsn0-1)+=3*err0; *(ptrsn1-1)+=3*err1; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *ptrsn0+=err0; *ptrsn1+=err1; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; case 3 : { // Optimized for 3d vectors (colors). tuint *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; cimg_forYZ(*this,y,z) { if (y<height()-2) { Tfloat *ptrc0 = cache_next, *ptrc1 = ptrc0 + cwhd, *ptrc2 = ptrc1 + cwhd; const T *ptrs0 = data(0,y+1,z,0), *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd; cimg_forX(*this,x) { *(ptrc0++) = (Tfloat)*(ptrs0++); *(ptrc1++) = (Tfloat)*(ptrs1++); *(ptrc2++) = (Tfloat)*(ptrs2++); } } Tfloat *ptrs0 = cache_current, *ptrs1 = ptrs0 + cwhd, *ptrs2 = ptrs1 + cwhd, *ptrsn0 = cache_next, *ptrsn1 = ptrsn0 + cwhd, *ptrsn2 = ptrsn1 + cwhd; cimg_forX(*this,x) { const Tfloat _val0 = (Tfloat)*ptrs0, val0 = _val0<valm?valm:_val0>valM?valM:_val0, _val1 = (Tfloat)*ptrs1, val1 = _val1<valm?valm:_val1>valM?valM:_val1, _val2 = (Tfloat)*ptrs2, val2 = _val2<valm?valm:_val2>valM?valM:_val2; Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } const t *const ptrmin1 = ptrmin0 + pwhd, *const ptrmin2 = ptrmin1 + pwhd; const Tfloat err0 = ((*(ptrs0++)=val0) - (Tfloat)*ptrmin0)*ndithering, err1 = ((*(ptrs1++)=val1) - (Tfloat)*ptrmin1)*ndithering, err2 = ((*(ptrs2++)=val2) - (Tfloat)*ptrmin2)*ndithering; *ptrs0+=7*err0; *ptrs1+=7*err1; *ptrs2+=7*err2; *(ptrsn0-1)+=3*err0; *(ptrsn1-1)+=3*err1; *(ptrsn2-1)+=3*err2; *(ptrsn0++)+=5*err0; *(ptrsn1++)+=5*err1; *(ptrsn2++)+=5*err2; *ptrsn0+=err0; *ptrsn1+=err1; *ptrsn2+=err2; if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*ptrmin1; *(ptrd2++) = (tuint)*ptrmin2; } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } cimg::swap(cache_current,cache_next); } } break; default : // Generic version cimg_forYZ(*this,y,z) { if (y<height()-2) { Tfloat *ptrc = cache_next; cimg_forC(*this,c) { Tfloat *_ptrc = ptrc; const T *_ptrs = data(0,y+1,z,c); cimg_forX(*this,x) *(_ptrc++) = (Tfloat)*(_ptrs++); ptrc+=cwhd; } } Tfloat *ptrs = cache_current, *ptrsn = cache_next; cimg_forX(*this,x) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; Tfloat *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { const Tfloat _val = *_ptrs, val = _val<valm?valm:_val>valM?valM:_val; dist+=cimg::sqr((*_ptrs=val) - (Tfloat)*_ptrp); _ptrs+=cwhd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } const t *_ptrmin = ptrmin; Tfloat *_ptrs = ptrs++, *_ptrsn = (ptrsn++)-1; cimg_forC(*this,c) { const Tfloat err = (*(_ptrs++) - (Tfloat)*_ptrmin)*ndithering; *_ptrs+=7*err; *(_ptrsn++)+=3*err; *(_ptrsn++)+=5*err; *_ptrsn+=err; _ptrmin+=pwhd; _ptrs+=cwhd-1; _ptrsn+=cwhd-2; } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } cimg::swap(cache_current,cache_next); } } } else { // Non-dithered versions switch (_spectrum) { case 1 : { // Optimized for scalars. for (const T *ptrs0 = _data, *ptrs_end = ptrs0 + whd; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp_end = ptrp0 + pwhd; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, dist = pval0*pval0; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) *(ptrd++) = (tuint)*ptrmin0; else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } break; case 2 : { // Optimized for 2d vectors. tuint *ptrd1 = ptrd + whd; for (const T *ptrs0 = _data, *ptrs1 = ptrs0 + whd, *ptrs_end = ptrs1; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, dist = pval0*pval0 + pval1*pval1; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } break; case 3 : { // Optimized for 3d vectors (colors). tuint *ptrd1 = ptrd + whd, *ptrd2 = ptrd1 + whd; for (const T *ptrs0 = _data, *ptrs1 = ptrs0 + whd, *ptrs2 = ptrs1 + whd, *ptrs_end = ptrs1; ptrs0<ptrs_end; ) { const Tfloat val0 = (Tfloat)*(ptrs0++), val1 = (Tfloat)*(ptrs1++), val2 = (Tfloat)*(ptrs2++); Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin0 = colormap._data; for (const t *ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd, *ptrp_end = ptrp1; ptrp0<ptrp_end; ) { const Tfloat pval0 = (Tfloat)*(ptrp0++) - val0, pval1 = (Tfloat)*(ptrp1++) - val1, pval2 = (Tfloat)*(ptrp2++) - val2, dist = pval0*pval0 + pval1*pval1 + pval2*pval2; if (dist<distmin) { ptrmin0 = ptrp0 - 1; distmin = dist; } } if (map_indexes) { *(ptrd++) = (tuint)*ptrmin0; *(ptrd1++) = (tuint)*(ptrmin0 + pwhd); *(ptrd2++) = (tuint)*(ptrmin0 + 2*pwhd); } else *(ptrd++) = (tuint)(ptrmin0 - colormap._data); } } break; default : // Generic version. for (const T *ptrs = _data, *ptrs_end = ptrs + whd; ptrs<ptrs_end; ++ptrs) { Tfloat distmin = cimg::type<Tfloat>::max(); const t *ptrmin = colormap._data; for (const t *ptrp = colormap._data, *ptrp_end = ptrp + pwhd; ptrp<ptrp_end; ++ptrp) { Tfloat dist = 0; const T *_ptrs = ptrs; const t *_ptrp = ptrp; cimg_forC(*this,c) { dist+=cimg::sqr((Tfloat)*_ptrs - (Tfloat)*_ptrp); _ptrs+=whd; _ptrp+=pwhd; } if (dist<distmin) { ptrmin = ptrp; distmin = dist; } } if (map_indexes) { tuint *_ptrd = ptrd++; cimg_forC(*this,c) { *_ptrd = (tuint)*ptrmin; _ptrd+=whd; ptrmin+=pwhd; } } else *(ptrd++) = (tuint)(ptrmin - colormap._data); } } } return res; } //! Map predefined colormap on the scalar (indexed) image instance. /** \param colormap Multi-valued colormap used for mapping the indexes. \par Example \code const CImg<float> img("reference.jpg"), colormap1(3,1,1,3, 0,128,255, 0,128,255, 0,128,255), colormap2(3,1,1,3, 255,0,0, 0,255,0, 0,0,255), res = img.get_index(colormap1,0).map(colormap2); (img,res).display(); \endcode \image html ref_map.jpg **/ template<typename t> CImg<T>& map(const CImg<t>& colormap) { return get_map(colormap).move_to(*this); } //! Map predefined colormap on the scalar (indexed) image instance \newinstance. template<typename t> CImg<t> get_map(const CImg<t>& colormap) const { if (_spectrum!=1 && colormap._spectrum!=1) throw CImgArgumentException(_cimg_instance "map(): Instance and specified colormap (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); const unsigned long whd = (unsigned long)_width*_height*_depth, pwhd = (unsigned long)colormap._width*colormap._height*colormap._depth; CImg<t> res(_width,_height,_depth,colormap._spectrum==1?_spectrum:colormap._spectrum); switch (colormap._spectrum) { case 1 : { // Optimized for scalars. const T *ptrs = _data; cimg_for(res,ptrd,t) { const unsigned long _ind = (unsigned long)*(ptrs++), ind = _ind<pwhd?_ind:0; *ptrd = colormap[ind]; } } break; case 2 : { // Optimized for 2d vectors. const t *const ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd; t *ptrd0 = res._data, *ptrd1 = ptrd0 + whd; for (const T *ptrs = _data, *ptrs_end = ptrs + whd; ptrs<ptrs_end; ) { const unsigned long _ind = (unsigned long)*(ptrs++), ind = _ind<pwhd?_ind:0; *(ptrd0++) = ptrp0[ind]; *(ptrd1++) = ptrp1[ind]; } } break; case 3 : { // Optimized for 3d vectors (colors). const t *const ptrp0 = colormap._data, *ptrp1 = ptrp0 + pwhd, *ptrp2 = ptrp1 + pwhd; t *ptrd0 = res._data, *ptrd1 = ptrd0 + whd, *ptrd2 = ptrd1 + whd; for (const T *ptrs = _data, *ptrs_end = ptrs + whd; ptrs<ptrs_end; ) { const unsigned long _ind = (unsigned long)*(ptrs++), ind = _ind<pwhd?_ind:0; *(ptrd0++) = ptrp0[ind]; *(ptrd1++) = ptrp1[ind]; *(ptrd2++) = ptrp2[ind]; } } break; default : { // Generic version. t *ptrd = res._data; for (const T *ptrs = _data, *ptrs_end = ptrs + whd; ptrs<ptrs_end; ) { const unsigned long _ind = (unsigned long)*(ptrs++), ind = _ind<pwhd?_ind:0; const t *ptrp = colormap._data + ind; t *_ptrd = ptrd++; cimg_forC(res,c) { *_ptrd = *ptrp; _ptrd+=whd; ptrp+=pwhd; } } } } return res; } //! Label connected components. /** \param is_high_connectivity Boolean that choose between 4(false)- or 8(true)-connectivity in 2d case, and between 6(false)- or 26(true)-connectivity in 3d case. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. \note The algorithm of connected components computation has been primarily done by A. Meijster, according to the publication: 'W.H. Hesselink, A. Meijster, C. Bron, "Concurrent Determination of Connected Components.", In: Science of Computer Programming 41 (2001), pp. 173--194'. The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& label(const bool is_high_connectivity=false, const Tfloat tolerance=0) { return get_label(is_high_connectivity,tolerance).move_to(*this); } //! Label connected components \newinstance. CImg<unsigned long> get_label(const bool is_high_connectivity=false, const Tfloat tolerance=0) const { if (is_empty()) return CImg<unsigned long>(); // Create neighborhood tables. int dx[13], dy[13], dz[13], nb = 0; dx[nb]=1; dy[nb] = 0; dz[nb++]=0; dx[nb]=0; dy[nb] = 1; dz[nb++]=0; if (is_high_connectivity) { dx[nb]=1; dy[nb] = 1; dz[nb++]=0; dx[nb]=1; dy[nb] = -1; dz[nb++]=0; } if (_depth>1) { // 3d version. dx[nb]=0; dy[nb] = 0; dz[nb++]=1; if (is_high_connectivity) { dx[nb]=1; dy[nb] = 1; dz[nb++]=-1; dx[nb]=1; dy[nb] = 0; dz[nb++]=-1; dx[nb]=1; dy[nb] = -1; dz[nb++]=-1; dx[nb]=0; dy[nb] = 1; dz[nb++]=-1; dx[nb]=0; dy[nb] = 1; dz[nb++]=1; dx[nb]=1; dy[nb] = -1; dz[nb++]=1; dx[nb]=1; dy[nb] = 0; dz[nb++]=1; dx[nb]=1; dy[nb] = 1; dz[nb++]=1; } } return _get_label(nb,dx,dy,dz,tolerance); } //! Label connected components \overloading. /** \param connectivity_mask Mask of the neighboring pixels. \param tolerance Tolerance used to determine if two neighboring pixels belong to the same region. **/ template<typename t> CImg<T>& label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) { return get_label(connectivity_mask,tolerance).move_to(*this); } //! Label connected components \newinstance. template<typename t> CImg<unsigned long> get_label(const CImg<t>& connectivity_mask, const Tfloat tolerance=0) const { int nb = 0; cimg_for(connectivity_mask,ptr,t) if (*ptr) ++nb; CImg<intT> dx(nb,1,1,1,0), dy(nb,1,1,1,0), dz(nb,1,1,1,0); nb = 0; cimg_forXYZ(connectivity_mask,x,y,z) if ((x || y || z) && connectivity_mask(x,y,z)) { dx[nb] = x; dy[nb] = y; dz[nb++] = z; } return _get_label(nb,dx,dy,dz,tolerance); } CImg<unsigned long> _get_label(const unsigned int nb, const int *const dx, const int *const dy, const int *const dz, const Tfloat tolerance) const { CImg<unsigned long> res(_width,_height,_depth,_spectrum); cimg_forC(*this,c) { CImg<unsigned long> _res = res.get_shared_channel(c); // Init label numbers. unsigned long *ptr = _res.data(); cimg_foroff(_res,p) *(ptr++) = p; // For each neighbour-direction, label. for (unsigned int n = 0; n<nb; ++n) { const int _dx = dx[n], _dy = dy[n], _dz = dz[n]; if (_dx || _dy || _dz) { const int x0 = _dx<0?-_dx:0, x1 = _dx<0?_width:_width - _dx, y0 = _dy<0?-_dy:0, y1 = _dy<0?_height:_height - _dy, z0 = _dz<0?-_dz:0, z1 = _dz<0?_depth:_depth - _dz; const long wh = (long)_width*_height, offset = (long)_dz*wh + (long)_dy*_width + _dx; for (long z = z0, nz = z0 + _dz, pz = z0*wh; z<z1; ++z, ++nz, pz+=wh) { for (long y = y0, ny = y0 + _dy, py = y0*_width + pz; y<y1; ++y, ++ny, py+=_width) { for (long x = x0, nx = x0 + _dx, p = x0 + py; x<x1; ++x, ++nx, ++p) { if ((Tfloat)cimg::abs((*this)(x,y,z,c,wh)-(*this)(nx,ny,nz,c,wh))<=tolerance) { const long q = p + offset; unsigned long x, y; for (x = p<q?q:p, y = p<q?p:q; x!=y && _res[x]!=x; ) { x = _res[x]; if (x<y) cimg::swap(x,y); } if (x!=y) _res[x] = y; for (unsigned long _p = p; _p!=y; ) { const unsigned long h = _res[_p]; _res[_p] = y; _p = h; } for (unsigned long _q = q; _q!=y; ) { const unsigned long h = _res[_q]; _res[_q] = y; _q = h; } } } } } } } // Resolve equivalences. unsigned long counter = 0; ptr = _res.data(); cimg_foroff(_res,p) { *ptr = *ptr==p?counter++:_res[*ptr]; ++ptr; } } return res; } //@} //--------------------------------- // //! \name Color Base Management //@{ //--------------------------------- //! Return colormap \e "default", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_default.jpg **/ static const CImg<Tuchar>& default_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { colormap.assign(1,256,1,3); for (unsigned int index = 0, r = 16; r<256; r+=32) for (unsigned int g = 16; g<256; g+=32) for (unsigned int b = 32; b<256; b+=64) { colormap(0,index,0) = (Tuchar)r; colormap(0,index,1) = (Tuchar)g; colormap(0,index++,2) = (Tuchar)b; } } return colormap; } //! Return colormap \e "HSV", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hsv.jpg **/ static const CImg<Tuchar>& HSV_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { CImg<Tint> tmp(1,256,1,3,1); tmp.get_shared_channel(0).sequence(0,359); colormap = tmp.HSVtoRGB(); } return colormap; } //! Return colormap \e "lines", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_lines.jpg **/ static const CImg<Tuchar>& lines_LUT256() { static const unsigned char pal[] = { 217,62,88,75,1,237,240,12,56,160,165,116,1,1,204,2,15,248,148,185,133,141,46,246,222,116,16,5,207,226, 17,114,247,1,214,53,238,0,95,55,233,235,109,0,17,54,33,0,90,30,3,0,94,27,19,0,68,212,166,130,0,15,7,119, 238,2,246,198,0,3,16,10,13,2,25,28,12,6,2,99,18,141,30,4,3,140,12,4,30,233,7,10,0,136,35,160,168,184,20, 233,0,1,242,83,90,56,180,44,41,0,6,19,207,5,31,214,4,35,153,180,75,21,76,16,202,218,22,17,2,136,71,74, 81,251,244,148,222,17,0,234,24,0,200,16,239,15,225,102,230,186,58,230,110,12,0,7,129,249,22,241,37,219, 1,3,254,210,3,212,113,131,197,162,123,252,90,96,209,60,0,17,0,180,249,12,112,165,43,27,229,77,40,195,12, 87,1,210,148,47,80,5,9,1,137,2,40,57,205,244,40,8,252,98,0,40,43,206,31,187,0,180,1,69,70,227,131,108,0, 223,94,228,35,248,243,4,16,0,34,24,2,9,35,73,91,12,199,51,1,249,12,103,131,20,224,2,70,32, 233,1,165,3,8,154,246,233,196,5,0,6,183,227,247,195,208,36,0,0,226,160,210,198,69,153,210,1,23,8,192,2,4, 137,1,0,52,2,249,241,129,0,0,234,7,238,71,7,32,15,157,157,252,158,2,250,6,13,30,11,162,0,199,21,11,27,224, 4,157,20,181,111,187,218,3,0,11,158,230,196,34,223,22,248,135,254,210,157,219,0,117,239,3,255,4,227,5,247, 11,4,3,188,111,11,105,195,2,0,14,1,21,219,192,0,183,191,113,241,1,12,17,248,0,48,7,19,1,254,212,0,239,246, 0,23,0,250,165,194,194,17,3,253,0,24,6,0,141,167,221,24,212,2,235,243,0,0,205,1,251,133,204,28,4,6,1,10, 141,21,74,12,236,254,228,19,1,0,214,1,186,13,13,6,13,16,27,209,6,216,11,207,251,59,32,9,155,23,19,235,143, 116,6,213,6,75,159,23,6,0,228,4,10,245,249,1,7,44,234,4,102,174,0,19,239,103,16,15,18,8,214,22,4,47,244, 255,8,0,251,173,1,212,252,250,251,252,6,0,29,29,222,233,246,5,149,0,182,180,13,151,0,203,183,0,35,149,0, 235,246,254,78,9,17,203,73,11,195,0,3,5,44,0,0,237,5,106,6,130,16,214,20,168,247,168,4,207,11,5,1,232,251, 129,210,116,231,217,223,214,27,45,38,4,177,186,249,7,215,172,16,214,27,249,230,236,2,34,216,217,0,175,30, 243,225,244,182,20,212,2,226,21,255,20,0,2,13,62,13,191,14,76,64,20,121,4,118,0,216,1,147,0,2,210,1,215, 95,210,236,225,184,46,0,248,24,11,1,9,141,250,243,9,221,233,160,11,147,2,55,8,23,12,253,9,0,54,0,231,6,3, 141,8,2,246,9,180,5,11,8,227,8,43,110,242,1,130,5,97,36,10,6,219,86,133,11,108,6,1,5,244,67,19,28,0,174, 154,16,127,149,252,188,196,196,228,244,9,249,0,0,0,37,170,32,250,0,73,255,23,3,224,234,38,195,198,0,255,87, 33,221,174,31,3,0,189,228,6,153,14,144,14,108,197,0,9,206,245,254,3,16,253,178,248,0,95,125,8,0,3,168,21, 23,168,19,50,240,244,185,0,1,144,10,168,31,82,1,13 }; static const CImg<Tuchar> colormap(pal,1,256,1,3,false); return colormap; } //! Return colormap \e "hot", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_hot.jpg **/ static const CImg<Tuchar>& hot_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { colormap.assign(1,4,1,3,0); colormap[1] = colormap[2] = colormap[3] = colormap[6] = colormap[7] = colormap[11] = 255; colormap.resize(1,256,1,3,3); } return colormap; } //! Return colormap \e "cool", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cool.jpg **/ static const CImg<Tuchar>& cool_LUT256() { static CImg<Tuchar> colormap; if (!colormap) colormap.assign(1,2,1,3).fill(0,255,255,0,255,255).resize(1,256,1,3,3); return colormap; } //! Return colormap \e "jet", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_jet.jpg **/ static const CImg<Tuchar>& jet_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { colormap.assign(1,4,1,3,0); colormap[2] = colormap[3] = colormap[5] = colormap[6] = colormap[8] = colormap[9] = 255; colormap.resize(1,256,1,3,3); } return colormap; } //! Return colormap \e "flag", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_flag.jpg **/ static const CImg<Tuchar>& flag_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { colormap.assign(1,4,1,3,0); colormap[0] = colormap[1] = colormap[5] = colormap[9] = colormap[10] = 255; colormap.resize(1,256,1,3,0,2); } return colormap; } //! Return colormap \e "cube", containing 256 colors entries in RGB. /** \return The following \c 256x1x1x3 colormap is returned: \image html ref_colormap_cube.jpg **/ static const CImg<Tuchar>& cube_LUT256() { static CImg<Tuchar> colormap; if (!colormap) { colormap.assign(1,8,1,3,0); colormap[1] = colormap[3] = colormap[5] = colormap[7] = colormap[10] = colormap[11] = colormap[12] = colormap[13] = colormap[20] = colormap[21] = colormap[22] = colormap[23] = 255; colormap.resize(1,256,1,3,3); } return colormap; } //! Convert pixel values from sRGB to RGB color spaces. CImg<T>& sRGBtoRGB() { cimg_for(*this,ptr,T) { const Tfloat sval = (Tfloat)*ptr, nsval = (sval<0?0:sval>255?255:sval)/255, val = (Tfloat)(nsval<=0.04045f?nsval/12.92f:std::pow((nsval+0.055f)/(1.055f),2.4f)); *ptr = (T)(val*255); } return *this; } //! Convert pixel values from sRGB to RGB color spaces \newinstance. CImg<Tfloat> get_sRGBtoRGB() const { return CImg<Tfloat>(*this,false).sRGBtoRGB(); } //! Convert pixel values from RGB to sRGB color spaces. CImg<T>& RGBtosRGB() { cimg_for(*this,ptr,T) { const Tfloat val = (Tfloat)*ptr, nval = (val<0?0:val>255?255:val)/255, sval = (Tfloat)(nval<=0.0031308f?nval*12.92f:1.055f*std::pow(nval,0.416667f)-0.055f); *ptr = (T)(sval*255); } return *this; } //! Convert pixel values from RGB to sRGB color spaces \newinstance. CImg<Tfloat> get_RGBtosRGB() const { return CImg<Tfloat>(*this,false).RGBtosRGB(); } //! Convert pixel values from RGB to HSV color spaces. CImg<T>& RGBtoHSV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1, G = (Tfloat)*p2, B = (Tfloat)*p3, nR = (R<0?0:(R>255?255:R))/255, nG = (G<0?0:(G>255?255:G))/255, nB = (B<0?0:(B>255?255:B))/255, m = cimg::min(nR,nG,nB), M = cimg::max(nR,nG,nB); Tfloat H = 0, S = 0; if (M!=m) { const Tfloat f = (nR==m)?(nG-nB):((nG==m)?(nB-nR):(nR-nG)), i = (Tfloat)((nR==m)?3:((nG==m)?5:1)); H = (i-f/(M-m)); if (H>=6) H-=6; H*=60; S = (M-m)/M; } *(p1++) = (T)H; *(p2++) = (T)S; *(p3++) = (T)M; } return *this; } //! Convert pixel values from RGB to HSV color spaces \newinstance. CImg<Tfloat> get_RGBtoHSV() const { return CImg<Tfloat>(*this,false).RGBtoHSV(); } //! Convert pixel values from HSV to RGB color spaces. CImg<T>& HSVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSVtoRGB(): Instance is not a HSV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { Tfloat H = (Tfloat)*p1, S = (Tfloat)*p2, V = (Tfloat)*p3, R = 0, G = 0, B = 0; if (H==0 && S==0) R = G = B = V; else { H/=60; const int i = (int)std::floor(H); const Tfloat f = (i&1)?(H - i):(1 - H + i), m = V*(1 - S), n = V*(1 - S*f); switch (i) { case 6 : case 0 : R = V; G = n; B = m; break; case 1 : R = n; G = V; B = m; break; case 2 : R = m; G = V; B = n; break; case 3 : R = m; G = n; B = V; break; case 4 : R = n; G = m; B = V; break; case 5 : R = V; G = m; B = n; break; } } R*=255; G*=255; B*=255; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from HSV to RGB color spaces \newinstance. CImg<Tuchar> get_HSVtoRGB() const { return CImg<Tuchar>(*this,false).HSVtoRGB(); } //! Convert pixel values from RGB to HSL color spaces. CImg<T>& RGBtoHSL() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSL(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1, G = (Tfloat)*p2, B = (Tfloat)*p3, nR = (R<0?0:(R>255?255:R))/255, nG = (G<0?0:(G>255?255:G))/255, nB = (B<0?0:(B>255?255:B))/255, m = cimg::min(nR,nG,nB), M = cimg::max(nR,nG,nB), L = (m + M)/2; Tfloat H = 0, S = 0; if (M==m) H = S = 0; else { const Tfloat f = (nR==m)?(nG-nB):((nG==m)?(nB-nR):(nR-nG)), i = (nR==m)?3.0f:((nG==m)?5.0f:1.0f); H = (i-f/(M-m)); if (H>=6) H-=6; H*=60; S = (2*L<=1)?((M-m)/(M+m)):((M-m)/(2-M-m)); } *(p1++) = (T)H; *(p2++) = (T)S; *(p3++) = (T)L; } return *this; } //! Convert pixel values from RGB to HSL color spaces \newinstance. CImg<Tfloat> get_RGBtoHSL() const { return CImg< Tfloat>(*this,false).RGBtoHSL(); } //! Convert pixel values from HSL to RGB color spaces. CImg<T>& HSLtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSLtoRGB(): Instance is not a HSL image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat H = (Tfloat)*p1, S = (Tfloat)*p2, L = (Tfloat)*p3, q = 2*L<1?L*(1+S):(L+S-L*S), p = 2*L-q, h = H/360, tr = h + 1.0f/3, tg = h, tb = h - 1.0f/3, ntr = tr<0?tr+1:(tr>1?tr-1:tr), ntg = tg<0?tg+1:(tg>1?tg-1:tg), ntb = tb<0?tb+1:(tb>1?tb-1:tb), R = 255*(6*ntr<1?p+(q-p)*6*ntr:(2*ntr<1?q:(3*ntr<2?p+(q-p)*6*(2.0f/3-ntr):p))), G = 255*(6*ntg<1?p+(q-p)*6*ntg:(2*ntg<1?q:(3*ntg<2?p+(q-p)*6*(2.0f/3-ntg):p))), B = 255*(6*ntb<1?p+(q-p)*6*ntb:(2*ntb<1?q:(3*ntb<2?p+(q-p)*6*(2.0f/3-ntb):p))); *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from HSL to RGB color spaces \newinstance. CImg<Tuchar> get_HSLtoRGB() const { return CImg<Tuchar>(*this,false).HSLtoRGB(); } //! Convert pixel values from RGB to HSI color spaces. CImg<T>& RGBtoHSI() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoHSI(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1, G = (Tfloat)*p2, B = (Tfloat)*p3, nR = (R<0?0:(R>255?255:R))/255, nG = (G<0?0:(G>255?255:G))/255, nB = (B<0?0:(B>255?255:B))/255, m = cimg::min(nR,nG,nB), theta = (Tfloat)(std::acos(0.5f*((nR-nG)+(nR-nB))/std::sqrt(std::pow(nR-nG,2)+(nR-nB)*(nG-nB)))*180/cimg::PI), sum = nR + nG + nB; Tfloat H = 0, S = 0, I = 0; if (theta>0) H = (nB<=nG)?theta:360-theta; if (sum>0) S = 1 - 3/sum*m; I = sum/3; *(p1++) = (T)H; *(p2++) = (T)S; *(p3++) = (T)I; } return *this; } //! Convert pixel values from RGB to HSI color spaces \newinstance. CImg<Tfloat> get_RGBtoHSI() const { return CImg<Tfloat>(*this,false).RGBtoHSI(); } //! Convert pixel values from HSI to RGB color spaces. CImg<T>& HSItoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "HSItoRGB(): Instance is not a HSI image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { Tfloat H = (Tfloat)*p1, S = (Tfloat)*p2, I = (Tfloat)*p3, a = I*(1-S), R = 0, G = 0, B = 0; if (H<120) { B = a; R = (Tfloat)(I*(1+S*std::cos(H*cimg::PI/180)/std::cos((60-H)*cimg::PI/180))); G = 3*I-(R+B); } else if (H<240) { H-=120; R = a; G = (Tfloat)(I*(1+S*std::cos(H*cimg::PI/180)/std::cos((60-H)*cimg::PI/180))); B = 3*I-(R+G); } else { H-=240; G = a; B = (Tfloat)(I*(1+S*std::cos(H*cimg::PI/180)/std::cos((60-H)*cimg::PI/180))); R = 3*I-(G+B); } R*=255; G*=255; B*=255; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from HSI to RGB color spaces \newinstance. CImg<Tfloat> get_HSItoRGB() const { return CImg< Tuchar>(*this,false).HSItoRGB(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& RGBtoYCbCr() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYCbCr(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1, G = (Tfloat)*p2, B = (Tfloat)*p3, Y = (66*R + 129*G + 25*B + 128)/256 + 16, Cb = (-38*R - 74*G + 112*B + 128)/256 + 128, Cr = (112*R - 94*G - 18*B + 128)/256 + 128; *(p1++) = (T)(Y<0?0:(Y>255?255:Y)); *(p2++) = (T)(Cb<0?0:(Cb>255?255:Cb)); *(p3++) = (T)(Cr<0?0:(Cr>255?255:Cr)); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_RGBtoYCbCr() const { return CImg<Tuchar>(*this,false).RGBtoYCbCr(); } //! Convert pixel values from RGB to YCbCr color spaces. CImg<T>& YCbCrtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YCbCrtoRGB(): Instance is not a YCbCr image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat Y = (Tfloat)*p1 - 16, Cb = (Tfloat)*p2 - 128, Cr = (Tfloat)*p3 - 128, R = (298*Y + 409*Cr + 128)/256, G = (298*Y - 100*Cb - 208*Cr + 128)/256, B = (298*Y + 516*Cb + 128)/256; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from RGB to YCbCr color spaces \newinstance. CImg<Tuchar> get_YCbCrtoRGB() const { return CImg<Tuchar>(*this,false).YCbCrtoRGB(); } //! Convert pixel values from RGB to YUV color spaces. CImg<T>& RGBtoYUV() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoYUV(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1/255, G = (Tfloat)*p2/255, B = (Tfloat)*p3/255, Y = 0.299f*R + 0.587f*G + 0.114f*B; *(p1++) = (T)Y; *(p2++) = (T)(0.492f*(B-Y)); *(p3++) = (T)(0.877*(R-Y)); } return *this; } //! Convert pixel values from RGB to YUV color spaces \newinstance. CImg<Tfloat> get_RGBtoYUV() const { return CImg<Tfloat>(*this,false).RGBtoYUV(); } //! Convert pixel values from YUV to RGB color spaces. CImg<T>& YUVtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "YUVtoRGB(): Instance is not a YUV image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat Y = (Tfloat)*p1, U = (Tfloat)*p2, V = (Tfloat)*p3, R = (Y + 1.140f*V)*255, G = (Y - 0.395f*U - 0.581f*V)*255, B = (Y + 2.032f*U)*255; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from YUV to RGB color spaces \newinstance. CImg<Tuchar> get_YUVtoRGB() const { return CImg< Tuchar>(*this,false).YUVtoRGB(); } //! Convert pixel values from RGB to CMY color spaces. CImg<T>& RGBtoCMY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoCMY(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1, G = (Tfloat)*p2, B = (Tfloat)*p3, C = 255 - R, M = 255 - G, Y = 255 - B; *(p1++) = (T)(C<0?0:(C>255?255:C)); *(p2++) = (T)(M<0?0:(M>255?255:M)); *(p3++) = (T)(Y<0?0:(Y>255?255:Y)); } return *this; } //! Convert pixel values from RGB to CMY color spaces \newinstance. CImg<Tuchar> get_RGBtoCMY() const { return CImg<Tfloat>(*this,false).RGBtoCMY(); } //! Convert pixel values from CMY to RGB color spaces. CImg<T>& CMYtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoRGB(): Instance is not a CMY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat C = (Tfloat)*p1, M = (Tfloat)*p2, Y = (Tfloat)*p3, R = 255 - C, G = 255 - M, B = 255 - Y; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from CMY to RGB color spaces \newinstance. CImg<Tuchar> get_CMYtoRGB() const { return CImg<Tuchar>(*this,false).CMYtoRGB(); } //! Convert pixel values from CMY to CMYK color spaces. CImg<T>& CMYtoCMYK() { return get_CMYtoCMYK().move_to(*this); } //! Convert pixel values from CMY to CMYK color spaces \newinstance. CImg<Tuchar> get_CMYtoCMYK() const { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "CMYtoCMYK(): Instance is not a CMY image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,4); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2), *pd4 = res.data(0,0,0,3); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { Tfloat C = (Tfloat)*(ps1++), M = (Tfloat)*(ps2++), Y = (Tfloat)*(ps3++), K = cimg::min(C,M,Y); if (K>=255) C = M = Y = 0; else { const Tfloat K1 = 255 - K; C = 255*(C - K)/K1; M = 255*(M - K)/K1; Y = 255*(Y - K)/K1; } *(pd1++) = (Tfloat)(C<0?0:(C>255?255:C)); *(pd2++) = (Tfloat)(M<0?0:(M>255?255:M)); *(pd3++) = (Tfloat)(Y<0?0:(Y>255?255:Y)); *(pd4++) = (Tfloat)(K<0?0:(K>255?255:K)); } return res; } //! Convert pixel values from CMYK to CMY color spaces. CImg<T>& CMYKtoCMY() { return get_CMYKtoCMY().move_to(*this); } //! Convert pixel values from CMYK to CMY color spaces \newinstance. CImg<Tfloat> get_CMYKtoCMY() const { if (_spectrum!=4) throw CImgInstanceException(_cimg_instance "CMYKtoCMY(): Instance is not a CMYK image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,3); const T *ps1 = data(0,0,0,0), *ps2 = data(0,0,0,1), *ps3 = data(0,0,0,2), *ps4 = data(0,0,0,3); Tfloat *pd1 = res.data(0,0,0,0), *pd2 = res.data(0,0,0,1), *pd3 = res.data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat C = (Tfloat)*(ps1++), M = (Tfloat)*(ps2++), Y = (Tfloat)*(ps3++), K = (Tfloat)*(ps4++), K1 = 1 - K/255, nC = C*K1 + K, nM = M*K1 + K, nY = Y*K1 + K; *(pd1++) = (Tfloat)(nC<0?0:(nC>255?255:nC)); *(pd2++) = (Tfloat)(nM<0?0:(nM>255?255:nM)); *(pd3++) = (Tfloat)(nY<0?0:(nY>255?255:nY)); } return res; } //! Convert pixel values from RGB to XYZ_709 color spaces. /** \note Uses the standard D65 white point. **/ CImg<T>& RGBtoXYZ() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoXYZ(): Instance is not a RGB image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat R = (Tfloat)*p1/255, G = (Tfloat)*p2/255, B = (Tfloat)*p3/255; *(p1++) = (T)(0.412453f*R + 0.357580f*G + 0.180423f*B); *(p2++) = (T)(0.212671f*R + 0.715160f*G + 0.072169f*B); *(p3++) = (T)(0.019334f*R + 0.119193f*G + 0.950227f*B); } return *this; } //! Convert pixel values from RGB to XYZ_709 color spaces \newinstance. CImg<Tfloat> get_RGBtoXYZ() const { return CImg<Tfloat>(*this,false).RGBtoXYZ(); } //! Convert pixel values from XYZ_709 to RGB color spaces. CImg<T>& XYZtoRGB() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoRGB(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat X = (Tfloat)*p1*255, Y = (Tfloat)*p2*255, Z = (Tfloat)*p3*255, R = 3.240479f*X - 1.537150f*Y - 0.498535f*Z, G = -0.969256f*X + 1.875992f*Y + 0.041556f*Z, B = 0.055648f*X - 0.204043f*Y + 1.057311f*Z; *(p1++) = (T)(R<0?0:(R>255?255:R)); *(p2++) = (T)(G<0?0:(G>255?255:G)); *(p3++) = (T)(B<0?0:(B>255?255:B)); } return *this; } //! Convert pixel values from XYZ_709 to RGB color spaces \newinstance. CImg<Tuchar> get_XYZtoRGB() const { return CImg<Tuchar>(*this,false).XYZtoRGB(); } //! Convert pixel values from XYZ_709 to Lab color spaces. CImg<T>& XYZtoLab() { #define _cimg_Labf(x) ((x)>=0.008856f?(std::pow(x,(Tfloat)1/3)):(7.787f*(x)+16.0f/116)) if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoLab(): Instance is not a XYZ image.", cimg_instance); const Tfloat Xn = (Tfloat)(0.412453f + 0.357580f + 0.180423f), Yn = (Tfloat)(0.212671f + 0.715160f + 0.072169f), Zn = (Tfloat)(0.019334f + 0.119193f + 0.950227f); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat X = (Tfloat)*p1, Y = (Tfloat)*p2, Z = (Tfloat)*p3, XXn = X/Xn, YYn = Y/Yn, ZZn = Z/Zn, fX = (Tfloat)_cimg_Labf(XXn), fY = (Tfloat)_cimg_Labf(YYn), fZ = (Tfloat)_cimg_Labf(ZZn); *(p1++) = (T)cimg::max(0.0f,116*fY - 16); *(p2++) = (T)(500*(fX - fY)); *(p3++) = (T)(200*(fY - fZ)); } return *this; } //! Convert pixel values from XYZ_709 to Lab color spaces \newinstance. CImg<Tfloat> get_XYZtoLab() const { return CImg<Tfloat>(*this,false).XYZtoLab(); } //! Convert pixel values from Lab to XYZ_709 color spaces. CImg<T>& LabtoXYZ() { #define _cimg_Labfi(x) ((x)>=0.206893f?((x)*(x)*(x)):(((x)-16.0f/116)/7.787f)) if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "LabtoXYZ(): Instance is not a Lab image.", cimg_instance); const Tfloat Xn = (Tfloat)(0.412453f + 0.357580f + 0.180423f), Yn = (Tfloat)(0.212671f + 0.715160f + 0.072169f), Zn = (Tfloat)(0.019334f + 0.119193f + 0.950227f); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat L = (Tfloat)*p1, a = (Tfloat)*p2, b = (Tfloat)*p3, cY = (L + 16)/116, Y = (Tfloat)(Yn*_cimg_Labfi(cY)), pY = (Tfloat)std::pow(Y/Yn,(Tfloat)1/3), cX = a/500 + pY, X = Xn*cX*cX*cX, cZ = pY - b/200, Z = Zn*cZ*cZ*cZ; *(p1++) = (T)(X); *(p2++) = (T)(Y); *(p3++) = (T)(Z); } return *this; } //! Convert pixel values from Lab to XYZ_709 color spaces \newinstance. CImg<Tfloat> get_LabtoXYZ() const { return CImg<Tfloat>(*this,false).LabtoXYZ(); } //! Convert pixel values from XYZ_709 to xyY color spaces. CImg<T>& XYZtoxyY() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "XYZtoxyY(): Instance is not a XYZ image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat X = (Tfloat)*p1, Y = (Tfloat)*p2, Z = (Tfloat)*p3, sum = (X+Y+Z), nsum = sum>0?sum:1; *(p1++) = (T)(X/nsum); *(p2++) = (T)(Y/nsum); *(p3++) = (T)Y; } return *this; } //! Convert pixel values from XYZ_709 to xyY color spaces \newinstance. CImg<Tfloat> get_XYZtoxyY() const { return CImg<Tfloat>(*this,false).XYZtoxyY(); } //! Convert pixel values from xyY pixels to XYZ_709 color spaces. CImg<T>& xyYtoXYZ() { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "xyYtoXYZ(): Instance is not a xyY image.", cimg_instance); T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2); for (unsigned long N = (unsigned long)_width*_height*_depth; N; --N) { const Tfloat px = (Tfloat)*p1, py = (Tfloat)*p2, Y = (Tfloat)*p3, ny = py>0?py:1; *(p1++) = (T)(px*Y/ny); *(p2++) = (T)Y; *(p3++) = (T)((1-px-py)*Y/ny); } return *this; } //! Convert pixel values from xyY pixels to XYZ_709 color spaces \newinstance. CImg<Tfloat> get_xyYtoXYZ() const { return CImg<Tfloat>(*this,false).xyYtoXYZ(); } //! Convert pixel values from RGB to Lab color spaces. CImg<T>& RGBtoLab() { return RGBtoXYZ().XYZtoLab(); } //! Convert pixel values from RGB to Lab color spaces \newinstance. CImg<Tfloat> get_RGBtoLab() const { return CImg<Tfloat>(*this,false).RGBtoLab(); } //! Convert pixel values from Lab to RGB color spaces. CImg<T>& LabtoRGB() { return LabtoXYZ().XYZtoRGB(); } //! Convert pixel values from Lab to RGB color spaces \newinstance. CImg<Tuchar> get_LabtoRGB() const { return CImg<Tuchar>(*this,false).LabtoRGB(); } //! Convert pixel values from RGB to xyY color spaces. CImg<T>& RGBtoxyY() { return RGBtoXYZ().XYZtoxyY(); } //! Convert pixel values from RGB to xyY color spaces \newinstance. CImg<Tfloat> get_RGBtoxyY() const { return CImg<Tfloat>(*this,false).RGBtoxyY(); } //! Convert pixel values from xyY to RGB color spaces. CImg<T>& xyYtoRGB() { return xyYtoXYZ().XYZtoRGB(); } //! Convert pixel values from xyY to RGB color spaces \newinstance. CImg<Tuchar> get_xyYtoRGB() const { return CImg<Tuchar>(*this,false).xyYtoRGB(); } //! Convert pixel values from RGB to CMYK color spaces. CImg<T>& RGBtoCMYK() { return RGBtoCMY().CMYtoCMYK(); } //! Convert pixel values from RGB to CMYK color spaces \newinstance. CImg<Tfloat> get_RGBtoCMYK() const { return CImg<Tfloat>(*this,false).RGBtoCMYK(); } //! Convert pixel values from CMYK to RGB color spaces. CImg<T>& CMYKtoRGB() { return CMYKtoCMY().CMYtoRGB(); } //! Convert pixel values from CMYK to RGB color spaces \newinstance. CImg<Tuchar> get_CMYKtoRGB() const { return CImg<Tuchar>(*this,false).CMYKtoRGB(); } //! Convert RGB color image to a Bayer-coded scalar image. /** \note First (upper-left) pixel if the red component of the pixel color. **/ CImg<T>& RGBtoBayer() { return get_RGBtoBayer().move_to(*this); } //! Convert RGB color image to a Bayer-coded scalar image \newinstance. CImg<T> get_RGBtoBayer() const { if (_spectrum!=3) throw CImgInstanceException(_cimg_instance "RGBtoBayer(): Instance is not a RGB image.", cimg_instance); CImg<T> res(_width,_height,_depth,1); const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); T *ptrd = res._data; cimg_forXYZ(*this,x,y,z) { if (y%2) { if (x%2) *(ptrd++) = *ptr_b; else *(ptrd++) = *ptr_g; } else { if (x%2) *(ptrd++) = *ptr_g; else *(ptrd++) = *ptr_r; } ++ptr_r; ++ptr_g; ++ptr_b; } return res; } //! Convert Bayer-coded scalar image to a RGB color image. CImg<T>& BayertoRGB(const unsigned int interpolation_type=3) { return get_BayertoRGB(interpolation_type).move_to(*this); } //! Convert Bayer-coded scalar image to a RGB color image \newinstance. CImg<Tuchar> get_BayertoRGB(const unsigned int interpolation_type=3) const { if (_spectrum!=1) throw CImgInstanceException(_cimg_instance "BayertoRGB(): Instance is not a Bayer image.", cimg_instance); CImg<Tuchar> res(_width,_height,_depth,3); CImg_3x3(I,T); Tuchar *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2); switch (interpolation_type) { case 3 : { // Edge-directed CImg_3x3(R,T); CImg_3x3(G,T); CImg_3x3(B,T); cimg_forXYZ(*this,x,y,z) { const int _p1x = x?x-1:1, _p1y = y?y-1:1, _n1x = x<width()-1?x+1:x-1, _n1y = y<height()-1?y+1:y-1; cimg_get3x3(*this,x,y,z,0,I,T); if (y%2) { if (x%2) { const Tfloat alpha = cimg::sqr((Tfloat)Inc - Ipc), beta = cimg::sqr((Tfloat)Icn - Icp), cx = 1/(1+alpha), cy = 1/(1+beta); *ptr_g = (Tuchar)((cx*(Inc+Ipc) + cy*(Icn+Icp))/(2*(cx+cy))); } else *ptr_g = (Tuchar)Icc; } else { if (x%2) *ptr_g = (Tuchar)Icc; else { const Tfloat alpha = cimg::sqr((Tfloat)Inc - Ipc), beta = cimg::sqr((Tfloat)Icn - Icp), cx = 1/(1+alpha), cy = 1/(1+beta); *ptr_g = (Tuchar)((cx*(Inc+Ipc) + cy*(Icn+Icp))/(2*(cx+cy))); } } ++ptr_g; } cimg_forXYZ(*this,x,y,z) { const int _p1x = x?x-1:1, _p1y = y?y-1:1, _n1x = x<width()-1?x+1:x-1, _n1y = y<height()-1?y+1:y-1; cimg_get3x3(*this,x,y,z,0,I,T); cimg_get3x3(res,x,y,z,1,G,T); if (y%2) { if (x%2) *ptr_b = (Tuchar)Icc; else { *ptr_r = (Tuchar)((Icn+Icp)/2); *ptr_b = (Tuchar)((Inc+Ipc)/2); } } else { if (x%2) { *ptr_r = (Tuchar)((Inc+Ipc)/2); *ptr_b = (Tuchar)((Icn+Icp)/2); } else *ptr_r = (Tuchar)Icc; } ++ptr_r; ++ptr_b; } ptr_r = res.data(0,0,0,0); ptr_g = res.data(0,0,0,1); ptr_b = res.data(0,0,0,2); cimg_forXYZ(*this,x,y,z) { const int _p1x = x?x-1:1, _p1y = y?y-1:1, _n1x = x<width()-1?x+1:x-1, _n1y = y<height()-1?y+1:y-1; cimg_get3x3(res,x,y,z,0,R,T); cimg_get3x3(res,x,y,z,1,G,T); cimg_get3x3(res,x,y,z,2,B,T); if (y%2) { if (x%2) { const float alpha = (float)cimg::sqr(Rnc-Rpc), beta = (float)cimg::sqr(Rcn-Rcp), cx = 1/(1+alpha), cy = 1/(1+beta); *ptr_r = (Tuchar)((cx*(Rnc+Rpc) + cy*(Rcn+Rcp))/(2*(cx+cy))); } } else { if (!(x%2)) { const float alpha = (float)cimg::sqr(Bnc-Bpc), beta = (float)cimg::sqr(Bcn-Bcp), cx = 1/(1+alpha), cy = 1/(1+beta); *ptr_b = (Tuchar)((cx*(Bnc+Bpc) + cy*(Bcn+Bcp))/(2*(cx+cy))); } } ++ptr_r; ++ptr_g; ++ptr_b; } } break; case 2 : { // Linear interpolation cimg_forXYZ(*this,x,y,z) { const int _p1x = x?x-1:1, _p1y = y?y-1:1, _n1x = x<width()-1?x+1:x-1, _n1y = y<height()-1?y+1:y-1; cimg_get3x3(*this,x,y,z,0,I,T); if (y%2) { if (x%2) { *ptr_r = (Tuchar)((Ipp+Inn+Ipn+Inp)/4); *ptr_g = (Tuchar)((Inc+Ipc+Icn+Icp)/4); *ptr_b = (Tuchar)Icc; } else { *ptr_r = (Tuchar)((Icp+Icn)/2); *ptr_g = (Tuchar)Icc; *ptr_b = (Tuchar)((Inc+Ipc)/2); } } else { if (x%2) { *ptr_r = (Tuchar)((Ipc+Inc)/2); *ptr_g = (Tuchar)Icc; *ptr_b = (Tuchar)((Icn+Icp)/2); } else { *ptr_r = (Tuchar)Icc; *ptr_g = (Tuchar)((Inc+Ipc+Icn+Icp)/4); *ptr_b = (Tuchar)((Ipp+Inn+Ipn+Inp)/4); } } ++ptr_r; ++ptr_g; ++ptr_b; } } break; case 1 : { // Nearest neighbor interpolation cimg_forXYZ(*this,x,y,z) { const int _p1x = x?x-1:1, _p1y = y?y-1:1, _n1x = x<width()-1?x+1:x-1, _n1y = y<height()-1?y+1:y-1; cimg_get3x3(*this,x,y,z,0,I,T); if (y%2) { if (x%2) { *ptr_r = (Tuchar)cimg::min(Ipp,Inn,Ipn,Inp); *ptr_g = (Tuchar)cimg::min(Inc,Ipc,Icn,Icp); *ptr_b = (Tuchar)Icc; } else { *ptr_r = (Tuchar)cimg::min(Icn,Icp); *ptr_g = (Tuchar)Icc; *ptr_b = (Tuchar)cimg::min(Inc,Ipc); } } else { if (x%2) { *ptr_r = (Tuchar)cimg::min(Inc,Ipc); *ptr_g = (Tuchar)Icc; *ptr_b = (Tuchar)cimg::min(Icn,Icp); } else { *ptr_r = (Tuchar)Icc; *ptr_g = (Tuchar)cimg::min(Inc,Ipc,Icn,Icp); *ptr_b = (Tuchar)cimg::min(Ipp,Inn,Ipn,Inp); } } ++ptr_r; ++ptr_g; ++ptr_b; } } break; default : { // 0-filling interpolation const T *ptrs = _data; res.fill(0); cimg_forXYZ(*this,x,y,z) { const T val = *(ptrs++); if (y%2) { if (x%2) *ptr_b = val; else *ptr_g = val; } else { if (x%2) *ptr_g = val; else *ptr_r = val; } ++ptr_r; ++ptr_g; ++ptr_b; } } } return res; } //@} //------------------------------------------ // //! \name Geometric / Spatial Manipulation //@{ //------------------------------------------ static float _cimg_lanczos(const float x) { if (x<=-2 || x>=2) return 0; const float a = (float)cimg::PI*x, b = 0.5f*a; return (float)(x?std::sin(a)*std::sin(b)/(a*b):1); } //! Resize image to new dimensions. /** \param size_x Number of columns (new size along the X-axis). \param size_y Number of rows (new size along the Y-axis). \param size_z Number of slices (new size along the Z-axis). \param size_c Number of vector-channels (new size along the C-axis). \param interpolation_type Method of interpolation: - -1 = no interpolation: raw memory resizing. - 0 = no interpolation: additional space is filled according to \p boundary_conditions. - 1 = nearest-neighbor interpolation. - 2 = moving average interpolation. - 3 = linear interpolation. - 4 = grid interpolation. - 5 = bicubic interpolation. - 6 = lanczos interpolation. \param boundary_conditions Border condition type. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). \note If pd[x,y,z,v]<0, it corresponds to a percentage of the original size (the default value is -100). **/ CImg<T>& resize(const int size_x, const int size_y=-100, const int size_z=-100, const int size_c=-100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { if (!size_x || !size_y || !size_z || !size_c) return assign(); const unsigned int _sx = (unsigned int)(size_x<0?-size_x*width()/100:size_x), _sy = (unsigned int)(size_y<0?-size_y*height()/100:size_y), _sz = (unsigned int)(size_z<0?-size_z*depth()/100:size_z), _sc = (unsigned int)(size_c<0?-size_c*spectrum()/100:size_c), sx = _sx?_sx:1, sy = _sy?_sy:1, sz = _sz?_sz:1, sc = _sc?_sc:1; if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return *this; if (is_empty()) return assign(sx,sy,sz,sc,0); if (interpolation_type==-1 && sx*sy*sz*sc==size()) { _width = sx; _height = sy; _depth = sz; _spectrum = sc; return *this; } return get_resize(sx,sy,sz,sc,interpolation_type,boundary_conditions,centering_x,centering_y,centering_z,centering_c).move_to(*this); } //! Resize image to new dimensions \newinstance. CImg<T> get_resize(const int size_x, const int size_y = -100, const int size_z = -100, const int size_c = -100, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { if (centering_x<0 || centering_x>1 || centering_y<0 || centering_y>1 || centering_z<0 || centering_z>1 || centering_c<0 || centering_c>1) throw CImgArgumentException(_cimg_instance "resize(): Specified centering arguments (%g,%g,%g,%g) are outside range [0,1].", cimg_instance, centering_x,centering_y,centering_z,centering_c); if (!size_x || !size_y || !size_z || !size_c) return CImg<T>(); const unsigned int _sx = (unsigned int)(size_x<0?-size_x*width()/100:size_x), _sy = (unsigned int)(size_y<0?-size_y*height()/100:size_y), _sz = (unsigned int)(size_z<0?-size_z*depth()/100:size_z), _sc = (unsigned int)(size_c<0?-size_c*spectrum()/100:size_c), sx = _sx?_sx:1, sy = _sy?_sy:1, sz = _sz?_sz:1, sc = _sc?_sc:1; if (sx==_width && sy==_height && sz==_depth && sc==_spectrum) return +*this; if (is_empty()) return CImg<T>(sx,sy,sz,sc,0); CImg<T> res; switch (interpolation_type) { // Raw resizing. // case -1 : std::memcpy(res.assign(sx,sy,sz,sc,0)._data,_data,sizeof(T)*cimg::min(size(),sx*sy*sz*sc)); break; // No interpolation. // case 0 : { const int xc = (int)(centering_x*((int)sx - width())), yc = (int)(centering_y*((int)sy - height())), zc = (int)(centering_z*((int)sz - depth())), cc = (int)(centering_c*((int)sc - spectrum())); switch (boundary_conditions) { case 2 : { // Cyclic borders. res.assign(sx,sy,sz,sc); const int x0 = ((int)xc%width()) - width(), y0 = ((int)yc%height()) - height(), z0 = ((int)zc%depth()) - depth(), c0 = ((int)cc%spectrum()) - spectrum(); for (int c = c0; c<(int)sc; c+=spectrum()) for (int z = z0; z<(int)sz; z+=depth()) for (int y = y0; y<(int)sy; y+=height()) for (int x = x0; x<(int)sx; x+=width()) res.draw_image(x,y,z,c,*this); } break; case 1 : { // Neumann borders. res.assign(sx,sy,sz,sc).draw_image(xc,yc,zc,cc,*this); CImg<T> sprite; if (xc>0) { // X-backward res.get_crop(xc,yc,zc,cc,xc,yc+height()-1,zc+depth()-1,cc+spectrum()-1).move_to(sprite); for (int x = xc-1; x>=0; --x) res.draw_image(x,yc,zc,cc,sprite); } if (xc+width()<(int)sx) { // X-forward res.get_crop(xc+width()-1,yc,zc,cc,xc+width()-1,yc+height()-1,zc+depth()-1,cc+spectrum()-1).move_to(sprite); for (int x = xc+width(); x<(int)sx; ++x) res.draw_image(x,yc,zc,cc,sprite); } if (yc>0) { // Y-backward res.get_crop(0,yc,zc,cc,sx-1,yc,zc+depth()-1,cc+spectrum()-1).move_to(sprite); for (int y = yc-1; y>=0; --y) res.draw_image(0,y,zc,cc,sprite); } if (yc+height()<(int)sy) { // Y-forward res.get_crop(0,yc+height()-1,zc,cc,sx-1,yc+height()-1,zc+depth()-1,cc+spectrum()-1).move_to(sprite); for (int y = yc+height(); y<(int)sy; ++y) res.draw_image(0,y,zc,cc,sprite); } if (zc>0) { // Z-backward res.get_crop(0,0,zc,cc,sx-1,sy-1,zc,cc+spectrum()-1).move_to(sprite); for (int z = zc-1; z>=0; --z) res.draw_image(0,0,z,cc,sprite); } if (zc+depth()<(int)sz) { // Z-forward res.get_crop(0,0,zc+depth()-1,cc,sx-1,sy-1,zc+depth()-1,cc+spectrum()-1).move_to(sprite); for (int z = zc+depth(); z<(int)sz; ++z) res.draw_image(0,0,z,cc,sprite); } if (cc>0) { // C-backward res.get_crop(0,0,0,cc,sx-1,sy-1,sz-1,cc).move_to(sprite); for (int c = cc-1; c>=0; --c) res.draw_image(0,0,0,c,sprite); } if (cc+spectrum()<(int)sc) { // C-forward res.get_crop(0,0,0,cc+spectrum()-1,sx-1,sy-1,sz-1,cc+spectrum()-1).move_to(sprite); for (int c = cc+spectrum(); c<(int)sc; ++c) res.draw_image(0,0,0,c,sprite); } } break; default : // Dirichlet borders. res.assign(sx,sy,sz,sc,0).draw_image(xc,yc,zc,cc,*this); } break; } break; // Nearest neighbor interpolation. // case 1 : { res.assign(sx,sy,sz,sc); CImg<ulongT> off_x(sx), off_y(sy+1), off_z(sz+1), off_c(sc+1); unsigned long *poff_x, *poff_y, *poff_z, *poff_c, curr, old; const unsigned long wh = (unsigned long)_width*_height, whd = (unsigned long)_width*_height*_depth, sxy = (unsigned long)sx*sy, sxyz = (unsigned long)sx*sy*sz; if (sx==_width) off_x.fill(1); else { poff_x = off_x._data; curr = 0; cimg_forX(res,x) { old = curr; curr = ((x+1LU)*_width/sx); *(poff_x++) = curr - old; } } if (sy==_height) off_y.fill(_width); else { poff_y = off_y._data; curr = 0; cimg_forY(res,y) { old = curr; curr = ((y+1LU)*_height/sy); *(poff_y++) = _width*(curr - old); } *poff_y = 0; } if (sz==_depth) off_z.fill(wh); else { poff_z = off_z._data; curr = 0; cimg_forZ(res,z) { old = curr; curr = ((z+1LU)*_depth/sz); *(poff_z++) = wh*(curr - old); } *poff_z = 0; } if (sc==_spectrum) off_c.fill(whd); else { poff_c = off_c._data; curr = 0; cimg_forC(res,c) { old = curr; curr = ((c+1LU)*_spectrum/sc); *(poff_c++) = whd*(curr - old); } *poff_c = 0; } T *ptrd = res._data; const T* ptrv = _data; poff_c = off_c._data; for (unsigned int c = 0; c<sc; ) { const T *ptrz = ptrv; poff_z = off_z._data; for (unsigned int z = 0; z<sz; ) { const T *ptry = ptrz; poff_y = off_y._data; for (unsigned int y = 0; y<sy; ) { const T *ptrx = ptry; poff_x = off_x._data; cimg_forX(res,x) { *(ptrd++) = *ptrx; ptrx+=*(poff_x++); } ++y; unsigned long dy = *(poff_y++); for (;!dy && y<dy; std::memcpy(ptrd,ptrd - sx,sizeof(T)*sx), ++y, ptrd+=sx, dy = *(poff_y++)) {} ptry+=dy; } ++z; unsigned long dz = *(poff_z++); for (;!dz && z<dz; std::memcpy(ptrd,ptrd-sxy,sizeof(T)*sxy), ++z, ptrd+=sxy, dz = *(poff_z++)) {} ptrz+=dz; } ++c; unsigned long dc = *(poff_c++); for (;!dc && c<dc; std::memcpy(ptrd,ptrd-sxyz,sizeof(T)*sxyz), ++c, ptrd+=sxyz, dc = *(poff_c++)) {} ptrv+=dc; } } break; // Moving average. // case 2 : { bool instance_first = true; if (sx!=_width) { CImg<Tfloat> tmp(sx,_height,_depth,_spectrum,0); for (unsigned int a = _width*sx, b = _width, c = sx, s = 0, t = 0; a; ) { const unsigned int d = cimg::min(b,c); a-=d; b-=d; c-=d; cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)+=(Tfloat)(*this)(s,y,z,v)*d; if (!b) { cimg_forYZC(tmp,y,z,v) tmp(t,y,z,v)/=_width; ++t; b = _width; } if (!c) { ++s; c = sx; } } tmp.move_to(res); instance_first = false; } if (sy!=_height) { CImg<Tfloat> tmp(sx,sy,_depth,_spectrum,0); for (unsigned int a = _height*sy, b = _height, c = sy, s = 0, t = 0; a; ) { const unsigned int d = cimg::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)(*this)(x,s,z,v)*d; else cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)+=(Tfloat)res(x,s,z,v)*d; if (!b) { cimg_forXZC(tmp,x,z,v) tmp(x,t,z,v)/=_height; ++t; b = _height; } if (!c) { ++s; c = sy; } } tmp.move_to(res); instance_first = false; } if (sz!=_depth) { CImg<Tfloat> tmp(sx,sy,sz,_spectrum,0); for (unsigned int a = _depth*sz, b = _depth, c = sz, s = 0, t = 0; a; ) { const unsigned int d = cimg::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)(*this)(x,y,s,v)*d; else cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)+=(Tfloat)res(x,y,s,v)*d; if (!b) { cimg_forXYC(tmp,x,y,v) tmp(x,y,t,v)/=_depth; ++t; b = _depth; } if (!c) { ++s; c = sz; } } tmp.move_to(res); instance_first = false; } if (sc!=_spectrum) { CImg<Tfloat> tmp(sx,sy,sz,sc,0); for (unsigned int a = _spectrum*sc, b = _spectrum, c = sc, s = 0, t = 0; a; ) { const unsigned int d = cimg::min(b,c); a-=d; b-=d; c-=d; if (instance_first) cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)(*this)(x,y,z,s)*d; else cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)+=(Tfloat)res(x,y,z,s)*d; if (!b) { cimg_forXYZ(tmp,x,y,z) tmp(x,y,z,t)/=_spectrum; ++t; b = _spectrum; } if (!c) { ++s; c = sc; } } tmp.move_to(res); instance_first = false; } } break; // Linear interpolation. // case 3 : { CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<floatT> foff(off._width); unsigned int *poff; float *pfoff, old, curr; CImg<T> resx, resy, resz, resc; T *ptrd; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { const float fx = (!boundary_conditions && sx>_width)?(sx>1?(_width-1.0f)/(sx-1):0):(float)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fx; *(poff++) = (unsigned int)curr - (unsigned int)old; } ptrd = resx._data; const T *ptrs0 = _data; cimg_forYZC(resx,y,z,c) { poff = off._data; pfoff = foff._data; const T *ptrs = ptrs0, *const ptrsmax = ptrs0 + (_width-1); cimg_forX(resx,x) { const float alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs+1):val1; *(ptrd++) = (T)((1-alpha)*val1 + alpha*val2); ptrs+=*(poff++); } ptrs0+=_width; } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { const float fy = (!boundary_conditions && sy>_height)?(sy>1?(_height-1.0f)/(sy-1):0):(float)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fy; *(poff++) = sx*((unsigned int)curr-(unsigned int)old); } cimg_forXZC(resy,x,z,c) { ptrd = resy.data(x,0,z,c); const T *ptrs = resx.data(x,0,z,c), *const ptrsmax = ptrs + (_height-1)*sx; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { const float alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs+sx):val1; *ptrd = (T)((1-alpha)*val1 + alpha*val2); ptrd+=sx; ptrs+=*(poff++); } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { const float fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth-1.0f)/(sz-1):0):(float)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fz; *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } cimg_forXYC(resz,x,y,c) { ptrd = resz.data(x,y,0,c); const T *ptrs = resy.data(x,y,0,c), *const ptrsmax = ptrs + (_depth-1)*sxy; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { const float alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs+sxy):val1; *ptrd = (T)((1-alpha)*val1 + alpha*val2); ptrd+=sxy; ptrs+=*(poff++); } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { const float fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum-1.0f)/(sc-1):0):(float)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fc; *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } cimg_forXYZ(resc,x,y,z) { ptrd = resc.data(x,y,z,0); const T *ptrs = resz.data(x,y,z,0), *const ptrsmax = ptrs + (_spectrum-1)*sxyz; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { const float alpha = *(pfoff++); const T val1 = *ptrs, val2 = ptrs<ptrsmax?*(ptrs+sxyz):val1; *ptrd = (T)((1-alpha)*val1 + alpha*val2); ptrd+=sxyz; ptrs+=*(poff++); } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Grid interpolation. // case 4 : { CImg<T> resx, resy, resz, resc; if (sx!=_width) { if (sx<_width) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { resx.assign(sx,_height,_depth,_spectrum,0); const int dx = sx*2, dy = width()*2; int err = dy + centering_x*(sx*dy/width() - dy), xs = 0; cimg_forX(resx,x) if ((err-=dy)<=0) { cimg_forYZC(resx,y,z,c) resx(x,y,z,c) = (*this)(xs,y,z,c); ++xs; err+=dx; } } } else resx.assign(*this,true); if (sy!=_height) { if (sy<_height) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { resy.assign(sx,sy,_depth,_spectrum,0); const int dx = sy*2, dy = height()*2; int err = dy + centering_y*(sy*dy/height() - dy), ys = 0; cimg_forY(resy,y) if ((err-=dy)<=0) { cimg_forXZC(resy,x,z,c) resy(x,y,z,c) = resx(x,ys,z,c); ++ys; err+=dx; } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (sz<_depth) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { resz.assign(sx,sy,sz,_spectrum,0); const int dx = sz*2, dy = depth()*2; int err = dy + centering_z*(sz*dy/depth() - dy), zs = 0; cimg_forZ(resz,z) if ((err-=dy)<=0) { cimg_forXYC(resz,x,y,c) resz(x,y,z,c) = resy(x,y,zs,c); ++zs; err+=dx; } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (sc<_spectrum) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { resc.assign(sx,sy,sz,sc,0); const int dx = sc*2, dy = spectrum()*2; int err = dy + centering_c*(sc*dy/spectrum() - dy), cs = 0; cimg_forC(resc,c) if ((err-=dy)<=0) { cimg_forXYZ(resc,x,y,z) resc(x,y,z,c) = resz(x,y,z,cs); ++cs; err+=dx; } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Bicubic interpolation. // case 5 : { const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<floatT> foff(off._width); unsigned int *poff; float *pfoff, old, curr; CImg<T> resx, resy, resz, resc; T *ptrd; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { const float fx = (!boundary_conditions && sx>_width)?(sx>1?(_width-1.0f)/(sx-1):0):(float)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fx; *(poff++) = (unsigned int)curr - (unsigned int)old; } ptrd = resx._data; const T *ptrs0 = _data; cimg_forYZC(resx,y,z,c) { poff = off._data; pfoff = foff._data; const T *ptrs = ptrs0, *const ptrsmax = ptrs0 + (_width-2); cimg_forX(resx,x) { const float t = *(pfoff++); const Tfloat val1 = (Tfloat)*ptrs, val0 = ptrs>ptrs0?(Tfloat)*(ptrs-1):val1, val2 = ptrs<=ptrsmax?(Tfloat)*(ptrs+1):val1, val3 = ptrs<ptrsmax?(Tfloat)*(ptrs+2):val2, val = val1 + 0.5f*(t*(-val0+val2) + t*t*(2*val0-5*val1+4*val2-val3) + t*t*t*(-val0+3*val1-3*val2+val3)); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } ptrs0+=_width; } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { const float fy = (!boundary_conditions && sy>_height)?(sy>1?(_height-1.0f)/(sy-1):0):(float)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fy; *(poff++) = sx*((unsigned int)curr-(unsigned int)old); } cimg_forXZC(resy,x,z,c) { ptrd = resy.data(x,0,z,c); const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmax = ptrs0 + (_height-2)*sx; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { const float t = *(pfoff++); const Tfloat val1 = (Tfloat)*ptrs, val0 = ptrs>ptrs0?(Tfloat)*(ptrs-sx):val1, val2 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sx):val1, val3 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sx):val2, val = val1 + 0.5f*(t*(-val0+val2) + t*t*(2*val0-5*val1+4*val2-val3) + t*t*t*(-val0+3*val1-3*val2+val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { const float fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth-1.0f)/(sz-1):0):(float)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fz; *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } cimg_forXYC(resz,x,y,c) { ptrd = resz.data(x,y,0,c); const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmax = ptrs0 + (_depth-2)*sxy; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { const float t = *(pfoff++); const Tfloat val1 = (Tfloat)*ptrs, val0 = ptrs>ptrs0?(Tfloat)*(ptrs-sxy):val1, val2 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sxy):val1, val3 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sxy):val2, val = val1 + 0.5f*(t*(-val0+val2) + t*t*(2*val0-5*val1+4*val2-val3) + t*t*t*(-val0+3*val1-3*val2+val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { const float fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum-1.0f)/(sc-1):0):(float)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fc; *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } cimg_forXYZ(resc,x,y,z) { ptrd = resc.data(x,y,z,0); const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmax = ptrs + (_spectrum-2)*sxyz; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { const float t = *(pfoff++); const Tfloat val1 = (Tfloat)*ptrs, val0 = ptrs>ptrs0?(Tfloat)*(ptrs-sxyz):val1, val2 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sxyz):val1, val3 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sxyz):val2, val = val1 + 0.5f*(t*(-val0+val2) + t*t*(2*val0-5*val1+4*val2-val3) + t*t*t*(-val0+3*val1-3*val2+val3)); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Lanczos interpolation. // case 6 : { const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); CImg<uintT> off(cimg::max(sx,sy,sz,sc)); CImg<floatT> foff(off._width); unsigned int *poff; float *pfoff, old, curr; CImg<T> resx, resy, resz, resc; T *ptrd; if (sx!=_width) { if (_width==1) get_resize(sx,_height,_depth,_spectrum,1).move_to(resx); else { const float fx = (!boundary_conditions && sx>_width)?(sx>1?(_width-1.0f)/(sx-1):0):(float)_width/sx; resx.assign(sx,_height,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forX(resx,x) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fx; *(poff++) = (unsigned int)curr - (unsigned int)old; } ptrd = resx._data; const T *ptrs0 = _data; cimg_forYZC(resx,y,z,c) { poff = off._data; pfoff = foff._data; const T *ptrs = ptrs0, *const ptrsmin = ptrs0 + 1, *const ptrsmax = ptrs0 + (_width-2); cimg_forX(resx,x) { const float t = *(pfoff++), w0 = _cimg_lanczos(t+2), w1 = _cimg_lanczos(t+1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t-1), w4 = _cimg_lanczos(t-2); const Tfloat val2 = (Tfloat)*ptrs, val1 = ptrs>=ptrsmin?(Tfloat)*(ptrs-1):val2, val0 = ptrs>ptrsmin?(Tfloat)*(ptrs-2):val1, val3 = ptrs<=ptrsmax?(Tfloat)*(ptrs+1):val2, val4 = ptrs<ptrsmax?(Tfloat)*(ptrs+2):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *(ptrd++) = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrs+=*(poff++); } ptrs0+=_width; } } } else resx.assign(*this,true); if (sy!=_height) { if (_height==1) resx.get_resize(sx,sy,_depth,_spectrum,1).move_to(resy); else { const float fy = (!boundary_conditions && sy>_height)?(sy>1?(_height-1.0f)/(sy-1):0):(float)_height/sy; resy.assign(sx,sy,_depth,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fy; *(poff++) = sx*((unsigned int)curr-(unsigned int)old); } cimg_forXZC(resy,x,z,c) { ptrd = resy.data(x,0,z,c); const T *const ptrs0 = resx.data(x,0,z,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sx, *const ptrsmax = ptrs0 + (_height-2)*sx; poff = off._data; pfoff = foff._data; cimg_forY(resy,y) { const float t = *(pfoff++), w0 = _cimg_lanczos(t+2), w1 = _cimg_lanczos(t+1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t-1), w4 = _cimg_lanczos(t-2); const Tfloat val2 = (Tfloat)*ptrs, val1 = ptrs>=ptrsmin?(Tfloat)*(ptrs-sx):val2, val0 = ptrs>ptrsmin?(Tfloat)*(ptrs-2*sx):val1, val3 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sx):val2, val4 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sx):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sx; ptrs+=*(poff++); } } } resx.assign(); } else resy.assign(resx,true); if (sz!=_depth) { if (_depth==1) resy.get_resize(sx,sy,sz,_spectrum,1).move_to(resz); else { const float fz = (!boundary_conditions && sz>_depth)?(sz>1?(_depth-1.0f)/(sz-1):0):(float)_depth/sz; const unsigned int sxy = sx*sy; resz.assign(sx,sy,sz,_spectrum); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fz; *(poff++) = sxy*((unsigned int)curr - (unsigned int)old); } cimg_forXYC(resz,x,y,c) { ptrd = resz.data(x,y,0,c); const T *const ptrs0 = resy.data(x,y,0,c), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxy, *const ptrsmax = ptrs0 + (_depth-2)*sxy; poff = off._data; pfoff = foff._data; cimg_forZ(resz,z) { const float t = *(pfoff++), w0 = _cimg_lanczos(t+2), w1 = _cimg_lanczos(t+1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t-1), w4 = _cimg_lanczos(t-2); const Tfloat val2 = (Tfloat)*ptrs, val1 = ptrs>=ptrsmin?(Tfloat)*(ptrs-sxy):val2, val0 = ptrs>ptrsmin?(Tfloat)*(ptrs-2*sxy):val1, val3 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sxy):val2, val4 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sxy):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxy; ptrs+=*(poff++); } } } resy.assign(); } else resz.assign(resy,true); if (sc!=_spectrum) { if (_spectrum==1) resz.get_resize(sx,sy,sz,sc,1).move_to(resc); else { const float fc = (!boundary_conditions && sc>_spectrum)?(sc>1?(_spectrum-1.0f)/(sc-1):0):(float)_spectrum/sc; const unsigned int sxyz = sx*sy*sz; resc.assign(sx,sy,sz,sc); curr = old = 0; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { *(pfoff++) = curr - (unsigned int)curr; old = curr; curr+=fc; *(poff++) = sxyz*((unsigned int)curr - (unsigned int)old); } cimg_forXYZ(resc,x,y,z) { ptrd = resc.data(x,y,z,0); const T *const ptrs0 = resz.data(x,y,z,0), *ptrs = ptrs0, *const ptrsmin = ptrs0 + sxyz, *const ptrsmax = ptrs + (_spectrum-2)*sxyz; poff = off._data; pfoff = foff._data; cimg_forC(resc,c) { const float t = *(pfoff++), w0 = _cimg_lanczos(t+2), w1 = _cimg_lanczos(t+1), w2 = _cimg_lanczos(t), w3 = _cimg_lanczos(t-1), w4 = _cimg_lanczos(t-2); const Tfloat val2 = (Tfloat)*ptrs, val1 = ptrs>=ptrsmin?(Tfloat)*(ptrs-sxyz):val2, val0 = ptrs>ptrsmin?(Tfloat)*(ptrs-2*sxyz):val1, val3 = ptrs<=ptrsmax?(Tfloat)*(ptrs+sxyz):val2, val4 = ptrs<ptrsmax?(Tfloat)*(ptrs+2*sxyz):val3, val = (val0*w0 + val1*w1 + val2*w2 + val3*w3 + val4*w4)/(w1 + w2 + w3 + w4); *ptrd = (T)(val<vmin?vmin:val>vmax?vmax:val); ptrd+=sxyz; ptrs+=*(poff++); } } } resz.assign(); } else resc.assign(resz,true); return resc._is_shared?(resz._is_shared?(resy._is_shared?(resx._is_shared?(+(*this)):resx):resy):resz):resc; } break; // Unknow interpolation. // default : throw CImgArgumentException(_cimg_instance "resize(): Invalid specified interpolation %d " "(should be { -1=raw | 0=none | 1=nearest | 2=average | 3=linear | 4=grid | 5=bicubic | 6=lanczos }).", cimg_instance, interpolation_type); } return res; } //! Resize image to dimensions of another image. /** \param src Reference image used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ template<typename t> CImg<T>& resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of another image \newinstance. template<typename t> CImg<T> get_resize(const CImg<t>& src, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window. /** \param disp Reference display window used for dimensions. \param interpolation_type Interpolation method. \param boundary_conditions Boundary conditions. \param centering_x Set centering type (only if \p interpolation_type=0). \param centering_y Set centering type (only if \p interpolation_type=0). \param centering_z Set centering type (only if \p interpolation_type=0). \param centering_c Set centering type (only if \p interpolation_type=0). **/ CImg<T>& resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) { return resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to dimensions of a display window \newinstance. CImg<T> get_resize(const CImgDisplay& disp, const int interpolation_type=1, const unsigned int boundary_conditions=0, const float centering_x = 0, const float centering_y = 0, const float centering_z = 0, const float centering_c = 0) const { return get_resize(disp.width(),disp.height(),_depth,_spectrum,interpolation_type,boundary_conditions, centering_x,centering_y,centering_z,centering_c); } //! Resize image to half-size along XY axes, using an optimized filter. CImg<T>& resize_halfXY() { return get_resize_halfXY().move_to(*this); } //! Resize image to half-size along XY axes, using an optimized filter \newinstance. CImg<T> get_resize_halfXY() const { if (is_empty()) return *this; const Tfloat mask[9] = { 0.07842776544f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.1935127547f, 0.1231940459f, 0.07842776544f, 0.1231940459f, 0.07842776544f }; T I[9] = { 0 }; CImg<T> res(_width/2,_height/2,_depth,_spectrum); T *ptrd = res._data; cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,T) if (x%2 && y%2) *(ptrd++) = (T) (I[0]*mask[0] + I[1]*mask[1] + I[2]*mask[2] + I[3]*mask[3] + I[4]*mask[4] + I[5]*mask[5] + I[6]*mask[6] + I[7]*mask[7] + I[8]*mask[8]); return res; } //! Resize image to double-size, using the Scale2X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_doubleXY() { return get_resize_doubleXY().move_to(*this); } //! Resize image to double-size, using the Scale2X algorithm \newinstance. CImg<T> get_resize_doubleXY() const { #define _cimg_gs2x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=(res)._width, ptrd2+=(res)._width) #define _cimg_gs2x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs2x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(_width<<1,_height<<1,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width; _cimg_gs2x_for3x3(*this,x,y,z,c,I,T) { if (Icp!=Icn && Ipc!=Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = Ipc==Icn?Ipc:Icc; *(ptrd2++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; } } } return res; } //! Resize image to triple-size, using the Scale3X algorithm. /** \note Use anisotropic upscaling algorithm <a href="http://scale2x.sourceforge.net/algorithm.html">described here</a>. **/ CImg<T>& resize_tripleXY() { return get_resize_tripleXY().move_to(*this); } //! Resize image to triple-size, using the Scale3X algorithm \newinstance. CImg<T> get_resize_tripleXY() const { #define _cimg_gs3x_for3(bound,i) \ for (int i = 0, _p1##i = 0, \ _n1##i = 1>=(bound)?(int)(bound)-1:1; \ _n1##i<(int)(bound) || i==--_n1##i; \ _p1##i = i++, ++_n1##i, ptrd1+=2*(res)._width, ptrd2+=2*(res)._width, ptrd3+=2*(res)._width) #define _cimg_gs3x_for3x3(img,x,y,z,c,I,T) \ _cimg_gs3x_for3((img)._height,y) for (int x = 0, \ _p1##x = 0, \ _n1##x = (int)( \ (I[0] = I[1] = (T)(img)(_p1##x,_p1##y,z,c)), \ (I[3] = I[4] = (T)(img)(0,y,z,c)), \ (I[6] = I[7] = (T)(img)(0,_n1##y,z,c)), \ 1>=(img)._width?(img).width()-1:1); \ (_n1##x<(img).width() && ( \ (I[2] = (T)(img)(_n1##x,_p1##y,z,c)), \ (I[5] = (T)(img)(_n1##x,y,z,c)), \ (I[8] = (T)(img)(_n1##x,_n1##y,z,c)),1)) || \ x==--_n1##x; \ I[0] = I[1], I[1] = I[2], \ I[3] = I[4], I[4] = I[5], \ I[6] = I[7], I[7] = I[8], \ _p1##x = x++, ++_n1##x) if (is_empty()) return *this; CImg<T> res(3*_width,3*_height,_depth,_spectrum); CImg_3x3(I,T); cimg_forZC(*this,z,c) { T *ptrd1 = res.data(0,0,z,c), *ptrd2 = ptrd1 + res._width, *ptrd3 = ptrd2 + res._width; _cimg_gs3x_for3x3(*this,x,y,z,c,I,T) { if (Icp != Icn && Ipc != Inc) { *(ptrd1++) = Ipc==Icp?Ipc:Icc; *(ptrd1++) = (Ipc==Icp && Icc!=Inp) || (Icp==Inc && Icc!=Ipp)?Icp:Icc; *(ptrd1++) = Icp==Inc?Inc:Icc; *(ptrd2++) = (Ipc==Icp && Icc!=Ipn) || (Ipc==Icn && Icc!=Ipp)?Ipc:Icc; *(ptrd2++) = Icc; *(ptrd2++) = (Icp==Inc && Icc!=Inn) || (Icn==Inc && Icc!=Inp)?Inc:Icc; *(ptrd3++) = Ipc==Icn?Ipc:Icc; *(ptrd3++) = (Ipc==Icn && Icc!=Inn) || (Icn==Inc && Icc!=Ipn)?Icn:Icc; *(ptrd3++) = Icn==Inc?Inc:Icc; } else { *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd1++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd2++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; *(ptrd3++) = Icc; } } } return res; } //! Mirror image content along specified axis. /** \param axis Mirror axis **/ CImg<T>& mirror(const char axis) { if (is_empty()) return *this; T *pf, *pb, *buf = 0; switch (cimg::uncase(axis)) { case 'x' : { pf = _data; pb = data(_width-1); const unsigned int width2 = _width/2; for (unsigned int yzv = 0; yzv<_height*_depth*_spectrum; ++yzv) { for (unsigned int x = 0; x<width2; ++x) { const T val = *pf; *(pf++) = *pb; *(pb--) = val; } pf+=_width - width2; pb+=_width + width2; } } break; case 'y' : { buf = new T[_width]; pf = _data; pb = data(0,_height-1); const unsigned int height2 = _height/2; for (unsigned int zv = 0; zv<_depth*_spectrum; ++zv) { for (unsigned int y = 0; y<height2; ++y) { std::memcpy(buf,pf,_width*sizeof(T)); std::memcpy(pf,pb,_width*sizeof(T)); std::memcpy(pb,buf,_width*sizeof(T)); pf+=_width; pb-=_width; } pf+=(unsigned long)_width*(_height - height2); pb+=(unsigned long)_width*(_height + height2); } } break; case 'z' : { buf = new T[(unsigned long)_width*_height]; pf = _data; pb = data(0,0,_depth-1); const unsigned int depth2 = _depth/2; cimg_forC(*this,c) { for (unsigned int z = 0; z<depth2; ++z) { std::memcpy(buf,pf,_width*_height*sizeof(T)); std::memcpy(pf,pb,_width*_height*sizeof(T)); std::memcpy(pb,buf,_width*_height*sizeof(T)); pf+=(unsigned long)_width*_height; pb-=(unsigned long)_width*_height; } pf+=(unsigned long)_width*_height*(_depth - depth2); pb+=(unsigned long)_width*_height*(_depth + depth2); } } break; case 'c' : { buf = new T[(unsigned long)_width*_height*_depth]; pf = _data; pb = data(0,0,0,_spectrum-1); const unsigned int _spectrum2 = _spectrum/2; for (unsigned int v = 0; v<_spectrum2; ++v) { std::memcpy(buf,pf,_width*_height*_depth*sizeof(T)); std::memcpy(pf,pb,_width*_height*_depth*sizeof(T)); std::memcpy(pb,buf,_width*_height*_depth*sizeof(T)); pf+=(unsigned long)_width*_height*_depth; pb-=(unsigned long)_width*_height*_depth; } } break; default : throw CImgArgumentException(_cimg_instance "mirror(): Invalid specified axis '%c'.", cimg_instance, axis); } delete[] buf; return *this; } //! Mirror image content along specified axis \newinstance. CImg<T> get_mirror(const char axis) const { return (+*this).mirror(axis); } //! Mirror image content along specified axes. /** \param axes Mirror axes, as a C-string. \note \c axes may contains multiple character, e.g. \c "xyz" **/ CImg<T>& mirror(const char *const axes) { for (const char *s = axes; *s; s++) mirror(*s); return *this; } //! Mirror image content along specified axes \newinstance. CImg<T> get_mirror(const char *const axes) const { return (+*this).mirror(axes); } //! Shift image content. /** \param delta_x Amount of displacement along the X-axis. \param delta_y Amount of displacement along the Y-axis. \param delta_z Amount of displacement along the Z-axis. \param delta_c Amount of displacement along the C-axis. \param boundary_conditions Border condition. - \c boundary_conditions can be: - 0: Zero border condition (Dirichlet). - 1: Nearest neighbors (Neumann). - 2: Repeat Pattern (Fourier style). **/ CImg<T>& shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const int boundary_conditions=0) { if (is_empty()) return *this; if (delta_x) // Shift along X-axis switch (boundary_conditions) { case 0 : if (cimg::abs(delta_x)>=width()) return fill(0); if (delta_x<0) cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(-delta_x,y,z,c),(_width+delta_x)*sizeof(T)); std::memset(data(_width+delta_x,y,z,c),0,-delta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memmove(data(delta_x,y,z,c),data(0,y,z,c),(_width-delta_x)*sizeof(T)); std::memset(data(0,y,z,c),0,delta_x*sizeof(T)); } break; case 1 : if (delta_x<0) { const int ndelta_x = (-delta_x>=width())?width()-1:-delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(_width-1,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x-1; ++l) *(--ptrd) = val; } } else { const int ndelta_x = (delta_x>=width())?width()-1:delta_x; if (!ndelta_x) return *this; cimg_forYZC(*this,y,z,c) { std::memmove(data(ndelta_x,y,z,c),data(0,y,z,c),(_width-ndelta_x)*sizeof(T)); T *ptrd = data(0,y,z,c); const T val = *ptrd; for (int l = 0; l<ndelta_x-1; ++l) *(++ptrd) = val; } } break; default : { const int ml = cimg::mod(-delta_x,width()), ndelta_x = (ml<=width()/2)?ml:(ml-width()); if (!ndelta_x) return *this; T *const buf = new T[cimg::abs(ndelta_x)]; if (ndelta_x>0) cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(0,y,z,c),ndelta_x*sizeof(T)); std::memmove(data(0,y,z,c),data(ndelta_x,y,z,c),(_width-ndelta_x)*sizeof(T)); std::memcpy(data(_width-ndelta_x,y,z,c),buf,ndelta_x*sizeof(T)); } else cimg_forYZC(*this,y,z,c) { std::memcpy(buf,data(_width+ndelta_x,y,z,c),-ndelta_x*sizeof(T)); std::memmove(data(-ndelta_x,y,z,c),data(0,y,z,c),(_width+ndelta_x)*sizeof(T)); std::memcpy(data(0,y,z,c),buf,-ndelta_x*sizeof(T)); } delete[] buf; } } if (delta_y) // Shift along Y-axis switch (boundary_conditions) { case 0 : if (cimg::abs(delta_y)>=height()) return fill(0); if (delta_y<0) cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,-delta_y,z,c),_width*(_height+delta_y)*sizeof(T)); std::memset(data(0,_height+delta_y,z,c),0,-delta_y*_width*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memmove(data(0,delta_y,z,c),data(0,0,z,c),_width*(_height-delta_y)*sizeof(T)); std::memset(data(0,0,z,c),0,delta_y*_width*sizeof(T)); } break; case 1 : if (delta_y<0) { const int ndelta_y = (-delta_y>=height())?height()-1:-delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,_height-ndelta_y,z,c), *ptrs = data(0,_height-1,z,c); for (int l = 0; l<ndelta_y-1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } else { const int ndelta_y = (delta_y>=height())?height()-1:delta_y; if (!ndelta_y) return *this; cimg_forZC(*this,z,c) { std::memmove(data(0,ndelta_y,z,c),data(0,0,z,c),_width*(_height-ndelta_y)*sizeof(T)); T *ptrd = data(0,1,z,c), *ptrs = data(0,0,z,c); for (int l = 0; l<ndelta_y-1; ++l) { std::memcpy(ptrd,ptrs,_width*sizeof(T)); ptrd+=_width; } } } break; default : { const int ml = cimg::mod(-delta_y,height()), ndelta_y = (ml<=height()/2)?ml:(ml-height()); if (!ndelta_y) return *this; T *const buf = new T[(unsigned long)_width*cimg::abs(ndelta_y)]; if (ndelta_y>0) cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,0,z,c),_width*ndelta_y*sizeof(T)); std::memmove(data(0,0,z,c),data(0,ndelta_y,z,c),_width*(_height-ndelta_y)*sizeof(T)); std::memcpy(data(0,_height-ndelta_y,z,c),buf,_width*ndelta_y*sizeof(T)); } else cimg_forZC(*this,z,c) { std::memcpy(buf,data(0,_height+ndelta_y,z,c),-ndelta_y*_width*sizeof(T)); std::memmove(data(0,-ndelta_y,z,c),data(0,0,z,c),_width*(_height+ndelta_y)*sizeof(T)); std::memcpy(data(0,0,z,c),buf,-ndelta_y*_width*sizeof(T)); } delete[] buf; } } if (delta_z) // Shift along Z-axis switch (boundary_conditions) { case 0 : if (cimg::abs(delta_z)>=depth()) return fill(0); if (delta_z<0) cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,-delta_z,c),_width*_height*(_depth+delta_z)*sizeof(T)); std::memset(data(0,0,_depth+delta_z,c),0,_width*_height*(-delta_z)*sizeof(T)); } else cimg_forC(*this,c) { std::memmove(data(0,0,delta_z,c),data(0,0,0,c),_width*_height*(_depth-delta_z)*sizeof(T)); std::memset(data(0,0,0,c),0,delta_z*_width*_height*sizeof(T)); } break; case 1 : if (delta_z<0) { const int ndelta_z = (-delta_z>=depth())?depth()-1:-delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,_depth-ndelta_z,c), *ptrs = data(0,0,_depth-1,c); for (int l = 0; l<ndelta_z-1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(unsigned long)_width*_height; } } } else { const int ndelta_z = (delta_z>=depth())?depth()-1:delta_z; if (!ndelta_z) return *this; cimg_forC(*this,c) { std::memmove(data(0,0,ndelta_z,c),data(0,0,0,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); T *ptrd = data(0,0,1,c), *ptrs = data(0,0,0,c); for (int l = 0; l<ndelta_z-1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*sizeof(T)); ptrd+=(unsigned long)_width*_height; } } } break; default : { const int ml = cimg::mod(-delta_z,depth()), ndelta_z = (ml<=depth()/2)?ml:(ml-depth()); if (!ndelta_z) return *this; T *const buf = new T[(unsigned long)_width*_height*cimg::abs(ndelta_z)]; if (ndelta_z>0) cimg_forC(*this,c) { std::memcpy(buf,data(0,0,0,c),_width*_height*ndelta_z*sizeof(T)); std::memmove(data(0,0,0,c),data(0,0,ndelta_z,c),_width*_height*(_depth-ndelta_z)*sizeof(T)); std::memcpy(data(0,0,_depth-ndelta_z,c),buf,_width*_height*ndelta_z*sizeof(T)); } else cimg_forC(*this,c) { std::memcpy(buf,data(0,0,_depth+ndelta_z,c),-ndelta_z*_width*_height*sizeof(T)); std::memmove(data(0,0,-ndelta_z,c),data(0,0,0,c),_width*_height*(_depth+ndelta_z)*sizeof(T)); std::memcpy(data(0,0,0,c),buf,-ndelta_z*_width*_height*sizeof(T)); } delete[] buf; } } if (delta_c) // Shift along C-axis switch (boundary_conditions) { case 0 : if (cimg::abs(delta_c)>=spectrum()) return fill(0); if (delta_c<0) { std::memmove(_data,data(0,0,0,-delta_c),_width*_height*_depth*(_spectrum+delta_c)*sizeof(T)); std::memset(data(0,0,0,_spectrum+delta_c),0,_width*_height*_depth*(-delta_c)*sizeof(T)); } else { std::memmove(data(0,0,0,delta_c),_data,_width*_height*_depth*(_spectrum-delta_c)*sizeof(T)); std::memset(_data,0,delta_c*_width*_height*_depth*sizeof(T)); } break; case 1 : if (delta_c<0) { const int ndelta_c = (-delta_c>=spectrum())?spectrum()-1:-delta_c; if (!ndelta_c) return *this; std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,_spectrum-ndelta_c), *ptrs = data(0,0,0,_spectrum-1); for (int l = 0; l<ndelta_c-1; ++l) { std::memcpy(ptrd,ptrs,_width*_height*_depth*sizeof(T)); ptrd+=(unsigned long)_width*_height*_depth; } } else { const int ndelta_c = (delta_c>=spectrum())?spectrum()-1:delta_c; if (!ndelta_c) return *this; std::memmove(data(0,0,0,ndelta_c),_data,_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); T *ptrd = data(0,0,0,1); for (int l = 0; l<ndelta_c-1; ++l) { std::memcpy(ptrd,_data,_width*_height*_depth*sizeof(T)); ptrd+=(unsigned long)_width*_height*_depth; } } break; default : { const int ml = cimg::mod(-delta_c,spectrum()), ndelta_c = (ml<=spectrum()/2)?ml:(ml-spectrum()); if (!ndelta_c) return *this; T *const buf = new T[(unsigned long)_width*_height*_depth*cimg::abs(ndelta_c)]; if (ndelta_c>0) { std::memcpy(buf,_data,_width*_height*_depth*ndelta_c*sizeof(T)); std::memmove(_data,data(0,0,0,ndelta_c),_width*_height*_depth*(_spectrum-ndelta_c)*sizeof(T)); std::memcpy(data(0,0,0,_spectrum-ndelta_c),buf,_width*_height*_depth*ndelta_c*sizeof(T)); } else { std::memcpy(buf,data(0,0,0,_spectrum+ndelta_c),-ndelta_c*_width*_height*_depth*sizeof(T)); std::memmove(data(0,0,0,-ndelta_c),_data,_width*_height*_depth*(_spectrum+ndelta_c)*sizeof(T)); std::memcpy(_data,buf,-ndelta_c*_width*_height*_depth*sizeof(T)); } delete[] buf; } } return *this; } //! Shift image content \newinstance. CImg<T> get_shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0, const int boundary_conditions=0) const { return (+*this).shift(delta_x,delta_y,delta_z,delta_c,boundary_conditions); } //! Permute axes order. /** \param order Axes permutations, as a C-string of 4 characters. This function permutes image content regarding the specified axes permutation. **/ CImg<T>& permute_axes(const char *const order) { return get_permute_axes(order).move_to(*this); } //! Permute axes order \newinstance. CImg<T> get_permute_axes(const char *const order) const { const T foo = (T)0; return _get_permute_axes(order,foo); } template<typename t> CImg<t> _get_permute_axes(const char *const permut, const t&) const { if (is_empty() || !permut) return CImg<t>(*this,false); CImg<t> res; const T* ptrs = _data; if (!cimg::strncasecmp(permut,"xyzc",4)) return +*this; if (!cimg::strncasecmp(permut,"xycz",4)) { res.assign(_width,_height,_spectrum,_depth); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,y,c,z,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"xzyc",4)) { res.assign(_width,_depth,_height,_spectrum); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,y,c,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"xzcy",4)) { res.assign(_width,_depth,_spectrum,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,z,c,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"xcyz",4)) { res.assign(_width,_spectrum,_height,_depth); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,y,z,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"xczy",4)) { res.assign(_width,_spectrum,_depth,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(x,c,z,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"yxzc",4)) { res.assign(_height,_width,_depth,_spectrum); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,z,c,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"yxcz",4)) { res.assign(_height,_width,_spectrum,_depth); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,x,c,z,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"yzxc",4)) { res.assign(_height,_depth,_width,_spectrum); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,x,c,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"yzcx",4)) { res.assign(_height,_depth,_spectrum,_width); switch (_width) { case 1 : { t *ptr_r = res.data(0,0,0,0); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); } } break; case 2 : { t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); *(ptr_g++) = (t)*(ptrs++); } } break; case 3 : { // Optimization for the classical conversion from interleaved RGB to planar RGB t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); *(ptr_g++) = (t)*(ptrs++); *(ptr_b++) = (t)*(ptrs++); } } break; case 4 : { // Optimization for the classical conversion from interleaved RGBA to planar RGBA t *ptr_r = res.data(0,0,0,0), *ptr_g = res.data(0,0,0,1), *ptr_b = res.data(0,0,0,2), *ptr_a = res.data(0,0,0,3); for (unsigned int siz = _height*_depth*_spectrum; siz; --siz) { *(ptr_r++) = (t)*(ptrs++); *(ptr_g++) = (t)*(ptrs++); *(ptr_b++) = (t)*(ptrs++); *(ptr_a++) = (t)*(ptrs++); } } break; default : { const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,z,c,x,wh,whd) = *(ptrs++); return res; } } } if (!cimg::strncasecmp(permut,"ycxz",4)) { res.assign(_height,_spectrum,_width,_depth); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,x,z,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"yczx",4)) { res.assign(_height,_spectrum,_depth,_width); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(y,c,z,x,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zxyc",4)) { res.assign(_depth,_width,_height,_spectrum); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,y,c,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zxcy",4)) { res.assign(_depth,_width,_spectrum,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,x,c,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zyxc",4)) { res.assign(_depth,_height,_width,_spectrum); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,x,c,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zycx",4)) { res.assign(_depth,_height,_spectrum,_width); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,y,c,x,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zcxy",4)) { res.assign(_depth,_spectrum,_width,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,x,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"zcyx",4)) { res.assign(_depth,_spectrum,_height,_width); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(z,c,y,x,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"cxyz",4)) { res.assign(_spectrum,_width,_height,_depth); switch (_spectrum) { case 1 : { const T *ptr_r = data(0,0,0,0); t *ptrd = res._data; for (unsigned long siz = (unsigned long)_width*_height*_depth; siz; --siz) *(ptrd++) = (t)*(ptr_r++); } break; case 2 : { const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1); t *ptrd = res._data; for (unsigned long siz = (unsigned long)_width*_height*_depth; siz; --siz) { *(ptrd++) = (t)*(ptr_r++); *(ptrd++) = (t)*(ptr_g++); } } break; case 3 : { // Optimization for the classical conversion from planar RGB to interleaved RGB const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); t *ptrd = res._data; for (unsigned long siz = (unsigned long)_width*_height*_depth; siz; --siz) { *(ptrd++) = (t)*(ptr_r++); *(ptrd++) = (t)*(ptr_g++); *(ptrd++) = (t)*(ptr_b++); } } break; case 4 : { // Optimization for the classical conversion from planar RGBA to interleaved RGBA const T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); t *ptrd = res._data; for (unsigned long siz = (unsigned long)_width*_height*_depth; siz; --siz) { *(ptrd++) = (t)*(ptr_r++); *(ptrd++) = (t)*(ptr_g++); *(ptrd++) = (t)*(ptr_b++); *(ptrd++) = (t)*(ptr_a++); } } break; default : { const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,y,z,wh,whd) = (t)*(ptrs++); } } } if (!cimg::strncasecmp(permut,"cxzy",4)) { res.assign(_spectrum,_width,_depth,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,x,z,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"cyxz",4)) { res.assign(_spectrum,_height,_width,_depth); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,x,z,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"cyzx",4)) { res.assign(_spectrum,_height,_depth,_width); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,y,z,x,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"czxy",4)) { res.assign(_spectrum,_depth,_width,_height); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,x,y,wh,whd) = (t)*(ptrs++); } if (!cimg::strncasecmp(permut,"czyx",4)) { res.assign(_spectrum,_depth,_height,_width); const unsigned long wh = (unsigned long)res._width*res._height, whd = wh*res._depth; cimg_forXYZC(*this,x,y,z,c) res(c,z,y,x,wh,whd) = (t)*(ptrs++); } if (!res) throw CImgArgumentException(_cimg_instance "permute_axes(): Invalid specified permutation '%s'.", cimg_instance, permut); return res; } //! Unroll pixel values along specified axis. /** \param axis Unroll axis (can be \c 'x', \c 'y', \c 'z' or c 'c'). **/ CImg<T>& unroll(const char axis) { const unsigned int siz = size(); if (siz) switch (axis) { case 'x' : _width = siz; _height = _depth = _spectrum = 1; break; case 'y' : _height = siz; _width = _depth = _spectrum = 1; break; case 'z' : _depth = siz; _width = _height = _spectrum = 1; break; default : _spectrum = siz; _width = _height = _depth = 1; } return *this; } //! Unroll pixel values along specified axis \newinstance. CImg<T> get_unroll(const char axis) const { return (+*this).unroll(axis); } //! Rotate image with arbitrary angle. /** \param angle Rotation angle, in degrees. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=cyclic }</tt>. \param interpolation_type Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. \note Most of the time, size of the image is modified. **/ CImg<T>& rotate(const float angle, const unsigned int boundary_conditions=0, const unsigned int interpolation_type=1) { return get_rotate(angle,boundary_conditions,interpolation_type).move_to(*this); } //! Rotate image with arbitrary angle \newinstance. CImg<T> get_rotate(const float angle, const unsigned int boundary_conditions=0, const unsigned int interpolation_type=1) const { if (is_empty()) return *this; CImg<T> res; const float nangle = cimg::mod(angle,360.0f); if (boundary_conditions!=1 && cimg::mod(nangle,90.0f)==0) { // optimized version for orthogonal angles const int wm1 = width() - 1, hm1 = height() - 1; const int iangle = (int)nangle/90; switch (iangle) { case 1 : { res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(y,hm1-x,z,c); } break; case 2 : { res.assign(_width,_height,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1-x,hm1-y,z,c); } break; case 3 : { res.assign(_height,_width,_depth,_spectrum); T *ptrd = res._data; cimg_forXYZC(res,x,y,z,c) *(ptrd++) = (*this)(wm1-y,x,z,c); } break; default : return *this; } } else { // generic version const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); const float rad = (float)(nangle*cimg::PI/180.0), ca = (float)std::cos(rad), sa = (float)std::sin(rad), ux = cimg::abs(_width*ca), uy = cimg::abs(_width*sa), vx = cimg::abs(_height*sa), vy = cimg::abs(_height*ca), w2 = 0.5f*_width, h2 = 0.5f*_height, dw2 = 0.5f*(ux+vx), dh2 = 0.5f*(uy+vy); res.assign((int)(ux+vx),(int)(uy+vy),_depth,_spectrum); switch (boundary_conditions) { case 0 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = cubic_atXY(w2 + (x-dw2)*ca + (y-dh2)*sa,h2 - (x-dw2)*sa + (y-dh2)*ca,z,c,0); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)linear_atXY(w2 + (x-dw2)*ca + (y-dh2)*sa,h2 - (x-dw2)*sa + (y-dh2)*ca,z,c,0); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = atXY((int)(w2 + (x-dw2)*ca + (y-dh2)*sa),(int)(h2 - (x-dw2)*sa + (y-dh2)*ca),z,c,0); } } } break; case 1 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = _cubic_atXY(w2 + (x-dw2)*ca + (y-dh2)*sa,h2 - (x-dw2)*sa + (y-dh2)*ca,z,c); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)_linear_atXY(w2 + (x-dw2)*ca + (y-dh2)*sa,h2 - (x-dw2)*sa + (y-dh2)*ca,z,c); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = _atXY((int)(w2 + (x-dw2)*ca + (y-dh2)*sa),(int)(h2 - (x-dw2)*sa + (y-dh2)*ca),z,c); } } } break; case 2 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = _cubic_atXY(cimg::mod(w2 + (x-dw2)*ca + (y-dh2)*sa,(float)width()), cimg::mod(h2 - (x-dw2)*sa + (y-dh2)*ca,(float)height()),z,c); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)_linear_atXY(cimg::mod(w2 + (x-dw2)*ca + (y-dh2)*sa,(float)width()), cimg::mod(h2 - (x-dw2)*sa + (y-dh2)*ca,(float)height()),z,c); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (*this)(cimg::mod((int)(w2 + (x-dw2)*ca + (y-dh2)*sa),width()), cimg::mod((int)(h2 - (x-dw2)*sa + (y-dh2)*ca),height()),z,c); } } } break; default : throw CImgArgumentException(_cimg_instance "rotate(): Invalid specified border conditions %d " "(should be { 0=dirichlet | 1=neumann | 2=cyclic }).", cimg_instance, boundary_conditions); } } return res; } //! Rotate image with arbitrary angle, around a center point. /** \param angle Rotation angle, in degrees. \param cx X-coordinate of the rotation center. \param cy Y-coordinate of the rotation center. \param zoom Zoom factor. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=cyclic }</tt>. \param interpolation_type Type of interpolation. Can be <tt>{ 0=nearest | 1=linear | 2=cubic }</tt>. **/ CImg<T>& rotate(const float angle, const float cx, const float cy, const float zoom, const unsigned int boundary_conditions=3, const unsigned int interpolation_type=1) { return get_rotate(angle,cx,cy,zoom,boundary_conditions,interpolation_type).move_to(*this); } //! Rotate image with arbitrary angle, around a center point \newinstance. CImg<T> get_rotate(const float angle, const float cx, const float cy, const float zoom, const unsigned int boundary_conditions=3, const unsigned int interpolation_type=1) const { if (interpolation_type>2) throw CImgArgumentException(_cimg_instance "rotate(): Invalid specified interpolation type %d " "(should be { 0=none | 1=linear | 2=bicubic }).", cimg_instance, interpolation_type); if (is_empty()) return *this; CImg<T> res(_width,_height,_depth,_spectrum); const Tfloat vmin = (Tfloat)cimg::type<T>::min(), vmax = (Tfloat)cimg::type<T>::max(); const float rad = (float)((angle*cimg::PI)/180.0), ca = (float)std::cos(rad)/zoom, sa = (float)std::sin(rad)/zoom; switch (boundary_conditions) { case 0 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = cubic_atXY(cx + (x-cx)*ca + (y-cy)*sa,cy - (x-cx)*sa + (y-cy)*ca,z,c,0); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)linear_atXY(cx + (x-cx)*ca + (y-cy)*sa,cy - (x-cx)*sa + (y-cy)*ca,z,c,0); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = atXY((int)(cx + (x-cx)*ca + (y-cy)*sa),(int)(cy - (x-cx)*sa + (y-cy)*ca),z,c,0); } } } break; case 1 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = _cubic_atXY(cx + (x-cx)*ca + (y-cy)*sa,cy - (x-cx)*sa + (y-cy)*ca,z,c); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)_linear_atXY(cx + (x-cx)*ca + (y-cy)*sa,cy - (x-cx)*sa + (y-cy)*ca,z,c); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = _atXY((int)(cx + (x-cx)*ca + (y-cy)*sa),(int)(cy - (x-cx)*sa + (y-cy)*ca),z,c); } } } break; case 2 : { switch (interpolation_type) { case 2 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) { const Tfloat val = _cubic_atXY(cimg::mod(cx + (x-cx)*ca + (y-cy)*sa,(float)width()), cimg::mod(cy - (x-cx)*sa + (y-cy)*ca,(float)height()),z,c); res(x,y,z,c) = (T)(val<vmin?vmin:val>vmax?vmax:val); } } break; case 1 : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (T)_linear_atXY(cimg::mod(cx + (x-cx)*ca + (y-cy)*sa,(float)width()), cimg::mod(cy - (x-cx)*sa + (y-cy)*ca,(float)height()),z,c); } break; default : { cimg_forXY(res,x,y) cimg_forZC(*this,z,c) res(x,y,z,c) = (*this)(cimg::mod((int)(cx + (x-cx)*ca + (y-cy)*sa),width()), cimg::mod((int)(cy - (x-cx)*sa + (y-cy)*ca),height()),z,c); } } } break; default : throw CImgArgumentException(_cimg_instance "rotate(): Invalid specified border conditions %d " "(should be { 0=dirichlet | 1=neumann | 2=cyclic }).", cimg_instance, boundary_conditions); } return res; } //! Warp image content by a warping field. /** \param warp Warping field. \param is_relative Tells if warping field gives absolute or relative warping coordinates. \param is_linear_interpolation Tells if linear interpolation must be used (instead of nearest neighbors). \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann | 2=cyclic }</tt>. **/ template<typename t> CImg<T>& warp(const CImg<t>& warp, const bool is_relative=false, const bool is_linear_interpolation=true, const unsigned int boundary_conditions=0) { return get_warp(warp,is_relative,is_linear_interpolation,boundary_conditions).move_to(*this); } //! Warp image content by a warping field \newinstance template<typename t> CImg<T> get_warp(const CImg<t>& warp, const bool is_relative=false, const bool is_linear_interpolation=true, const unsigned int boundary_conditions=0) const { if (is_empty() || !warp) return *this; if (is_relative && !is_sameXYZ(warp)) throw CImgArgumentException(_cimg_instance "warp(): Instance and specified relative warping field (%u,%u,%u,%u,%p) " "have different XYZ dimensions.", cimg_instance, warp._width,warp._height,warp._depth,warp._spectrum,warp._data); CImg<T> res(warp._width,warp._height,warp._depth,_spectrum); T *ptrd = res._data; switch (warp._spectrum) { case 1 : // 1d warping. if (is_relative) { // Relative warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atX(cimg::mod(x - (float)*(ptrs0++),(float)_width),y,z,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atX(x - (float)*(ptrs0++),y,z,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atX(x - (float)*(ptrs0++),y,z,c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod(x - (int)*(ptrs0++),(int)_width),y,z,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = _atX(x - (int)*(ptrs0++),y,z,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = atX(x - (int)*(ptrs0++),y,z,c,0); } } } } else { // Absolute warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atX(cimg::mod((float)*(ptrs0++),(float)_width),0,0,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atX((float)*(ptrs0++),0,0,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atX((float)*(ptrs0++),0,0,c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod((int)*(ptrs0++),(int)_width),0,0,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = _atX((int)*(ptrs0++),0,0,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp._data; cimg_forXYZ(res,x,y,z) *(ptrd++) = atX((int)*(ptrs0++),0,0,c,0); } } } } break; case 2 : // 2d warping if (is_relative) { // Relative warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXY(cimg::mod(x - (float)*(ptrs0++),(float)_width), cimg::mod(y - (float)*(ptrs1++),(float)_height),z,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atXY(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z,c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod(x - (int)*(ptrs0++),(int)_width), cimg::mod(y - (int)*(ptrs1++),(int)_height),z,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = _atXY(x - (int)*(ptrs0++),y - (int)*(ptrs1++),z,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = atXY(x - (int)*(ptrs0++),y - (int)*(ptrs1++),z,c,0); } } } } else { // Absolute warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXY(cimg::mod((float)*(ptrs0++),(float)_width), cimg::mod((float)*(ptrs1++),(float)_height),0,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atXY((float)*(ptrs0++),(float)*(ptrs1++),0,c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod((int)*(ptrs0++),(int)_width), cimg::mod((int)*(ptrs1++),(int)_height),0,c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = _atXY((int)*(ptrs0++),(int)*(ptrs1++),0,c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1); cimg_forXYZ(res,x,y,z) *(ptrd++) = atXY((int)*(ptrs0++),(int)*(ptrs1++),0,c,0); } } } } break; default : // 3d warping if (is_relative) { // Relative warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXYZ(cimg::mod(x - (float)*(ptrs0++),(float)_width), cimg::mod(y - (float)*(ptrs1++),(float)_height), cimg::mod(z - (float)*(ptrs2++),(float)_depth),c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atXYZ(x - (float)*(ptrs0++),y - (float)*(ptrs1++),z - (float)*(ptrs2++),c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod(x - (int)*(ptrs0++),(int)_width), cimg::mod(y - (int)*(ptrs1++),(int)_height), cimg::mod(z - (int)*(ptrs2++),(int)_depth),c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = _atXYZ(x - (int)*(ptrs0++),y - (int)*(ptrs1++),z - (int)*(ptrs2++),c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = atXYZ(x - (int)*(ptrs0++),y - (int)*(ptrs1++),z - (int)*(ptrs2++),c,0); } } } } else { // Absolute warp coordinates if (is_linear_interpolation) switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXYZ(cimg::mod((float)*(ptrs0++),(float)_width), cimg::mod((float)*(ptrs1++),(float)_height), cimg::mod((float)*(ptrs2++),(float)_depth),c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)_linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (T)linear_atXYZ((float)*(ptrs0++),(float)*(ptrs1++),(float)*(ptrs2++),c,0); } } } else switch (boundary_conditions) { case 2 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = (*this)(cimg::mod((int)*(ptrs0++),(int)_width), cimg::mod((int)*(ptrs1++),(int)_height), cimg::mod((int)*(ptrs2++),(int)_depth),c); } } break; case 1 : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = _atXYZ((int)*(ptrs0++),(int)*(ptrs1++),(int)*(ptrs2++),c); } } break; default : { cimg_forC(res,c) { const t *ptrs0 = warp.data(0,0,0,0), *ptrs1 = warp.data(0,0,0,1), *ptrs2 = warp.data(0,0,0,2); cimg_forXYZ(res,x,y,z) *(ptrd++) = atXYZ((int)*(ptrs0++),(int)*(ptrs1++),(int)*(ptrs2++),c,0); } } } } } return res; } //! Generate a 2d representation of a 3d image, with XY,XZ and YZ views. /** \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. **/ CImg<T> get_projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) const { if (is_empty() || _depth<2) return +*this; const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; const CImg<T> img_xy = get_crop(0,0,_z0,0,_width-1,_height-1,_z0,_spectrum-1), img_zy = get_crop(_x0,0,0,0,_x0,_height-1,_depth-1,_spectrum-1).permute_axes("xzyc").resize(_depth,_height,1,-100,-1), img_xz = get_crop(0,_y0,0,0,_width-1,_y0,_depth-1,_spectrum-1).resize(_width,_depth,1,-100,-1); return CImg<T>(_width + _depth,_height + _depth,1,_spectrum,cimg::min(img_xy.min(),img_zy.min(),img_xz.min())). draw_image(0,0,img_xy).draw_image(img_xy._width,0,img_zy). draw_image(0,img_xy._height,img_xz); } //! Construct a 2d representation of a 3d image, with XY,XZ and YZ views \inplace. CImg<T>& projections2d(const unsigned int x0, const unsigned int y0, const unsigned int z0) { if (_depth<2) return *this; return get_projections2d(x0,y0,z0).move_to(*this); } //! Crop image region. /** \param x0 = X-coordinate of the upper-left crop rectangle corner. \param y0 = Y-coordinate of the upper-left crop rectangle corner. \param z0 = Z-coordinate of the upper-left crop rectangle corner. \param c0 = C-coordinate of the upper-left crop rectangle corner. \param x1 = X-coordinate of the lower-right crop rectangle corner. \param y1 = Y-coordinate of the lower-right crop rectangle corner. \param z1 = Z-coordinate of the lower-right crop rectangle corner. \param c1 = C-coordinate of the lower-right crop rectangle corner. \param boundary_conditions = Dirichlet (false) or Neumann border conditions. **/ CImg<T>& crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const bool boundary_conditions=false) { return get_crop(x0,y0,z0,c0,x1,y1,z1,c1,boundary_conditions).move_to(*this); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const bool boundary_conditions=false) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "crop(): Empty instance.", cimg_instance); const int nx0 = x0<x1?x0:x1, nx1 = x0^x1^nx0, ny0 = y0<y1?y0:y1, ny1 = y0^y1^ny0, nz0 = z0<z1?z0:z1, nz1 = z0^z1^nz0, nc0 = c0<c1?c0:c1, nc1 = c0^c1^nc0; CImg<T> res(1U + nx1 - nx0,1U + ny1 - ny0,1U + nz1 - nz0,1U + nc1 - nc0); if (nx0<0 || nx1>=width() || ny0<0 || ny1>=height() || nz0<0 || nz1>=depth() || nc0<0 || nc1>=spectrum()) { if (boundary_conditions) cimg_forXYZC(res,x,y,z,c) res(x,y,z,c) = _atXYZC(nx0+x,ny0+y,nz0+z,nc0+c); else res.fill(0).draw_image(-nx0,-ny0,-nz0,-nc0,*this); } else res.draw_image(-nx0,-ny0,-nz0,-nc0,*this); return res; } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const bool boundary_conditions=false) { return crop(x0,y0,z0,0,x1,y1,z1,_spectrum-1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const bool boundary_conditions=false) const { return get_crop(x0,y0,z0,0,x1,y1,z1,_spectrum-1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int y0, const int x1, const int y1, const bool boundary_conditions=false) { return crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int y0, const int x1, const int y1, const bool boundary_conditions=false) const { return get_crop(x0,y0,0,0,x1,y1,_depth - 1,_spectrum - 1,boundary_conditions); } //! Crop image region \overloading. CImg<T>& crop(const int x0, const int x1, const bool boundary_conditions=false) { return crop(x0,0,0,0,x1,_height-1,_depth-1,_spectrum-1,boundary_conditions); } //! Crop image region \newinstance. CImg<T> get_crop(const int x0, const int x1, const bool boundary_conditions=false) const { return get_crop(x0,0,0,0,x1,_height-1,_depth-1,_spectrum-1,boundary_conditions); } //! Autocrop image region, regarding the specified background value. CImg<T>& autocrop(const T value, const char *const axes="czyx") { if (is_empty()) return *this; for (const char *s = axes; *s; ++s) { const char axis = cimg::uncase(*s); const CImg<intT> coords = _autocrop(value,axis); if (coords[0]==-1 && coords[1]==-1) return assign(); // Image has only 'value' pixels. else switch (axis) { case 'x' : { const int x0 = coords[0], x1 = coords[1]; if (x0>=0 && x1>=0) crop(x0,x1); } break; case 'y' : { const int y0 = coords[0], y1 = coords[1]; if (y0>=0 && y1>=0) crop(0,y0,_width-1,y1); } break; case 'z' : { const int z0 = coords[0], z1 = coords[1]; if (z0>=0 && z1>=0) crop(0,0,z0,_width-1,_height-1,z1); } break; default : { const int c0 = coords[0], c1 = coords[1]; if (c0>=0 && c1>=0) crop(0,0,0,c0,_width-1,_height-1,_depth-1,c1); } } } return *this; } //! Autocrop image region, regarding the specified background value \newinstance. CImg<T> get_autocrop(const T value, const char *const axes="czyx") const { return (+*this).autocrop(value,axes); } //! Autocrop image region, regarding the specified background color. /** \param color Color used for the crop. If \c 0, color is guessed. \param axes Axes used for the crop. **/ CImg<T>& autocrop(const T *const color=0, const char *const axes="zyx") { if (is_empty()) return *this; if (!color) { // Guess color. const CImg<T> col1 = get_vector_at(0,0,0); const unsigned int w = _width, h = _height, d = _depth, s = _spectrum; autocrop(col1,axes); if (_width==w && _height==h && _depth==d && _spectrum==s) { const CImg<T> col2 = get_vector_at(w-1,h-1,d-1); autocrop(col2,axes); } return *this; } for (const char *s = axes; *s; ++s) { const char axis = cimg::uncase(*s); switch (axis) { case 'x' : { int x0 = width(), x1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'x'); const int nx0 = coords[0], nx1 = coords[1]; if (nx0>=0 && nx1>=0) { x0 = cimg::min(x0,nx0); x1 = cimg::max(x1,nx1); } } if (x0==width() && x1==-1) return assign(); else crop(x0,x1); } break; case 'y' : { int y0 = height(), y1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'y'); const int ny0 = coords[0], ny1 = coords[1]; if (ny0>=0 && ny1>=0) { y0 = cimg::min(y0,ny0); y1 = cimg::max(y1,ny1); } } if (y0==height() && y1==-1) return assign(); else crop(0,y0,_width-1,y1); } break; default : { int z0 = depth(), z1 = -1; cimg_forC(*this,c) { const CImg<intT> coords = get_shared_channel(c)._autocrop(color[c],'z'); const int nz0 = coords[0], nz1 = coords[1]; if (nz0>=0 && nz1>=0) { z0 = cimg::min(z0,nz0); z1 = cimg::max(z1,nz1); } } if (z0==depth() && z1==-1) return assign(); else crop(0,0,z0,_width-1,_height-1,z1); } } } return *this; } //! Autocrop image region, regarding the specified background color \newinstance. CImg<T> get_autocrop(const T *const color=0, const char *const axes="zyx") const { return (+*this).autocrop(color,axes); } //! Autocrop image region, regarding the specified background color \overloading. template<typename t> CImg<T>& autocrop(const CImg<t>& color, const char *const axes="zyx") { return get_autocrop(color,axes).move_to(*this); } //! Autocrop image region, regarding the specified background color \newinstance. template<typename t> CImg<T> get_autocrop(const CImg<t>& color, const char *const axes="zyx") const { return get_autocrop(color._data,axes); } CImg<intT> _autocrop(const T value, const char axis) const { CImg<intT> res; switch (cimg::uncase(axis)) { case 'x' : { int x0 = -1, x1 = -1; cimg_forX(*this,x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x0 = x; x = width(); y = height(); z = depth(); c = spectrum(); } if (x0>=0) { for (int x = width()-1; x>=0; --x) cimg_forYZC(*this,y,z,c) if ((*this)(x,y,z,c)!=value) { x1 = x; x = 0; y = height(); z = depth(); c = spectrum(); } } res = CImg<intT>::vector(x0,x1); } break; case 'y' : { int y0 = -1, y1 = -1; cimg_forY(*this,y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y0 = y; x = width(); y = height(); z = depth(); c = spectrum(); } if (y0>=0) { for (int y = height()-1; y>=0; --y) cimg_forXZC(*this,x,z,c) if ((*this)(x,y,z,c)!=value) { y1 = y; x = width(); y = 0; z = depth(); c = spectrum(); } } res = CImg<intT>::vector(y0,y1); } break; case 'z' : { int z0 = -1, z1 = -1; cimg_forZ(*this,z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z0 = z; x = width(); y = height(); z = depth(); c = spectrum(); } if (z0>=0) { for (int z = depth()-1; z>=0; --z) cimg_forXYC(*this,x,y,c) if ((*this)(x,y,z,c)!=value) { z1 = z; x = width(); y = height(); z = 0; c = spectrum(); } } res = CImg<intT>::vector(z0,z1); } break; default : { int c0 = -1, c1 = -1; cimg_forC(*this,c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c0 = c; x = width(); y = height(); z = depth(); c = spectrum(); } if (c0>=0) { for (int c = spectrum()-1; c>=0; --c) cimg_forXYZ(*this,x,y,z) if ((*this)(x,y,z,c)!=value) { c1 = c; x = width(); y = height(); z = depth(); c = 0; } } res = CImg<intT>::vector(c0,c1); } } return res; } //! Return specified image column. /** \param x0 Image column. **/ CImg<T> get_column(const int x0) const { return get_columns(x0,x0); } //! Return specified image column \inplace. CImg<T>& column(const int x0) { return columns(x0,x0); } //! Return specified range of image columns. /** \param x0 Starting image column. \param x1 Ending image column. **/ CImg<T>& columns(const int x0, const int x1) { return get_columns(x0,x1).move_to(*this); } //! Return specified range of image columns \inplace. CImg<T> get_columns(const int x0, const int x1) const { return get_crop(x0,0,0,0,x1,height()-1,depth()-1,spectrum()-1); } //! Return specified image row. CImg<T> get_row(const int y0) const { return get_rows(y0,y0); } //! Return specified image row \inplace. /** \param y0 Image row. **/ CImg<T>& row(const int y0) { return rows(y0,y0); } //! Return specified range of image rows. /** \param y0 Starting image row. \param y1 Ending image row. **/ CImg<T> get_rows(const int y0, const int y1) const { return get_crop(0,y0,0,0,width()-1,y1,depth()-1,spectrum()-1); } //! Return specified range of image rows \inplace. CImg<T>& rows(const int y0, const int y1) { return get_rows(y0,y1).move_to(*this); } //! Return specified image slice. /** \param z0 Image slice. **/ CImg<T> get_slice(const int z0) const { return get_slices(z0,z0); } //! Return specified image slice \inplace. CImg<T>& slice(const int z0) { return slices(z0,z0); } //! Return specified range of image slices. /** \param z0 Starting image slice. \param z1 Ending image slice. **/ CImg<T> get_slices(const int z0, const int z1) const { return get_crop(0,0,z0,0,width()-1,height()-1,z1,spectrum()-1); } //! Return specified range of image slices \inplace. CImg<T>& slices(const int z0, const int z1) { return get_slices(z0,z1).move_to(*this); } //! Return specified image channel. /** \param c0 Image channel. **/ CImg<T> get_channel(const int c0) const { return get_channels(c0,c0); } //! Return specified image channel \inplace. CImg<T>& channel(const int c0) { return channels(c0,c0); } //! Return specified range of image channels. /** \param c0 Starting image channel. \param c1 Ending image channel. **/ CImg<T> get_channels(const int c0, const int c1) const { return get_crop(0,0,0,c0,width()-1,height()-1,depth()-1,c1); } //! Return specified range of image channels \inplace. CImg<T>& channels(const int c0, const int c1) { return get_channels(c0,c1).move_to(*this); } //! Return stream line of a 2d or 3d vector field. CImg<floatT> get_streamline(const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false) const { if (_spectrum!=2 && _spectrum!=3) throw CImgInstanceException(_cimg_instance "streamline(): Instance is not a 2d or 3d vector field.", cimg_instance); if (_spectrum==2) { if (is_oriented_only) { typename CImg<T>::_functor4d_streamline2d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true,0,0,0,_width-1.0f,_height-1.0f,0.0f); } else { typename CImg<T>::_functor4d_streamline2d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false,0,0,0,_width-1.0f,_height-1.0f,0.0f); } } if (is_oriented_only) { typename CImg<T>::_functor4d_streamline3d_oriented func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,true,0,0,0,_width-1.0f,_height-1.0f,_depth-1.0f); } typename CImg<T>::_functor4d_streamline3d_directed func(*this); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,false,0,0,0,_width-1.0f,_height-1.0f,_depth-1.0f); } //! Return stream line of a 3d vector field. /** \param func Vector field function. \param x X-coordinate of the starting point of the streamline. \param y Y-coordinate of the starting point of the streamline. \param z Z-coordinate of the starting point of the streamline. \param L Streamline length. \param dl Streamline length increment. \param interpolation_type Type of interpolation. Can be <tt>{ 0=nearest int | 1=linear | 2=2nd-order RK | 3=4th-order RK. }</tt>. \param is_backward_tracking Tells if the streamline is estimated forward or backward. \param is_oriented_only Tells if the direction of the vectors must be ignored. \param x0 X-coordinate of the first bounding-box vertex. \param y0 Y-coordinate of the first bounding-box vertex. \param z0 Z-coordinate of the first bounding-box vertex. \param x1 X-coordinate of the second bounding-box vertex. \param y1 Y-coordinate of the second bounding-box vertex. \param z1 Z-coordinate of the second bounding-box vertex. **/ template<typename tfunc> static CImg<floatT> streamline(const tfunc& func, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=false, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { if (dl<=0) throw CImgArgumentException("CImg<%s>::streamline(): Invalid specified integration length %g " "(should be >0).", pixel_type(), dl); const bool is_bounded = (x0!=x1 || y0!=y1 || z0!=z1); if (L<=0 || (is_bounded && (x<x0 || x>x1 || y<y0 || y>y1 || z<z0 || z>z1))) return CImg<floatT>(); const unsigned int size_L = (unsigned int)cimg::round(L/dl+1); CImg<floatT> coordinates(size_L,3); const float dl2 = dl/2; float *ptr_x = coordinates.data(0,0), *ptr_y = coordinates.data(0,1), *ptr_z = coordinates.data(0,2), pu = (float)(dl*func(x,y,z,0)), pv = (float)(dl*func(x,y,z,1)), pw = (float)(dl*func(x,y,z,2)), X = x, Y = y, Z = z; switch (interpolation_type) { case 0 : { // Nearest integer interpolation. cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; const int xi = (int)(X>0?X+0.5f:X-0.5f), yi = (int)(Y>0?Y+0.5f:Y-0.5f), zi = (int)(Z>0?Z+0.5f:Z-0.5f); float u = (float)(dl*func((float)xi,(float)yi,(float)zi,0)), v = (float)(dl*func((float)xi,(float)yi,(float)zi,1)), w = (float)(dl*func((float)xi,(float)yi,(float)zi,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 1 : { // First-order interpolation. cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u = (float)(dl*func(X,Y,Z,0)), v = (float)(dl*func(X,Y,Z,1)), w = (float)(dl*func(X,Y,Z,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; case 2 : { // Second order interpolation. cimg_forX(coordinates,l) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u = (float)(dl*func(X+u0,Y+v0,Z+w0,0)), v = (float)(dl*func(X+u0,Y+v0,Z+w0,1)), w = (float)(dl*func(X+u0,Y+v0,Z+w0,2)); if (is_oriented_only && u*pu + v*pv + w*pw<0) { u = -u; v = -v; w = -w; } if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } break; default : { // Fourth order interpolation. cimg_forX(coordinates,x) { *(ptr_x++) = X; *(ptr_y++) = Y; *(ptr_z++) = Z; float u0 = (float)(dl2*func(X,Y,Z,0)), v0 = (float)(dl2*func(X,Y,Z,1)), w0 = (float)(dl2*func(X,Y,Z,2)); if (is_oriented_only && u0*pu + v0*pv + w0*pw<0) { u0 = -u0; v0 = -v0; w0 = -w0; } float u1 = (float)(dl2*func(X+u0,Y+v0,Z+w0,0)), v1 = (float)(dl2*func(X+u0,Y+v0,Z+w0,1)), w1 = (float)(dl2*func(X+u0,Y+v0,Z+w0,2)); if (is_oriented_only && u1*pu + v1*pv + w1*pw<0) { u1 = -u1; v1 = -v1; w1 = -w1; } float u2 = (float)(dl2*func(X+u1,Y+v1,Z+w1,0)), v2 = (float)(dl2*func(X+u1,Y+v1,Z+w1,1)), w2 = (float)(dl2*func(X+u1,Y+v1,Z+w1,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u2 = -u2; v2 = -v2; w2 = -w2; } float u3 = (float)(dl2*func(X+u2,Y+v2,Z+w2,0)), v3 = (float)(dl2*func(X+u2,Y+v2,Z+w2,1)), w3 = (float)(dl2*func(X+u2,Y+v2,Z+w2,2)); if (is_oriented_only && u2*pu + v2*pv + w2*pw<0) { u3 = -u3; v3 = -v3; w3 = -w3; } const float u = (u0 + u3)/3 + (u1 + u2)/1.5f, v = (v0 + v3)/3 + (v1 + v2)/1.5f, w = (w0 + w3)/3 + (w1 + w2)/1.5f; if (is_backward_tracking) { X-=(pu=u); Y-=(pv=v); Z-=(pw=w); } else { X+=(pu=u); Y+=(pv=v); Z+=(pw=w); } if (is_bounded && (X<x0 || X>x1 || Y<y0 || Y>y1 || Z<z0 || Z>z1)) break; } } } if (ptr_x!=coordinates.data(0,1)) coordinates.resize((int)(ptr_x-coordinates.data()),3,1,1,0); return coordinates; } //! Return stream line of a 3d vector field \overloading. static CImg<floatT> streamline(const char *const expression, const float x, const float y, const float z, const float L=256, const float dl=0.1f, const unsigned int interpolation_type=2, const bool is_backward_tracking=true, const bool is_oriented_only=false, const float x0=0, const float y0=0, const float z0=0, const float x1=0, const float y1=0, const float z1=0) { _functor4d_streamline_expr func(expression); return streamline(func,x,y,z,L,dl,interpolation_type,is_backward_tracking,is_oriented_only,x0,y0,z0,x1,y1,z1); } struct _functor4d_streamline2d_directed { const CImg<T>& ref; _functor4d_streamline2d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return c<2?(float)ref._linear_atXY(x,y,(int)z,c):0; } }; struct _functor4d_streamline3d_directed { const CImg<T>& ref; _functor4d_streamline3d_directed(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref._linear_atXYZ(x,y,z,c); } }; struct _functor4d_streamline2d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline2d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,1,2); } ~_functor4d_streamline2d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign2d(i,j) if (I(i,j,0)*I(0,0,0)+I(i,j,1)*I(0,0,1)<0) { I(i,j,0) = -I(i,j,0); I(i,j,1) = -I(i,j,1); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z; const float dx = x - xi, dy = y - yi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width()-1; if (nxi>=ref.width()) nxi = ref.width()-1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height()-1; if (nyi>=ref.height()) nyi = ref.height()-1; I(0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,1) = (float)ref(xi,yi,zi,1); I(1,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,1) = (float)ref(nxi,yi,zi,1); I(1,1,0) = (float)ref(nxi,nyi,zi,0); I(1,1,1) = (float)ref(nxi,nyi,zi,1); I(0,1,0) = (float)ref(xi,nyi,zi,0); I(0,1,1) = (float)ref(xi,nyi,zi,1); _cimg_vecalign2d(1,0); _cimg_vecalign2d(1,1); _cimg_vecalign2d(0,1); } return c<2?(float)pI->_linear_atXY(dx,dy,0,c):0; } }; struct _functor4d_streamline3d_oriented { const CImg<T>& ref; CImg<floatT> *pI; _functor4d_streamline3d_oriented(const CImg<T>& pref):ref(pref),pI(0) { pI = new CImg<floatT>(2,2,2,3); } ~_functor4d_streamline3d_oriented() { delete pI; } float operator()(const float x, const float y, const float z, const unsigned int c) const { #define _cimg_vecalign3d(i,j,k) if (I(i,j,k,0)*I(0,0,0,0)+I(i,j,k,1)*I(0,0,0,1)+I(i,j,k,2)*I(0,0,0,2)<0) { \ I(i,j,k,0) = -I(i,j,k,0); I(i,j,k,1) = -I(i,j,k,1); I(i,j,k,2) = -I(i,j,k,2); } int xi = (int)x - (x>=0?0:1), nxi = xi + 1, yi = (int)y - (y>=0?0:1), nyi = yi + 1, zi = (int)z - (z>=0?0:1), nzi = zi + 1; const float dx = x - xi, dy = y - yi, dz = z - zi; if (c==0) { CImg<floatT>& I = *pI; if (xi<0) xi = 0; if (nxi<0) nxi = 0; if (xi>=ref.width()) xi = ref.width()-1; if (nxi>=ref.width()) nxi = ref.width()-1; if (yi<0) yi = 0; if (nyi<0) nyi = 0; if (yi>=ref.height()) yi = ref.height()-1; if (nyi>=ref.height()) nyi = ref.height()-1; if (zi<0) zi = 0; if (nzi<0) nzi = 0; if (zi>=ref.depth()) zi = ref.depth()-1; if (nzi>=ref.depth()) nzi = ref.depth()-1; I(0,0,0,0) = (float)ref(xi,yi,zi,0); I(0,0,0,1) = (float)ref(xi,yi,zi,1); I(0,0,0,2) = (float)ref(xi,yi,zi,2); I(1,0,0,0) = (float)ref(nxi,yi,zi,0); I(1,0,0,1) = (float)ref(nxi,yi,zi,1); I(1,0,0,2) = (float)ref(nxi,yi,zi,2); I(1,1,0,0) = (float)ref(nxi,nyi,zi,0); I(1,1,0,1) = (float)ref(nxi,nyi,zi,1); I(1,1,0,2) = (float)ref(nxi,nyi,zi,2); I(0,1,0,0) = (float)ref(xi,nyi,zi,0); I(0,1,0,1) = (float)ref(xi,nyi,zi,1); I(0,1,0,2) = (float)ref(xi,yi,zi,2); I(0,0,0,1) = (float)ref(xi,yi,nzi,0); I(0,0,0,1) = (float)ref(xi,yi,nzi,1); I(0,0,0,2) = (float)ref(xi,yi,nzi,2); I(1,0,0,1) = (float)ref(nxi,yi,nzi,0); I(1,0,0,1) = (float)ref(nxi,yi,nzi,1); I(1,0,0,2) = (float)ref(nxi,yi,nzi,2); I(1,1,0,1) = (float)ref(nxi,nyi,nzi,0); I(1,1,0,1) = (float)ref(nxi,nyi,nzi,1); I(1,1,0,2) = (float)ref(nxi,nyi,nzi,2); I(0,1,0,1) = (float)ref(xi,nyi,nzi,0); I(0,1,0,1) = (float)ref(xi,nyi,nzi,1); I(0,1,0,2) = (float)ref(xi,yi,nzi,2); _cimg_vecalign3d(1,0,0); _cimg_vecalign3d(1,1,0); _cimg_vecalign3d(0,1,0); _cimg_vecalign3d(0,0,1); _cimg_vecalign3d(1,0,1); _cimg_vecalign3d(1,1,1); _cimg_vecalign3d(0,1,1); } return (float)pI->_linear_atXYZ(dx,dy,dz,c); } }; struct _functor4d_streamline_expr { _cimg_math_parser *mp; ~_functor4d_streamline_expr() { delete mp; } _functor4d_streamline_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(CImg<T>::empty(),expr,"streamline"); } float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)mp->eval(x,y,z,c); } }; //! Return a shared-memory image referencing a range of pixels of the image instance. /** \param x0 X-coordinate of the starting pixel. \param x1 X-coordinate of the ending pixel. \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data+beg,x1-x0+1,1,1,1,true); } //! Return a shared-memory image referencing a range of pixels of the image instance \const. const CImg<T> get_shared_points(const unsigned int x0, const unsigned int x1, const unsigned int y0=0, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = (unsigned int)offset(x0,y0,z0,c0), end = offset(x1,y0,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_points(): Invalid request of a shared-memory subset (%u->%u,%u,%u,%u).", cimg_instance, x0,x1,y0,z0,c0); return CImg<T>(_data+beg,x1-x0+1,1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance. /** \param y0 Y-coordinate of the starting row. \param y1 Y-coordinate of the ending row. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) { const unsigned int beg = offset(0,y0,z0,c0), end = offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset (0->%u,%u->%u,%u,%u).", cimg_instance, _width-1,y0,y1,z0,c0); return CImg<T>(_data+beg,_width,y1-y0+1,1,1,true); } //! Return a shared-memory image referencing a range of rows of the image instance \const. const CImg<T> get_shared_rows(const unsigned int y0, const unsigned int y1, const unsigned int z0=0, const unsigned int c0=0) const { const unsigned int beg = offset(0,y0,z0,c0), end = offset(0,y1,z0,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_rows(): Invalid request of a shared-memory subset (0->%u,%u->%u,%u,%u).", cimg_instance, _width-1,y0,y1,z0,c0); return CImg<T>(_data+beg,_width,y1-y0+1,1,1,true); } //! Return a shared-memory image referencing one row of the image instance. /** \param y0 Y-coordinate. \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared-memory image referencing one row of the image instance \const. const CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const { return get_shared_rows(y0,y0,z0,c0); } //! Return a shared memory image referencing a range of slices of the image instance. /** \param z0 Z-coordinate of the starting slice. \param z1 Z-coordinate of the ending slice. \param c0 C-coordinate. **/ CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) { const unsigned int beg = offset(0,0,z0,c0), end = offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset (0->%u,0->%u,%u->%u,%u).", cimg_instance, _width-1,_height-1,z0,z1,c0); return CImg<T>(_data+beg,_width,_height,z1-z0+1,1,true); } //! Return a shared memory image referencing a range of slices of the image instance \const. const CImg<T> get_shared_slices(const unsigned int z0, const unsigned int z1, const unsigned int c0=0) const { const unsigned int beg = offset(0,0,z0,c0), end = offset(0,0,z1,c0); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_slices(): Invalid request of a shared-memory subset (0->%u,0->%u,%u->%u,%u).", cimg_instance, _width-1,_height-1,z0,z1,c0); return CImg<T>(_data+beg,_width,_height,z1-z0+1,1,true); } //! Return a shared-memory image referencing one slice of the image instance. /** \param z0 Z-coordinate. \param c0 C-coordinate. **/ CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing one slice of the image instance \const. const CImg<T> get_shared_slice(const unsigned int z0, const unsigned int c0=0) const { return get_shared_slices(z0,z0,c0); } //! Return a shared-memory image referencing a range of channels of the image instance. /** \param c0 C-coordinate of the starting channel. \param c1 C-coordinate of the ending channel. **/ CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) { const unsigned int beg = offset(0,0,0,c0), end = offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset (0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width-1,_height-1,_depth-1,c0,c1); return CImg<T>(_data+beg,_width,_height,_depth,c1-c0+1,true); } //! Return a shared-memory image referencing a range of channels of the image instance \const. const CImg<T> get_shared_channels(const unsigned int c0, const unsigned int c1) const { const unsigned int beg = offset(0,0,0,c0), end = offset(0,0,0,c1); if (beg>end || beg>=size() || end>=size()) throw CImgArgumentException(_cimg_instance "get_shared_channels(): Invalid request of a shared-memory subset (0->%u,0->%u,0->%u,%u->%u).", cimg_instance, _width-1,_height-1,_depth-1,c0,c1); return CImg<T>(_data+beg,_width,_height,_depth,c1-c0+1,true); } //! Return a shared-memory image referencing one channel of the image instance. /** \param c0 C-coordinate. **/ CImg<T> get_shared_channel(const unsigned int c0) { return get_shared_channels(c0,c0); } //! Return a shared-memory image referencing one channel of the image instance \const. const CImg<T> get_shared_channel(const unsigned int c0) const { return get_shared_channels(c0,c0); } //! Return a shared-memory version of the image instance. CImg<T> get_shared() { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Return a shared-memory version of the image instance \const. const CImg<T> get_shared() const { return CImg<T>(_data,_width,_height,_depth,_spectrum,true); } //! Split image into a list along specified axis. /** \param axis Splitting axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param nb Number of splitted parts. \note - If \c nb==0, there are as much splitted parts as the image size along the specified axis. - If \c nb<=0, instance image is splitted into blocs of -\c nb pixel wide. - If \c nb>0, instance image is splitted into \c nb blocs. **/ CImgList<T> get_split(const char axis, const int nb=0) const { CImgList<T> res; const char _axis = cimg::uncase(axis); if (nb<=0) { // Split by bloc size. const unsigned int dp = (unsigned int)(nb?-nb:1); int p = 0; switch (_axis) { case 'x': { for (int pe=_width-dp; p<pe; p+=dp) get_crop(p,0,0,0,p+dp-1,_height-1,_depth-1,_spectrum-1).move_to(res); get_crop(p,0,0,0,_width-1,_height-1,_depth-1,_spectrum-1).move_to(res); } break; case 'y': { for (int pe=_height-dp; p<pe; p+=dp) get_crop(0,p,0,0,_width-1,p+dp-1,_depth-1,_spectrum-1).move_to(res); get_crop(0,p,0,0,_width-1,_height-1,_depth-1,_spectrum-1).move_to(res); } break; case 'z': { for (int pe=_depth-dp; p<pe; p+=dp) get_crop(0,0,p,0,_width-1,_height-1,p+dp-1,_spectrum-1).move_to(res); get_crop(0,0,p,0,_width-1,_height-1,_depth-1,_spectrum-1).move_to(res); } break; default : { for (int pe=_spectrum-dp; p<pe; p+=dp) get_crop(0,0,0,p,_width-1,_height-1,_depth-1,p+dp-1).move_to(res); get_crop(0,0,0,p,_width-1,_height-1,_depth-1,_spectrum-1).move_to(res); } } } else { // Split by number of (non-homogeneous) blocs. const unsigned int siz = _axis=='x'?_width:_axis=='y'?_height:_axis=='z'?_depth:_axis=='c'?_spectrum:0; if ((unsigned int)nb>siz) throw CImgArgumentException(_cimg_instance "get_split(): Instance cannot be split along %c-axis into %u blocs.", cimg_instance, axis,nb); int err = (int)siz; unsigned int _p = 0; switch (_axis) { case 'x' : { cimg_forX(*this,p) if ((err-=nb)<=0) { get_crop(_p,0,0,0,p,_height-1,_depth-1,_spectrum-1).move_to(res); err+=(int)siz; _p=p+1; } } break; case 'y' : { cimg_forY(*this,p) if ((err-=nb)<=0) { get_crop(0,_p,0,0,_width-1,p,_depth-1,_spectrum-1).move_to(res); err+=(int)siz; _p=p+1; } } break; case 'z' : { cimg_forZ(*this,p) if ((err-=nb)<=0) { get_crop(0,0,_p,0,_width-1,_height-1,p,_spectrum-1).move_to(res); err+=(int)siz; _p=p+1; } } break; default : { cimg_forC(*this,p) if ((err-=nb)<=0) { get_crop(0,0,0,_p,_width-1,_height-1,_depth-1,p).move_to(res); err+=(int)siz; _p=p+1; } } } } return res; } //! Split image into a list of one-column vectors, according to a specified splitting value. /** \param value Splitting value. \param keep_values Tells if the splitting value must be kept in the splitted blocs. \param is_shared Tells if the splitted blocs have shared memory buffers. **/ CImgList<T> get_split(const T value, const bool keep_values, const bool is_shared) const { CImgList<T> res; for (const T *ps = _data, *_ps = ps, *const pe = end(); ps<pe; ) { while (_ps<pe && *_ps==value) ++_ps; unsigned int siz = _ps - ps; if (siz && keep_values) res.insert(CImg<T>(ps,1,siz,1,1,is_shared),~0U,is_shared); ps = _ps; while (_ps<pe && *_ps!=value) ++_ps; siz = _ps - ps; if (siz) res.insert(CImg<T>(ps,1,siz,1,1,is_shared),~0U,is_shared); ps = _ps; } return res; } //! Split image into a list of one-column vectors, according to a specified splitting value sequence. /** \param values Splitting value sequence. \param keep_values Tells if the splitting sequence must be kept in the splitted blocs. \param is_shared Tells if the splitted blocs have shared memory buffers. **/ template<typename t> CImgList<T> get_split(const CImg<t>& values, const bool keep_values, const bool is_shared) const { if (!values) return CImgList<T>(*this); if (values.size()==1) return get_split(*values,keep_values,is_shared); CImgList<T> res; const t *pve = values.end(); for (const T *ps = _data, *_ps = ps, *const pe = end(); ps<pe; ) { // Try to find match from current position. const t *pv = 0; do { pv = values._data; const T *__ps = _ps; while (__ps<pe && pv<pve && *__ps==(T)*pv) { ++__ps; ++pv; } if (pv==pve) _ps = __ps; } while (pv==pve); unsigned int siz = _ps - ps; if (siz && keep_values) res.insert(CImg<T>(ps,1,siz,1,1,is_shared),~0U,is_shared); // If match found. ps = _ps; // Try to find non-match from current position. do { pv = values._data; while (_ps<pe && *_ps!=(T)*pv) ++_ps; if (_ps<pe) { const T *__ps = _ps + 1; ++pv; while (__ps<pe && pv<pve && *__ps==(T)*pv) { ++__ps; ++pv; } if (pv!=pve) _ps = __ps; } } while (_ps<pe && pv!=pve); // Here, EOF of match found. siz = _ps - ps; if (siz) res.insert(CImg<T>(ps,1,siz,1,1,is_shared),~0U,is_shared); ps = _ps; } return res; } //! Append two images along specified axis. /** \param img Image to append with instance image. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Append alignment in \c [0,1]. **/ template<typename t> CImg<T>& append(const CImg<t>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,true).insert(img).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \specialization. CImg<T>& append(const CImg<T>& img, const char axis='x', const float align=0) { if (is_empty()) return assign(img,false); if (!img) return *this; return CImgList<T>(*this,img,true).get_append(axis,align).move_to(*this); } //! Append two images along specified axis \const. template<typename t> CImg<_cimg_Tt> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<_cimg_Tt>(*this,true).insert(img).get_append(axis,align); } //! Append two images along specified axis \specialization. CImg<T> get_append(const CImg<T>& img, const char axis='x', const float align=0) const { if (is_empty()) return +img; if (!img) return +*this; return CImgList<T>(*this,img,true).get_append(axis,align); } //@} //--------------------------------------- // //! \name Filtering / Transforms //@{ //--------------------------------------- //! Correlate image by a mask. /** \param mask = the correlation kernel. \param boundary_conditions = the border condition type (0=zero, 1=dirichlet) \param is_normalized = enable local normalization. \note The correlation of the image instance \p *this by the mask \p mask is defined to be: res(x,y,z) = sum_{i,j,k} (*this)(x+i,y+j,z+k)*mask(i,j,k) **/ template<typename t> CImg<T>& correlate(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) { if (is_empty() || !mask) return *this; return get_correlate(mask,boundary_conditions,is_normalized).move_to(*this); } //! Correlate image by a mask \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_correlate(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) const { if (is_empty() || !mask) return *this; typedef _cimg_Ttfloat Ttfloat; CImg<Ttfloat> res(_width,_height,_depth,cimg::max(_spectrum,mask._spectrum)); if (boundary_conditions && mask._width==mask._height && ((mask._depth==1 && mask._width<=5) || (mask._depth==mask._width && mask._width<=3))) { // A special optimization is done for 2x2, 3x3, 4x4, 5x5, 2x2x2 and 3x3x3 mask (with boundary_conditions=1) Ttfloat *ptrd = res._data; switch (mask._depth) { case 3 : { T I[27] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_for3x3x3(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[ 0]*I[ 0] + I[ 1]*I[ 1] + I[ 2]*I[ 2] + I[ 3]*I[ 3] + I[ 4]*I[ 4] + I[ 5]*I[ 5] + I[ 6]*I[ 6] + I[ 7]*I[ 7] + I[ 8]*I[ 8] + I[ 9]*I[ 9] + I[10]*I[10] + I[11]*I[11] + I[12]*I[12] + I[13]*I[13] + I[14]*I[14] + I[15]*I[15] + I[16]*I[16] + I[17]*I[17] + I[18]*I[18] + I[19]*I[19] + I[20]*I[20] + I[21]*I[21] + I[22]*I[22] + I[23]*I[23] + I[24]*I[24] + I[25]*I[25] + I[26]*I[26]); *(ptrd++) = (Ttfloat)(N?(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24] + I[25]*_mask[25] + I[26]*_mask[26])/std::sqrt(N):0); } } else cimg_for3x3x3(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24] + I[25]*_mask[25] + I[26]*_mask[26]); } } break; case 2 : { T I[8] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_for2x2x2(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[0]*I[0] + I[1]*I[1] + I[2]*I[2] + I[3]*I[3] + I[4]*I[4] + I[5]*I[5] + I[6]*I[6] + I[7]*I[7]); *(ptrd++) = (Ttfloat)(N?(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3] + I[4]*_mask[4] + I[5]*_mask[5] + I[6]*_mask[6] + I[7]*_mask[7])/std::sqrt(N):0); } } else cimg_for2x2x2(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3] + I[4]*_mask[4] + I[5]*_mask[5] + I[6]*_mask[6] + I[7]*_mask[7]); } } break; default : case 1 : switch (mask._width) { case 6 : { T I[36] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_forZ(_img,z) cimg_for6x6(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[ 0]*I[ 0] + I[ 1]*I[ 1] + I[ 2]*I[ 2] + I[ 3]*I[ 3] + I[ 4]*I[ 4] + I[ 5]*I[ 5] + I[ 6]*I[ 6] + I[ 7]*I[ 7] + I[ 8]*I[ 8] + I[ 9]*I[ 9] + I[10]*I[10] + I[11]*I[11] + I[12]*I[12] + I[13]*I[13] + I[14]*I[14] + I[15]*I[15] + I[16]*I[16] + I[17]*I[17] + I[18]*I[18] + I[19]*I[19] + I[20]*I[20] + I[21]*I[21] + I[22]*I[22] + I[23]*I[23] + I[24]*I[24] + I[25]*I[25] + I[26]*I[26] + I[27]*I[27] + I[28]*I[28] + I[29]*I[29] + I[30]*I[30] + I[31]*I[31] + I[32]*I[32] + I[33]*I[33] + I[34]*I[34] + I[35]*I[35]); *(ptrd++) = (Ttfloat)(N?(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24] + I[25]*_mask[25] + I[26]*_mask[26] + I[27]*_mask[27] + I[28]*_mask[28] + I[29]*_mask[29] + I[30]*_mask[30] + I[31]*_mask[31] + I[32]*_mask[32] + I[33]*_mask[33] + I[34]*_mask[34] + I[35]*_mask[35])/std::sqrt(N):0); } } else cimg_forZ(_img,z) cimg_for6x6(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24] + I[25]*_mask[25] + I[26]*_mask[26] + I[27]*_mask[27] + I[28]*_mask[28] + I[29]*_mask[29] + I[30]*_mask[30] + I[31]*_mask[31] + I[32]*_mask[32] + I[33]*_mask[33] + I[34]*_mask[34] + I[35]*_mask[35]); } } break; case 5 : { T I[25] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_forZ(_img,z) cimg_for5x5(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[ 0]*I[ 0] + I[ 1]*I[ 1] + I[ 2]*I[ 2] + I[ 3]*I[ 3] + I[ 4]*I[ 4] + I[ 5]*I[ 5] + I[ 6]*I[ 6] + I[ 7]*I[ 7] + I[ 8]*I[ 8] + I[ 9]*I[ 9] + I[10]*I[10] + I[11]*I[11] + I[12]*I[12] + I[13]*I[13] + I[14]*I[14] + I[15]*I[15] + I[16]*I[16] + I[17]*I[17] + I[18]*I[18] + I[19]*I[19] + I[20]*I[20] + I[21]*I[21] + I[22]*I[22] + I[23]*I[23] + I[24]*I[24]); *(ptrd++) = (Ttfloat)(N?(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24])/std::sqrt(N):0); } } else cimg_forZ(_img,z) cimg_for5x5(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15] + I[16]*_mask[16] + I[17]*_mask[17] + I[18]*_mask[18] + I[19]*_mask[19] + I[20]*_mask[20] + I[21]*_mask[21] + I[22]*_mask[22] + I[23]*_mask[23] + I[24]*_mask[24]); } } break; case 4 : { T I[16] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_forZ(_img,z) cimg_for4x4(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[ 0]*I[ 0] + I[ 1]*I[ 1] + I[ 2]*I[ 2] + I[ 3]*I[ 3] + I[ 4]*I[ 4] + I[ 5]*I[ 5] + I[ 6]*I[ 6] + I[ 7]*I[ 7] + I[ 8]*I[ 8] + I[ 9]*I[ 9] + I[10]*I[10] + I[11]*I[11] + I[12]*I[12] + I[13]*I[13] + I[14]*I[14] + I[15]*I[15]); *(ptrd++) = (Ttfloat)(N?(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15])/std::sqrt(N):0); } } else cimg_forZ(_img,z) cimg_for4x4(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[ 0]*_mask[ 0] + I[ 1]*_mask[ 1] + I[ 2]*_mask[ 2] + I[ 3]*_mask[ 3] + I[ 4]*_mask[ 4] + I[ 5]*_mask[ 5] + I[ 6]*_mask[ 6] + I[ 7]*_mask[ 7] + I[ 8]*_mask[ 8] + I[ 9]*_mask[ 9] + I[10]*_mask[10] + I[11]*_mask[11] + I[12]*_mask[12] + I[13]*_mask[13] + I[14]*_mask[14] + I[15]*_mask[15]); } } break; case 3 : { T I[9] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_forZ(_img,z) cimg_for3x3(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[0]*I[0] + I[1]*I[1] + I[2]*I[2] + I[3]*I[3] + I[4]*I[4] + I[5]*I[5] + I[6]*I[6] + I[7]*I[7] + I[8]*I[8]); *(ptrd++) = (Ttfloat)(N?(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3] + I[4]*_mask[4] + I[5]*_mask[5] + I[6]*_mask[6] + I[7]*_mask[7] + I[8]*_mask[8])/std::sqrt(N):0); } } else cimg_forZ(_img,z) cimg_for3x3(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3] + I[4]*_mask[4] + I[5]*_mask[5] + I[6]*_mask[6] + I[7]*_mask[7] + I[8]*_mask[8]); } } break; case 2 : { T I[4] = { 0 }; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; cimg_forZ(_img,z) cimg_for2x2(_img,x,y,z,0,I,T) { const Ttfloat N = M*(I[0]*I[0] + I[1]*I[1] + I[2]*I[2] + I[3]*I[3]); *(ptrd++) = (Ttfloat)(N?(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3])/std::sqrt(N):0); } } else cimg_forZ(_img,z) cimg_for2x2(_img,x,y,z,0,I,T) *(ptrd++) = (Ttfloat)(I[0]*_mask[0] + I[1]*_mask[1] + I[2]*_mask[2] + I[3]*_mask[3]); } } break; case 1 : if (is_normalized) res.fill(1); else cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); res.get_shared_channel(c).assign(_img)*=_mask[0]; } break; } } } else { // Generic version for other masks and borders conditions. const int mx2 = mask.width()/2, my2 = mask.height()/2, mz2 = mask.depth()/2, mx1 = mx2 - 1 + (mask.width()%2), my1 = my2 - 1 + (mask.height()%2), mz1 = mz2 - 1 + (mask.depth()%2), mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; cimg_forC(res,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { // Normalized correlation. const Ttfloat _M = (Ttfloat)_mask.magnitude(2), M = _M*_M; for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)_img(x+xm,y+ym,z+zm); val+=_val*_mask(mx1+xm,my1+ym,mz1+zm); N+=_val*_val; } N*=M; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)_img._atXYZ(x+xm,y+ym,z+zm); val+=_val*_mask(mx1+xm,my1+ym,mz1+zm); N+=_val*_val; } N*=M; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } else cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0, N = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Ttfloat _val = (Ttfloat)_img.atXYZ(x+xm,y+ym,z+zm,0,0); val+=_val*_mask(mx1+xm,my1+ym,mz1+zm); N+=_val*_val; } N*=M; res(x,y,z,c) = (Ttfloat)(N?val/std::sqrt(N):0); } } else { // Classical correlation. for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=_img(x+xm,y+ym,z+zm)*_mask(mx1+xm,my1+ym,mz1+zm); res(x,y,z,c) = (Ttfloat)val; } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=_img._atXYZ(x+xm,y+ym,z+zm)*_mask(mx1+xm,my1+ym,mz1+zm); res(x,y,z,c) = (Ttfloat)val; } else cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Ttfloat val = 0; for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) val+=_img.atXYZ(x+xm,y+ym,z+zm,0,0)*_mask(mx1+xm,my1+ym,mz1+zm); res(x,y,z,c) = (Ttfloat)val; } } } } return res; } //! Convolve image by a mask. /** \param mask = the correlation kernel. \param boundary_conditions = the border condition type (0=zero, 1=dirichlet) \param is_normalized = enable local normalization. \note The result \p res of the convolution of an image \p img by a mask \p mask is defined to be: res(x,y,z) = sum_{i,j,k} img(x-i,y-j,z-k)*mask(i,j,k) **/ template<typename t> CImg<T>& convolve(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) { if (is_empty() || !mask) return *this; return get_convolve(mask,boundary_conditions,is_normalized).move_to(*this); } //! Convolve image by a mask \newinstance. template<typename t> CImg<_cimg_Ttfloat> get_convolve(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) const { if (is_empty() || !mask) return *this; return get_correlate(CImg<t>(mask._data,mask.size(),1,1,1,true).get_mirror('x').resize(mask,-1),boundary_conditions,is_normalized); } //! Erode image by a structuring element. /** \param mask Structuring element. \param boundary_conditions Boundary conditions. \param is_normalized Tells if the erosion is locally normalized. **/ template<typename t> CImg<T>& erode(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) { if (is_empty() || !mask) return *this; return get_erode(mask,boundary_conditions,is_normalized).move_to(*this); } //! Erode image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_erode(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) const { if (is_empty() || !mask) return *this; typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,cimg::max(_spectrum,mask._spectrum)); const int mx2 = mask.width()/2, my2 = mask.height()/2, mz2 = mask.depth()/2, mx1 = mx2 - 1 + (mask.width()%2), my1 = my2 - 1 + (mask.height()%2), mz1 = mz2 - 1 + (mask.depth()%2), mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; cimg_forC(*this,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { // Normalized erosion. for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img(x+xm,y+ym,z+zm) + mval); if (mval && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img._atXYZ(x+xm,y+ym,z+zm) + mval); if (mval && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } else cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img.atXYZ(x+xm,y+ym,z+zm,0,0) + mval); if (mval && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } else { // Classical erosion. for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Tt cval = (Tt)_img(x+xm,y+ym,z+zm); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const T cval = (Tt)_img._atXYZ(x+xm,y+ym,z+zm); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } else cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt min_val = cimg::type<Tt>::max(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const T cval = (Tt)_img.atXYZ(x+xm,y+ym,z+zm,0,0); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval<min_val) min_val = cval; } res(x,y,z,c) = min_val; } } } return res; } //! Erode image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis. const int L = width(), off = 1, s = (int)sx, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forYZC(*this,y,z,c) { const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } if (sy>1 && _height>1) { // Along Y-axis. const int L = height(), off = width(), s = (int)sy, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forXZC(*this,x,z,c) { const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } if (sz>1 && _depth>1) { // Along Z-axis. const int L = depth(), off = width()*height(), s = (int)sz, _s1 = s/2, _s2 = s - _s1, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forXYC(*this,x,y,c) { const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val<=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val<=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval<cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval<cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val<=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val<cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val<cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } return *this; } //! Erode image by a rectangular structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).erode(sx,sy,sz); } //! Erode the image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& erode(const unsigned int s) { return erode(s,s,s); } //! Erode the image by a square structuring element of specified size \newinstance. CImg<T> get_erode(const unsigned int s) const { return (+*this).erode(s); } //! Dilate image by a structuring element. /** \param mask Structuring element. \param boundary_conditions Boundary conditions. \param is_normalized Tells if the erosion is locally normalized. **/ template<typename t> CImg<T>& dilate(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) { if (is_empty() || !mask) return *this; return get_dilate(mask,boundary_conditions,is_normalized).move_to(*this); } //! Dilate image by a structuring element \newinstance. template<typename t> CImg<_cimg_Tt> get_dilate(const CImg<t>& mask, const unsigned int boundary_conditions=1, const bool is_normalized=false) const { if (is_empty() || !mask) return *this; typedef _cimg_Tt Tt; CImg<Tt> res(_width,_height,_depth,_spectrum); const int mx2 = mask.width()/2, my2 = mask.height()/2, mz2 = mask.depth()/2, mx1 = mx2 - 1 + (mask.width()%2), my1 = my2 - 1 + (mask.height()%2), mz1 = mz2 - 1 + (mask.depth()%2), mxe = width() - mx2, mye = height() - my2, mze = depth() - mz2; cimg_forC(*this,c) { const CImg<T> _img = get_shared_channel(c%_spectrum); const CImg<t> _mask = mask.get_shared_channel(c%mask._spectrum); if (is_normalized) { // Normalized dilation. for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img(x+xm,y+ym,z+zm) - mval); if (mval && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img._atXYZ(x+xm,y+ym,z+zm) - mval); if (mval && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } else cimg_forYZ(*this,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const t mval = _mask(mx1+xm,my1+ym,mz1+zm); const Tt cval = (Tt)(_img.atXYZ(x+xm,y+ym,z+zm,0,0) - mval); if (mval && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } else { // Classical dilation. for (int z = mz1; z<mze; ++z) for (int y = my1; y<mye; ++y) for (int x = mx1; x<mxe; ++x) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const Tt cval = (Tt)_img(x+xm,y+ym,z+zm); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } if (boundary_conditions) cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const T cval = (Tt)_img._atXYZ(x+xm,y+ym,z+zm); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } else cimg_forYZ(res,y,z) for (int x = 0; x<width(); (y<my1 || y>=mye || z<mz1 || z>=mze)?++x:((x<mx1-1 || x>=mxe)?++x:(x=mxe))) { Tt max_val = cimg::type<Tt>::min(); for (int zm = -mz1; zm<=mz2; ++zm) for (int ym = -my1; ym<=my2; ++ym) for (int xm = -mx1; xm<=mx2; ++xm) { const T cval = (Tt)_img.atXYZ(x+xm,y+ym,z+zm,0,0); if (_mask(mx1+xm,my1+ym,mz1+zm) && cval>max_val) max_val = cval; } res(x,y,z,c) = max_val; } } } return res; } //! Dilate image by a rectangular structuring element of specified size. /** \param sx Width of the structuring element. \param sy Height of the structuring element. \param sz Depth of the structuring element. **/ CImg<T>& dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) { if (is_empty() || (sx==1 && sy==1 && sz==1)) return *this; if (sx>1 && _width>1) { // Along X-axis. const int L = width(), off = 1, s = (int)sx, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forYZC(*this,y,z,c) { const T *const ptrsb = data(0,y,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(0,y,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } if (sy>1 && _height>1) { // Along Y-axis. const int L = height(), off = width(), s = (int)sy, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forXZC(*this,x,z,c) { const T *const ptrsb = data(x,0,z,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,0,z,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } if (sz>1 && _depth>1) { // Along Z-axis. const int L = depth(), off = width()*height(), s = (int)sz, _s2 = s/2 + 1, _s1 = s - _s2, s1 = _s1>L?L:_s1, s2 = _s2>L?L:_s2; CImg<T> buf(L); T *const ptrdb = buf._data, *ptrd = ptrdb, *const ptrde = buf._data + L - 1; cimg_forXYC(*this,x,y,c) { const T *const ptrsb = data(x,y,0,c), *ptrs = ptrsb, *const ptrse = ptrs + L*off - off; ptrd = buf._data; T cur = *ptrs; ptrs+=off; bool is_first = true; for (int p = s2-1; p>0 && ptrs<=ptrse; --p) { const T val = *ptrs; ptrs+=off; if (val>=cur) { cur = val; is_first = false; }} *(ptrd++) = cur; for (int p = s1; p>0 && ptrd<=ptrde; --p) { const T val = *ptrs; if (ptrs<ptrse) ptrs+=off; if (val>=cur) { cur = val; is_first = false; } *(ptrd++) = cur; } for (int p = L - s - 1; p>0; --p) { const T val = *ptrs; ptrs+=off; if (is_first) { const T *nptrs = ptrs - off; cur = val; for (int q = s - 2; q>0; --q) { nptrs-=off; const T nval = *nptrs; if (nval>cur) cur = nval; } nptrs-=off; const T nval = *nptrs; if (nval>cur) { cur = nval; is_first = true; } else is_first = false; } else { if (val>=cur) cur = val; else if (cur==*(ptrs-s*off)) is_first = true; } *(ptrd++) = cur; } ptrd = ptrde; ptrs = ptrse; cur = *ptrs; ptrs-=off; for (int p = s1; p>0 && ptrs>=ptrsb; --p) { const T val = *ptrs; ptrs-=off; if (val>cur) cur = val; } *(ptrd--) = cur; for (int p = s2-1; p>0 && ptrd>=ptrdb; --p) { const T val = *ptrs; if (ptrs>ptrsb) ptrs-=off; if (val>cur) cur = val; *(ptrd--) = cur; } T *pd = data(x,y,0,c); cimg_for(buf,ps,T) { *pd = *ps; pd+=off; } } } return *this; } //! Dilate image by a rectangular structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int sx, const unsigned int sy, const unsigned int sz=1) const { return (+*this).dilate(sx,sy,sz); } //! Dilate image by a square structuring element of specified size. /** \param s Size of the structuring element. **/ CImg<T>& dilate(const unsigned int s) { return dilate(s,s,s); } //! Dilate image by a square structuring element of specified size \newinstance. CImg<T> get_dilate(const unsigned int s) const { return (+*this).dilate(s); } //! Compute watershed transform. /** \param priority Priority map. \param fill_lines Tells if watershed lines must be filled or not. \note Non-zero values of the instance instance are propagated to zero-valued ones according to specified the priority map. **/ template<typename t> CImg<T>& watershed(const CImg<t>& priority, const bool fill_lines=true) { if (is_empty()) return *this; if (!is_sameXYZ(priority)) throw CImgArgumentException(_cimg_instance "watershed(): image instance and specified priority (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance,priority._width,priority._height,priority._depth,priority._spectrum,priority._data); if (_spectrum!=1) { cimg_forC(*this,c) get_shared_channel(c).watershed(priority.get_shared_channel(c%priority._spectrum),fill_lines); return *this; } CImg<boolT> in_queue(_width,_height,_depth,1,0); CImg<typename cimg::superset2<T,t,int>::type> Q; unsigned int sizeQ = 0; // Find seed points and insert them in priority queue. const T *ptrs = _data; cimg_forXYZ(*this,x,y,z) if (*(ptrs++)) { if (x-1>=0 && !(*this)(x-1,y,z)) Q._priority_queue_insert(in_queue,sizeQ,priority(x-1,y,z),x-1,y,z); if (x+1<width() && !(*this)(x+1,y,z)) Q._priority_queue_insert(in_queue,sizeQ,priority(x+1,y,z),x+1,y,z); if (y-1>=0 && !(*this)(x,y-1,z)) Q._priority_queue_insert(in_queue,sizeQ,priority(x,y-1,z),x,y-1,z); if (y+1<height() && !(*this)(x,y+1,z)) Q._priority_queue_insert(in_queue,sizeQ,priority(x,y+1,z),x,y+1,z); if (z-1>=0 && !(*this)(x,y,z-1)) Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z-1),x,y,z-1); if (z+1<depth() && !(*this)(x,y,z+1)) Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z+1),x,y,z+1); } // Start watershed computation. while (sizeQ) { // Get and remove point with maximal priority from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); Q._priority_queue_remove(sizeQ); // Check labels of the neighbors. bool is_same_label = true; unsigned int label = 0; if (x-1>=0) { if ((*this)(x-1,y,z)) { if (!label) label = (unsigned int)(*this)(x-1,y,z); else if (label!=(*this)(x-1,y,z)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x-1,y,z),x-1,y,z); } if (x+1<width()) { if ((*this)(x+1,y,z)) { if (!label) label = (unsigned int)(*this)(x+1,y,z); else if (label!=(*this)(x+1,y,z)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x+1,y,z),x+1,y,z); } if (y-1>=0) { if ((*this)(x,y-1,z)) { if (!label) label = (unsigned int)(*this)(x,y-1,z); else if (label!=(*this)(x,y-1,z)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y-1,z),x,y-1,z); } if (y+1<height()) { if ((*this)(x,y+1,z)) { if (!label) label = (unsigned int)(*this)(x,y+1,z); else if (label!=(*this)(x,y+1,z)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y+1,z),x,y+1,z); } if (z-1>=0) { if ((*this)(x,y,z-1)) { if (!label) label = (unsigned int)(*this)(x,y,z-1); else if (label!=(*this)(x,y,z-1)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z-1),x,y,z-1); } if (z+1<depth()) { if ((*this)(x,y,z+1)) { if (!label) label = (unsigned int)(*this)(x,y,z+1); else if (label!=(*this)(x,y,z+1)) is_same_label = false; } else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z+1),x,y,z+1); } if (is_same_label) (*this)(x,y,z) = label; } // Fill lines. if (fill_lines) { // Sort all non-labeled pixels with labeled neighbors. in_queue = false; const T *ptrs = _data; cimg_forXYZ(*this,x,y,z) if (!*(ptrs++) && ((x-1>=0 && (*this)(x-1,y,z)) || (x+1<width() && (*this)(x+1,y,z)) || (y-1>=0 && (*this)(x,y-1,z)) || (y+1<height() && (*this)(x,y+1,z)) || (z-1>=0 && (*this)(x,y,z-1)) || (z+1>depth() && (*this)(x,y,z+1)))) Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z),x,y,z); // Start line filling process. while (sizeQ) { const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); Q._priority_queue_remove(sizeQ); t pmax = cimg::type<t>::min(); int xmax = 0, ymax = 0, zmax = 0; if (x-1>=0) { if ((*this)(x-1,y,z)) { if (priority(x-1,y,z)>pmax) { pmax = priority(x-1,y,z); xmax = x-1; ymax = y; zmax = z; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x-1,y,z),x-1,y,z); } if (x+1<width()) { if ((*this)(x+1,y,z)) { if (priority(x+1,y,z)>pmax) { pmax = priority(x+1,y,z); xmax = x+1; ymax = y; zmax = z; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x+1,y,z),x+1,y,z); } if (y-1>=0) { if ((*this)(x,y-1,z)) { if (priority(x,y-1,z)>pmax) { pmax = priority(x,y-1,z); xmax = x; ymax = y-1; zmax = z; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y-1,z),x,y-1,z); } if (y+1<height()) { if ((*this)(x,y+1,z)) { if (priority(x,y+1,z)>pmax) { pmax = priority(x,y+1,z); xmax = x; ymax = y+1; zmax = z; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y+1,z),x,y+1,z); } if (z-1>=0) { if ((*this)(x,y,z-1)) { if (priority(x,y,z-1)>pmax) { pmax = priority(x,y,z-1); xmax = x; ymax = y; zmax = z-1; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z-1),x,y,z-1); } if (z+1<depth()) { if ((*this)(x,y,z+1)) { if (priority(x,y,z+1)>pmax) { pmax = priority(x,y,z+1); xmax = x; ymax = y; zmax = z+1; }} else Q._priority_queue_insert(in_queue,sizeQ,priority(x,y,z+1),x,y,z+1); } (*this)(x,y,z) = (*this)(xmax,ymax,zmax); } } return *this; } //! Compute watershed transform \newinstance. template<typename t> CImg<T> get_watershed(const CImg<t>& priority, const bool fill_lines=true) const { return (+*this).watershed(priority,fill_lines); } // [internal] Insert/Remove items in priority queue, for watershed/distance transforms. template<typename t> bool _priority_queue_insert(CImg<boolT>& in_queue, unsigned int& siz, const t value, const unsigned int x, const unsigned int y, const unsigned int z) { if (in_queue(x,y,z)) return false; in_queue(x,y,z) = true; if (++siz>=_width) { if (!is_empty()) resize(_width*2,4,1,1,0); else assign(64,4); } (*this)(siz-1,0) = (T)value; (*this)(siz-1,1) = (T)x; (*this)(siz-1,2) = (T)y; (*this)(siz-1,3) = (T)z; for (unsigned int pos = siz - 1, par = 0; pos && value>(*this)(par=(pos+1)/2-1,0); pos = par) { cimg::swap((*this)(pos,0),(*this)(par,0)); cimg::swap((*this)(pos,1),(*this)(par,1)); cimg::swap((*this)(pos,2),(*this)(par,2)); cimg::swap((*this)(pos,3),(*this)(par,3)); } return true; } CImg<T>& _priority_queue_remove(unsigned int& siz) { (*this)(0,0) = (*this)(--siz,0); (*this)(0,1) = (*this)(siz,1); (*this)(0,2) = (*this)(siz,2); (*this)(0,3) = (*this)(siz,3); const float value = (*this)(0,0); for (unsigned int pos = 0, left = 0, right = 0; ((right=2*(pos+1),(left=right-1))<siz && value<(*this)(left,0)) || (right<siz && value<(*this)(right,0));) { if (right<siz) { if ((*this)(left,0)>(*this)(right,0)) { cimg::swap((*this)(pos,0),(*this)(left,0)); cimg::swap((*this)(pos,1),(*this)(left,1)); cimg::swap((*this)(pos,2),(*this)(left,2)); cimg::swap((*this)(pos,3),(*this)(left,3)); pos = left; } else { cimg::swap((*this)(pos,0),(*this)(right,0)); cimg::swap((*this)(pos,1),(*this)(right,1)); cimg::swap((*this)(pos,2),(*this)(right,2)); cimg::swap((*this)(pos,3),(*this)(right,3)); pos = right; } } else { cimg::swap((*this)(pos,0),(*this)(left,0)); cimg::swap((*this)(pos,1),(*this)(left,1)); cimg::swap((*this)(pos,2),(*this)(left,2)); cimg::swap((*this)(pos,3),(*this)(left,3)); pos = left; } } return *this; } //! Apply recursive Deriche filter. /** \param sigma Standard deviation of the filter. \param order Order of the filter. Can be <tt>{ 0=smooth-filter | 1=1st-derivative | 2=2nd-derivative }</tt>. \param axis Axis along which the filter is computed. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. **/ CImg<T>& deriche(const float sigma, const int order=0, const char axis='x', const bool boundary_conditions=true) { #define _cimg_deriche_apply \ Tfloat *ptrY = Y._data, yb = 0, yp = 0; \ T xp = (T)0; \ if (boundary_conditions) { xp = *ptrX; yb = yp = (Tfloat)(coefp*xp); } \ for (int m = 0; m<N; ++m) { \ const T xc = *ptrX; ptrX+=off; \ const Tfloat yc = *(ptrY++) = (Tfloat)(a0*xc + a1*xp - b1*yp - b2*yb); \ xp = xc; yb = yp; yp = yc; \ } \ T xn = (T)0, xa = (T)0; \ Tfloat yn = 0, ya = 0; \ if (boundary_conditions) { xn = xa = *(ptrX-off); yn = ya = (Tfloat)coefn*xn; } \ for (int n = N-1; n>=0; --n) { \ const T xc = *(ptrX-=off); \ const Tfloat yc = (Tfloat)(a2*xn + a3*xa - b1*yn - b2*ya); \ xa = xn; xn = xc; ya = yn; yn = yc; \ *ptrX = (T)(*(--ptrY)+yc); \ } const char naxis = cimg::uncase(axis); const float nsigma = sigma>=0?sigma:-sigma*(naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100; if (is_empty() || (nsigma<0.1 && !order)) return *this; const float nnsigma = nsigma<0.1f?0.1f:nsigma, alpha = 1.695f/nnsigma, ema = (float)std::exp(-alpha), ema2 = (float)std::exp(-2*alpha), b1 = -2*ema, b2 = ema2; float a0 = 0, a1 = 0, a2 = 0, a3 = 0, coefp = 0, coefn = 0; switch (order) { case 0 : { const float k = (1-ema)*(1-ema)/(1+2*alpha*ema-ema2); a0 = k; a1 = k*(alpha-1)*ema; a2 = k*(alpha+1)*ema; a3 = -k*ema2; } break; case 1 : { const float k = -(1-ema)*(1-ema)*(1-ema)/(2*(ema+1)*ema); a0 = a3 = 0; a1 = k*ema; a2 = -a1; } break; case 2 : { const float ea = (float)std::exp(-alpha), k = -(ema2-1)/(2*alpha*ema), kn = (-2*(-1+3*ea-3*ea*ea+ea*ea*ea)/(3*ea+1+3*ea*ea+ea*ea*ea)); a0 = kn; a1 = -kn*(1+k*alpha)*ema; a2 = kn*(1-k*alpha)*ema; a3 = -kn*ema2; } break; default : throw CImgArgumentException(_cimg_instance "deriche(): Invalid specified filter order %u " "(should be { 0=smoothing | 1=1st-derivative | 2=2nd-derivative }).", cimg_instance, order); } coefp = (a0+a1)/(1+b1+b2); coefn = (a2+a3)/(1+b1+b2); switch (naxis) { case 'x' : { const int N = _width; const unsigned long off = 1U; CImg<Tfloat> Y(N); cimg_forYZC(*this,y,z,c) { T *ptrX = data(0,y,z,c); _cimg_deriche_apply; } } break; case 'y' : { const int N = _height; const unsigned long off = (unsigned long)_width; CImg<Tfloat> Y(N); cimg_forXZC(*this,x,z,c) { T *ptrX = data(x,0,z,c); _cimg_deriche_apply; } } break; case 'z' : { const int N = _depth; const unsigned long off = (unsigned long)_width*_height; CImg<Tfloat> Y(N); cimg_forXYC(*this,x,y,c) { T *ptrX = data(x,y,0,c); _cimg_deriche_apply; } } break; default : { const int N = _spectrum; const unsigned long off = (unsigned long)_width*_height*_depth; CImg<Tfloat> Y(N); cimg_forXYZ(*this,x,y,z) { T *ptrX = data(x,y,z,0); _cimg_deriche_apply; } } } return *this; } //! Apply recursive Deriche filter \newinstance. CImg<Tfloat> get_deriche(const float sigma, const int order=0, const char axis='x', const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).deriche(sigma,order,axis,boundary_conditions); } //! Blur image. /** \param sigma_x Standard deviation of the blur, along the X-axis. \param sigma_y Standard deviation of the blur, along the Y-axis. \param sigma_z Standard deviation of the blur, along the Z-axis. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>. \note - The blur is computed as a 0-order Deriche filter. This is not a gaussian blur. - This is a recursive algorithm, not depending on the values of the standard deviations. **/ CImg<T>& blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true) { if (!is_empty()) { if (_width>1) deriche(sigma_x,0,'x',boundary_conditions); if (_height>1) deriche(sigma_y,0,'y',boundary_conditions); if (_depth>1) deriche(sigma_z,0,'z',boundary_conditions); } return *this; } //! Blur image \newinstance. CImg<Tfloat> get_blur(const float sigma_x, const float sigma_y, const float sigma_z, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur(sigma_x,sigma_y,sigma_z,boundary_conditions); } //! Blur image isotropically. /** \param sigma Standard deviation of the blur. \param boundary_conditions Boundary conditions. Can be <tt>{ 0=dirichlet | 1=neumann }</tt>.a **/ CImg<T>& blur(const float sigma, const bool boundary_conditions=true) { const float nsigma = sigma>=0?sigma:-sigma*cimg::max(_width,_height,_depth)/100; return blur(nsigma,nsigma,nsigma,boundary_conditions); } //! Blur image isotropically \newinstance. CImg<Tfloat> get_blur(const float sigma, const bool boundary_conditions=true) const { return CImg<Tfloat>(*this,false).blur(sigma,boundary_conditions); } //! Blur image anisotropically, directed by a field of diffusion tensors. /** \param G Field of square roots of diffusion tensors/vectors used to drive the smoothing. \param amplitude Amplitude of the smoothing. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ template<typename t> CImg<T>& blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=1) { // Check arguments and init variables if (!is_sameXYZ(G) || (G._spectrum!=3 && G._spectrum!=6)) throw CImgArgumentException(_cimg_instance "blur_anisotropic(): Invalid specified diffusion tensor field (%u,%u,%u,%u,%p).", cimg_instance, G._width,G._height,G._depth,G._spectrum,G._data); if (is_empty() || amplitude<=0 || dl<0) return *this; const bool is_3d = (G._spectrum==6); T val_min, val_max = max_min(val_min); if (da<=0) { // Iterated oriented Laplacians CImg<Tfloat> velocity(_width,_height,_depth,_spectrum); for (unsigned int iteration = 0; iteration<(unsigned int)amplitude; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (is_3d) { // 3d version CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, veloc = (Tfloat)(G(x,y,z,0)*ixx + 2*G(x,y,z,1)*ixy + 2*G(x,y,z,2)*ixz + G(x,y,z,3)*iyy + 2*G(x,y,z,4)*iyz + G(x,y,z,5)*izz); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else { // 2d version CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, veloc = (Tfloat)(G(x,y,0,0)*ixx + 2*G(x,y,0,1)*ixy + G(x,y,0,2)*iyy); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } if (veloc_max>0) *this+=(velocity*=dl/veloc_max); } } else { // LIC-based smoothing. const unsigned long whd = (unsigned long)_width*_height*_depth; const float sqrt2amplitude = (float)std::sqrt(2*amplitude); const int dx1 = width() - 1, dy1 = height() - 1, dz1 = depth() - 1; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0), W(_width,_height,_depth,is_3d?4:3), val(_spectrum); int N = 0; if (is_3d) { // 3d version for (float phi = (180%(int)da)/2.0f; phi<=180; phi+=da) { const float phir = (float)(phi*cimg::PI/180), datmp = (float)(da/std::cos(phir)), da2 = datmp<1?360.0f:datmp; for (float theta = 0; theta<360; (theta+=da2),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)*std::cos(phir)), vy = (float)(std::sin(thetar)*std::cos(phir)), vz = (float)std::sin(phir); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2), *pd = G.data(0,0,0,3), *pe = G.data(0,0,0,4), *pf = G.data(0,0,0,5); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2), *pd3 = W.data(0,0,0,3); cimg_forXYZ(G,xg,yg,zg) { const t a = *(pa++), b = *(pb++), c = *(pc++), d = *(pd++), e = *(pe++), f = *(pf++); const float u = (float)(a*vx + b*vy + c*vz), v = (float)(b*vx + d*vy + e*vz), w = (float)(c*vx + e*vy + f*vz), n = (float)std::sqrt(1e-5+u*u+v*v+w*w), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)(w*dln); *(pd3++) = (Tfloat)n; } Tfloat *ptrd = res._data; cimg_forXYZ(*this,x,y,z) { val.fill(0); const float n = (float)W(x,y,z,3), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y, Z = (float)z; switch (interpolation_type) { case 0 : { // Nearest neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const int cx = (int)(X+0.5f), cy = (int)(Y+0.5f), cz = (int)(Z+0.5f); const float u = (float)W(cx,cy,cz,0), v = (float)W(cx,cy,cz,1), w = (float)W(cx,cy,cz,2); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,cz,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,cz,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u = (float)(W._linear_atXYZ(X,Y,Z,0)), v = (float)(W._linear_atXYZ(X,Y,Z,1)), w = (float)(W._linear_atXYZ(X,Y,Z,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; default : { // 2nd order Runge Kutta for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1 && Z>=0 && Z<=dz1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,0)), v0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,1)), w0 = (float)(0.5f*W._linear_atXYZ(X,Y,Z,2)), u = (float)(W._linear_atXYZ(X+u0,Y+v0,Z+w0,0)), v = (float)(W._linear_atXYZ(X+u0,Y+v0,Z+w0,1)), w = (float)(W._linear_atXYZ(X+u0,Y+v0,Z+w0,2)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXYZ(X,Y,Z,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXYZ(X,Y,Z,c)); S+=coef; } X+=u; Y+=v; Z+=w; } } break; } Tfloat *_ptrd = ptrd++; if (S>0) cimg_forC(res,c) { *_ptrd+=val[c]/S; _ptrd+=whd; } else cimg_forC(res,c) { *_ptrd+=(Tfloat)((*this)(x,y,z,c)); _ptrd+=whd; } } } } } else { // 2d LIC algorithm for (float theta = (360%(int)da)/2.0f; theta<360; (theta+=da),++N) { const float thetar = (float)(theta*cimg::PI/180), vx = (float)(std::cos(thetar)), vy = (float)(std::sin(thetar)); const t *pa = G.data(0,0,0,0), *pb = G.data(0,0,0,1), *pc = G.data(0,0,0,2); Tfloat *pd0 = W.data(0,0,0,0), *pd1 = W.data(0,0,0,1), *pd2 = W.data(0,0,0,2); cimg_forXY(G,xg,yg) { const t a = *(pa++), b = *(pb++), c = *(pc++); const float u = (float)(a*vx + b*vy), v = (float)(b*vx + c*vy), n = (float)std::sqrt(1e-5+u*u+v*v), dln = dl/n; *(pd0++) = (Tfloat)(u*dln); *(pd1++) = (Tfloat)(v*dln); *(pd2++) = (Tfloat)n; } Tfloat *ptrd = res._data; cimg_forXY(*this,x,y) { val.fill(0); const float n = (float)W(x,y,0,2), fsigma = (float)(n*sqrt2amplitude), fsigma2 = 2*fsigma*fsigma, length = gauss_prec*fsigma; float S = 0, X = (float)x, Y = (float)y; switch (interpolation_type) { case 0 : { // Nearest-neighbor for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const int cx = (int)(X+0.5f), cy = (int)(Y+0.5f); const float u = (float)W(cx,cy,0,0), v = (float)W(cx,cy,0,1); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)(*this)(cx,cy,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*(*this)(cx,cy,0,c)); S+=coef; } X+=u; Y+=v; } } break; case 1 : { // Linear interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u = (float)(W._linear_atXY(X,Y,0,0)), v = (float)(W._linear_atXY(X,Y,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } break; default : { // 2nd-order Runge-kutta interpolation for (float l = 0; l<length && X>=0 && X<=dx1 && Y>=0 && Y<=dy1; l+=dl) { const float u0 = (float)(0.5f*W._linear_atXY(X,Y,0,0)), v0 = (float)(0.5f*W._linear_atXY(X,Y,0,1)), u = (float)(W._linear_atXY(X+u0,Y+v0,0,0)), v = (float)(W._linear_atXY(X+u0,Y+v0,0,1)); if (is_fast_approx) { cimg_forC(*this,c) val[c]+=(Tfloat)_linear_atXY(X,Y,0,c); ++S; } else { const float coef = (float)std::exp(-l*l/fsigma2); cimg_forC(*this,c) val[c]+=(Tfloat)(coef*_linear_atXY(X,Y,0,c)); S+=coef; } X+=u; Y+=v; } } } Tfloat *_ptrd = ptrd++; if (S>0) cimg_forC(res,c) { *_ptrd+=val[c]/S; _ptrd+=whd; } else cimg_forC(res,c) { *_ptrd+=(Tfloat)((*this)(x,y,0,c)); _ptrd+=whd; } } } } const Tfloat *ptrs = res._data; cimg_for(*this,ptrd,T) { const Tfloat val = *(ptrs++)/N; *ptrd = val<val_min?val_min:(val>val_max?val_max:(T)val); } } return *this; } //! Blur image anisotropically, directed by a field of diffusion tensors \newinstance. template<typename t> CImg<T> get_blur_anisotropic(const CImg<t>& G, const float amplitude=60, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return (+*this).blur_anisotropic(G,amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way. /** \param amplitude Amplitude of the smoothing. \param sharpness Sharpness. \param anisotropy Anisotropy. \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param dl Spatial discretization. \param da Angular discretization. \param gauss_prec Precision of the diffusion process. \param interpolation_type Interpolation scheme. Can be <tt>{ 0=nearest-neighbor | 1=linear | 2=Runge-Kutta }</tt>. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) { return blur_anisotropic(get_diffusion_tensors(sharpness,anisotropy,alpha,sigma,interpolation_type!=3), amplitude,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image anisotropically, in an edge-preserving way \newinstance. CImg<T> get_blur_anisotropic(const float amplitude, const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const float dl=0.8f, const float da=30, const float gauss_prec=2, const unsigned int interpolation_type=0, const bool is_fast_approx=true) const { return (+*this).blur_anisotropic(amplitude,sharpness,anisotropy,alpha,sigma,dl,da,gauss_prec,interpolation_type,is_fast_approx); } //! Blur image, with the bilateral filter. /** \param sigma_x Amount of blur along the X-axis. \param sigma_y Amount of blur along the Y-axis. \param sigma_z Amount of blur along the Z-axis. \param sigma_r Amount of blur along the value axis. \param bgrid_x Size of the bilateral grid along the X-axis. \param bgrid_y Size of the bilateral grid along the Y-axis. \param bgrid_z Size of the bilateral grid along the Z-axis. \param bgrid_r Size of the bilateral grid along the value axis. \param interpolation_type Use interpolation for image slicing. \note This algorithm uses the optimisation technique proposed by S. Paris and F. Durand, in ECCV'2006 (extended for 3d volumetric images). **/ CImg<T>& blur_bilateral(const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const int bgrid_x, const int bgrid_y, const int bgrid_z, const int bgrid_r, const bool interpolation_type=true) { if (is_empty()) return *this; T m, M = max_min(m); const float range = (float)(1.0f + M - m); const unsigned int bx0 = bgrid_x>=0?bgrid_x:_width*(-bgrid_x)/100, by0 = bgrid_y>=0?bgrid_y:_height*(-bgrid_y)/100, bz0 = bgrid_z>=0?bgrid_z:_depth*(-bgrid_z)/100, br0 = bgrid_r>=0?bgrid_r:(int)(-range*bgrid_r/100), bx = bx0>0?bx0:1, by = by0>0?by0:1, bz = bz0>0?bz0:1, br = br0>0?br0:1; const float _sigma_x = sigma_x>=0?sigma_x:-sigma_x*_width/100, _sigma_y = sigma_y>=0?sigma_y:-sigma_y*_height/100, _sigma_z = sigma_z>=0?sigma_z:-sigma_z*_depth/100, nsigma_x = _sigma_x*bx/_width, nsigma_y = _sigma_y*by/_height, nsigma_z = _sigma_z*bz/_depth, nsigma_r = sigma_r*br/range; if (nsigma_x>0 || nsigma_y>0 || nsigma_z>0 || nsigma_r>0) { const bool is_3d = (_depth>1); if (is_3d) { // 3d version of the algorithm CImg<floatT> bgrid(bx,by,bz,br), bgridw(bx,by,bz,br); cimg_forC(*this,c) { bgrid.fill(0); bgridw.fill(0); cimg_forXYZ(*this,x,y,z) { const T val = (*this)(x,y,z,c); const int X = x*bx/_width, Y = y*by/_height, Z = z*bz/_depth, R = (int)((val-m)*br/range); bgrid(X,Y,Z,R) += (float)val; bgridw(X,Y,Z,R) += 1; } bgrid.blur(nsigma_x,nsigma_y,nsigma_z,true).deriche(nsigma_r,0,'c',false); bgridw.blur(nsigma_x,nsigma_y,nsigma_z,true).deriche(nsigma_r,0,'c',false); if (interpolation_type) cimg_forXYZ(*this,x,y,z) { const T val = (*this)(x,y,z,c); const float X = (float)x*bx/_width, Y = (float)y*by/_height, Z = (float)z*bz/_depth, R = (float)((val-m)*br/range), bval0 = bgrid._linear_atXYZC(X,Y,Z,R), bval1 = bgridw._linear_atXYZC(X,Y,Z,R); (*this)(x,y,z,c) = (T)(bval0/bval1); } else cimg_forXYZ(*this,x,y,z) { const T val = (*this)(x,y,z,c); const int X = x*bx/_width, Y = y*by/_height, Z = z*bz/_depth, R = (int)((val-m)*br/range); const float bval0 = bgrid(X,Y,Z,R), bval1 = bgridw(X,Y,Z,R); (*this)(x,y,z,c) = (T)(bval0/bval1); } } } else { // 2d version of the algorithm CImg<floatT> bgrid(bx,by,br,2); cimg_forC(*this,c) { bgrid.fill(0); cimg_forXY(*this,x,y) { const T val = (*this)(x,y,c); const int X = x*bx/_width, Y = y*by/_height, R = (int)((val-m)*br/range); bgrid(X,Y,R,0) += (float)val; bgrid(X,Y,R,1) += 1; } bgrid.blur(nsigma_x,nsigma_y,0,true).blur(0,0,nsigma_r,false); if (interpolation_type) cimg_forXY(*this,x,y) { const T val = (*this)(x,y,c); const float X = (float)x*bx/_width, Y = (float)y*by/_height, R = (float)((val-m)*br/range), bval0 = bgrid._linear_atXYZ(X,Y,R,0), bval1 = bgrid._linear_atXYZ(X,Y,R,1); (*this)(x,y,c) = (T)(bval0/bval1); } else cimg_forXY(*this,x,y) { const T val = (*this)(x,y,c); const int X = x*bx/_width, Y = y*by/_height, R = (int)((val-m)*br/range); const float bval0 = bgrid(X,Y,R,0), bval1 = bgrid(X,Y,R,1); (*this)(x,y,c) = (T)(bval0/bval1); } } } } return *this; } //! Blur image, with the bilateral filter \newinstance. CImg<T> get_blur_bilateral(const float sigma_x, const float sigma_y, const float sigma_z, const float sigma_r, const int bgrid_x, const int bgrid_y, const int bgrid_z, const int bgrid_r, const bool interpolation_type=true) const { return (+*this).blur_bilateral(sigma_x,sigma_y,sigma_z,sigma_r,bgrid_x,bgrid_y,bgrid_z,bgrid_r,interpolation_type); } //! Blur image using the bilateral filter. /** \param sigma_s Amount of blur along the XYZ-axes. \param sigma_r Amount of blur along the value axis. \param bgrid_s Size of the bilateral grid along the XYZ-axes. \param bgrid_r Size of the bilateral grid along the value axis. \param interpolation_type Use interpolation for image slicing. **/ CImg<T>& blur_bilateral(const float sigma_s, const float sigma_r, const int bgrid_s=-33, const int bgrid_r=32, const bool interpolation_type=true) { const float nsigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100; return blur_bilateral(nsigma_s,nsigma_s,nsigma_s,sigma_r,bgrid_s,bgrid_s,bgrid_s,bgrid_r,interpolation_type); } //! Blur image using the bilateral filter \newinstance. CImg<T> get_blur_bilateral(const float sigma_s, const float sigma_r, const int bgrid_s=-33, const int bgrid_r=32, const bool interpolation_type=true) const { return (+*this).blur_bilateral(sigma_s,sigma_s,sigma_s,sigma_r,bgrid_s,bgrid_s,bgrid_s,bgrid_r,interpolation_type); } //! Blur image using patch-based space. /** \param sigma_s Amount of blur along the XYZ-axes. \param sigma_p Amount of blur along the value axis. \param patch_size Size of the patchs. \param lookup_size Size of the window to search similar patchs. \param smoothness Smoothness for the patch comparison. \param is_fast_approx Tells if a fast approximation of the gaussian function is used or not. **/ CImg<T>& blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) { if (is_empty() || !patch_size || !lookup_size) return *this; return get_blur_patch(sigma_s,sigma_p,patch_size,lookup_size,smoothness,is_fast_approx).move_to(*this); } //! Blur image using patch-based space \newinstance. CImg<T> get_blur_patch(const float sigma_s, const float sigma_p, const unsigned int patch_size=3, const unsigned int lookup_size=4, const float smoothness=0, const bool is_fast_approx=true) const { #define _cimg_blur_patch3d_fast(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (cimg::abs(img(x,y,z,0) - img(p,q,r,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,pP,T) { const float dI = (float)*pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = alldist>3?0.0f:1.0f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch3d(N) \ cimg_for##N##XYZ(res,x,y,z) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,x,y,z,c,pP,T); pP+=N3; } \ const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N##x##N(img,p,q,r,c,pQ,T); pQ+=N3; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,pP,T) { const float dI = (float)*pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, dz = (float)r - z, \ alldist = distance2 + (dx*dx + dy*dy + dz*dz)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); \ } #define _cimg_blur_patch2d_fast(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) if (cimg::abs(img(x,y,0,0) - img(p,q,0,0))<sigma_p3) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,pP,T) { const float dI = (float)*pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = alldist>3?0.0f:1.0f; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } #define _cimg_blur_patch2d(N) \ cimg_for##N##XY(res,x,y) { \ T *pP = P._data; cimg_forC(res,c) { cimg_get##N##x##N(img,x,y,0,c,pP,T); pP+=N2; } \ const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; \ float sum_weights = 0, weight_max = 0; \ cimg_for_in##N##XY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { \ T *pQ = Q._data; cimg_forC(res,c) { cimg_get##N##x##N(img,p,q,0,c,pQ,T); pQ+=N2; } \ float distance2 = 0; \ pQ = Q._data; cimg_for(P,pP,T) { const float dI = (float)*pP - (float)*(pQ++); distance2+=dI*dI; } \ distance2/=Pnorm; \ const float dx = (float)p - x, dy = (float)q - y, \ alldist = distance2 + (dx*dx+dy*dy)/sigma_s2, weight = (float)std::exp(-alldist); \ if (weight>weight_max) weight_max = weight; \ sum_weights+=weight; \ cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); \ } \ sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); \ if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; \ else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); \ } if (is_empty() || !patch_size || !lookup_size) return +*this; CImg<Tfloat> res(_width,_height,_depth,_spectrum,0); const CImg<T> _img = smoothness>0?get_blur(smoothness):CImg<Tfloat>(),&img = smoothness>0?_img:*this; CImg<T> P(patch_size*patch_size*_spectrum), Q(P); const float nsigma_s = sigma_s>=0?sigma_s:-sigma_s*cimg::max(_width,_height,_depth)/100, sigma_s2 = nsigma_s*nsigma_s, sigma_p2 = sigma_p*sigma_p, sigma_p3 = 3*sigma_p, Pnorm = P.size()*sigma_p2; const int rsize2 = (int)lookup_size/2, rsize1 = (int)lookup_size - rsize2 - 1; const unsigned int N2 = patch_size*patch_size, N3 = N2*patch_size; if (_depth>1) switch (patch_size) { // 3d case 2 : if (is_fast_approx) _cimg_blur_patch3d_fast(2) else _cimg_blur_patch3d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch3d_fast(3) else _cimg_blur_patch3d(3) break; default : { const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_forXYZ(res,x,y,z) { // Fast P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (cimg::abs(img(x,y,z,0)-img(p,q,r,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = distance2>3?0.0f:1.0f; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } else cimg_forXYZ(res,x,y,z) { // Exact P = img.get_crop(x - psize1,y - psize1,z - psize1,x + psize2,y + psize2,z + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, z0 = z - rsize1, x1 = x + rsize2, y1 = y + rsize2, z1 = z + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXYZ(res,x0,y0,z0,x1,y1,z1,p,q,r) if (p!=x || q!=y || r!=z) { (Q = img.get_crop(p - psize1,q - psize1,r - psize1,p + psize2,q + psize2,r + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, dz = (float)z - r, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy + dz*dz)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,z,c)+=weight*(*this)(p,q,r,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,z,c)+=weight_max*(*this)(x,y,z,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,z,c)/=sum_weights; else cimg_forC(res,c) res(x,y,z,c) = (Tfloat)((*this)(x,y,z,c)); } } } else switch (patch_size) { // 2d case 2 : if (is_fast_approx) _cimg_blur_patch2d_fast(2) else _cimg_blur_patch2d(2) break; case 3 : if (is_fast_approx) _cimg_blur_patch2d_fast(3) else _cimg_blur_patch2d(3) break; case 4 : if (is_fast_approx) _cimg_blur_patch2d_fast(4) else _cimg_blur_patch2d(4) break; case 5 : if (is_fast_approx) _cimg_blur_patch2d_fast(5) else _cimg_blur_patch2d(5) break; case 6 : if (is_fast_approx) _cimg_blur_patch2d_fast(6) else _cimg_blur_patch2d(6) break; case 7 : if (is_fast_approx) _cimg_blur_patch2d_fast(7) else _cimg_blur_patch2d(7) break; case 8 : if (is_fast_approx) _cimg_blur_patch2d_fast(8) else _cimg_blur_patch2d(8) break; case 9 : if (is_fast_approx) _cimg_blur_patch2d_fast(9) else _cimg_blur_patch2d(9) break; default : { // Fast const int psize2 = (int)patch_size/2, psize1 = (int)patch_size - psize2 - 1; if (is_fast_approx) cimg_forXY(res,x,y) { // 2d fast approximation. P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if (cimg::abs(img(x,y,0)-img(p,q,0))<sigma_p3) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = distance2>3?0.0f:1.0f; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,c) = (Tfloat)((*this)(x,y,c)); } else cimg_forXY(res,x,y) { // 2d exact algorithm. P = img.get_crop(x - psize1,y - psize1,x + psize2,y + psize2,true); const int x0 = x - rsize1, y0 = y - rsize1, x1 = x + rsize2, y1 = y + rsize2; float sum_weights = 0, weight_max = 0; cimg_for_inXY(res,x0,y0,x1,y1,p,q) if (p!=x || q!=y) { (Q = img.get_crop(p - psize1,q - psize1,p + psize2,q + psize2,true))-=P; const float dx = (float)x - p, dy = (float)y - q, distance2 = (float)(Q.pow(2).sum()/Pnorm + (dx*dx + dy*dy)/sigma_s2), weight = (float)std::exp(-distance2); if (weight>weight_max) weight_max = weight; sum_weights+=weight; cimg_forC(res,c) res(x,y,c)+=weight*(*this)(p,q,c); } sum_weights+=weight_max; cimg_forC(res,c) res(x,y,c)+=weight_max*(*this)(x,y,c); if (sum_weights>0) cimg_forC(res,c) res(x,y,c)/=sum_weights; else cimg_forC(res,c) res(x,y,0,c) = (Tfloat)((*this)(x,y,c)); } } } return res; } //! Blur image with the median filter. /** \param n Size of the median filter. **/ CImg<T>& blur_median(const unsigned int n) { if (!n) return *this; return get_blur_median(n).move_to(*this); } //! Blur image with the median filter \newinstance. CImg<T> get_blur_median(const unsigned int n) const { if (is_empty() || n<=1) return +*this; CImg<T> res(_width,_height,_depth,_spectrum); T *ptrd = res._data; const int hl = n/2, hr = hl - 1 + n%2; if (res._depth!=1) cimg_forXYZC(*this,x,y,z,c) { // 3d const int x0 = x - hl, y0 = y - hl, z0 = z-hl, x1 = x + hr, y1 = y + hr, z1 = z+hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nz0 = z0<0?0:z0, nx1 = x1>=width()?width()-1:x1, ny1 = y1>=height()?height()-1:y1, nz1 = z1>=depth()?depth()-1:z1; *(ptrd++) = get_crop(nx0,ny0,nz0,c,nx1,ny1,nz1,c).median(); } else { #define _cimg_median_sort(a,b) if ((a)>(b)) cimg::swap(a,b) if (res._height!=1) switch (n) { // 2d case 3 : { T I[9] = { 0 }; CImg_3x3(J,T); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) { std::memcpy(J,I,9*sizeof(T)); _cimg_median_sort(Jcp, Jnp); _cimg_median_sort(Jcc, Jnc); _cimg_median_sort(Jcn, Jnn); _cimg_median_sort(Jpp, Jcp); _cimg_median_sort(Jpc, Jcc); _cimg_median_sort(Jpn, Jcn); _cimg_median_sort(Jcp, Jnp); _cimg_median_sort(Jcc, Jnc); _cimg_median_sort(Jcn, Jnn); _cimg_median_sort(Jpp, Jpc); _cimg_median_sort(Jnc, Jnn); _cimg_median_sort(Jcc, Jcn); _cimg_median_sort(Jpc, Jpn); _cimg_median_sort(Jcp, Jcc); _cimg_median_sort(Jnp, Jnc); _cimg_median_sort(Jcc, Jcn); _cimg_median_sort(Jcc, Jnp); _cimg_median_sort(Jpn, Jcc); _cimg_median_sort(Jcc, Jnp); *(ptrd++) = Jcc; } } break; case 5 : { T I[25] = { 0 }; CImg_5x5(J,T); cimg_forC(*this,c) cimg_for5x5(*this,x,y,0,c,I,T) { std::memcpy(J,I,25*sizeof(T)); _cimg_median_sort(Jbb, Jpb); _cimg_median_sort(Jnb, Jab); _cimg_median_sort(Jcb, Jab); _cimg_median_sort(Jcb, Jnb); _cimg_median_sort(Jpp, Jcp); _cimg_median_sort(Jbp, Jcp); _cimg_median_sort(Jbp, Jpp); _cimg_median_sort(Jap, Jbc); _cimg_median_sort(Jnp, Jbc); _cimg_median_sort(Jnp, Jap); _cimg_median_sort(Jcc, Jnc); _cimg_median_sort(Jpc, Jnc); _cimg_median_sort(Jpc, Jcc); _cimg_median_sort(Jbn, Jpn); _cimg_median_sort(Jac, Jpn); _cimg_median_sort(Jac, Jbn); _cimg_median_sort(Jnn, Jan); _cimg_median_sort(Jcn, Jan); _cimg_median_sort(Jcn, Jnn); _cimg_median_sort(Jpa, Jca); _cimg_median_sort(Jba, Jca); _cimg_median_sort(Jba, Jpa); _cimg_median_sort(Jna, Jaa); _cimg_median_sort(Jcb, Jbp); _cimg_median_sort(Jnb, Jpp); _cimg_median_sort(Jbb, Jpp); _cimg_median_sort(Jbb, Jnb); _cimg_median_sort(Jab, Jcp); _cimg_median_sort(Jpb, Jcp); _cimg_median_sort(Jpb, Jab); _cimg_median_sort(Jpc, Jac); _cimg_median_sort(Jnp, Jac); _cimg_median_sort(Jnp, Jpc); _cimg_median_sort(Jcc, Jbn); _cimg_median_sort(Jap, Jbn); _cimg_median_sort(Jap, Jcc); _cimg_median_sort(Jnc, Jpn); _cimg_median_sort(Jbc, Jpn); _cimg_median_sort(Jbc, Jnc); _cimg_median_sort(Jba, Jna); _cimg_median_sort(Jcn, Jna); _cimg_median_sort(Jcn, Jba); _cimg_median_sort(Jpa, Jaa); _cimg_median_sort(Jnn, Jaa); _cimg_median_sort(Jnn, Jpa); _cimg_median_sort(Jan, Jca); _cimg_median_sort(Jnp, Jcn); _cimg_median_sort(Jap, Jnn); _cimg_median_sort(Jbb, Jnn); _cimg_median_sort(Jbb, Jap); _cimg_median_sort(Jbc, Jan); _cimg_median_sort(Jpb, Jan); _cimg_median_sort(Jpb, Jbc); _cimg_median_sort(Jpc, Jba); _cimg_median_sort(Jcb, Jba); _cimg_median_sort(Jcb, Jpc); _cimg_median_sort(Jcc, Jpa); _cimg_median_sort(Jnb, Jpa); _cimg_median_sort(Jnb, Jcc); _cimg_median_sort(Jnc, Jca); _cimg_median_sort(Jab, Jca); _cimg_median_sort(Jab, Jnc); _cimg_median_sort(Jac, Jna); _cimg_median_sort(Jbp, Jna); _cimg_median_sort(Jbp, Jac); _cimg_median_sort(Jbn, Jaa); _cimg_median_sort(Jpp, Jaa); _cimg_median_sort(Jpp, Jbn); _cimg_median_sort(Jcp, Jpn); _cimg_median_sort(Jcp, Jan); _cimg_median_sort(Jnc, Jpa); _cimg_median_sort(Jbn, Jna); _cimg_median_sort(Jcp, Jnc); _cimg_median_sort(Jcp, Jbn); _cimg_median_sort(Jpb, Jap); _cimg_median_sort(Jnb, Jpc); _cimg_median_sort(Jbp, Jcn); _cimg_median_sort(Jpc, Jcn); _cimg_median_sort(Jap, Jcn); _cimg_median_sort(Jab, Jbc); _cimg_median_sort(Jpp, Jcc); _cimg_median_sort(Jcp, Jac); _cimg_median_sort(Jab, Jpp); _cimg_median_sort(Jab, Jcp); _cimg_median_sort(Jcc, Jac); _cimg_median_sort(Jbc, Jac); _cimg_median_sort(Jpp, Jcp); _cimg_median_sort(Jbc, Jcc); _cimg_median_sort(Jpp, Jbc); _cimg_median_sort(Jpp, Jcn); _cimg_median_sort(Jcc, Jcn); _cimg_median_sort(Jcp, Jcn); _cimg_median_sort(Jcp, Jbc); _cimg_median_sort(Jcc, Jnn); _cimg_median_sort(Jcp, Jcc); _cimg_median_sort(Jbc, Jnn); _cimg_median_sort(Jcc, Jba); _cimg_median_sort(Jbc, Jba); _cimg_median_sort(Jbc, Jcc); *(ptrd++) = Jcc; } } break; default : { cimg_forXYC(*this,x,y,c) { const int x0 = x - hl, y0 = y - hl, x1 = x + hr, y1 = y + hr, nx0 = x0<0?0:x0, ny0 = y0<0?0:y0, nx1 = x1>=width()?width()-1:x1, ny1 = y1>=height()?height()-1:y1; *(ptrd++) = get_crop(nx0,ny0,0,c,nx1,ny1,0,c).median(); } } } else switch (n) { // 1d case 2 : { T I[4] = { 0 }; cimg_forC(*this,c) cimg_for2x2(*this,x,y,0,c,I,T) *(ptrd++) = (T)(0.5f*(I[0]+I[1])); } break; case 3 : { T I[9] = { 0 }; cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,T) *(ptrd++) = I[3]<I[4]?(I[4]<I[5]?I[4]:(I[3]<I[5]?I[5]:I[3])):(I[3]<I[5]?I[3]:(I[4]<I[5]?I[5]:I[4])); } break; default : { cimg_forXC(*this,x,c) { const int x0 = x - hl, x1 = x + hr, nx0 = x0<0?0:x0, nx1 = x1>=width()?width()-1:x1; *(ptrd++) = get_crop(nx0,0,0,c,nx1,0,0,c).median(); } } } } return res; } //! Sharpen image. /** \param amplitude Sharpening amplitude \param sharpen_type Select sharpening method. Can be <tt>{ false=inverse diffusion | true=shock filters }</tt>. \param edge Edge threshold (shock filters only). \param alpha Gradient smoothness (shock filters only). \param sigma Tensor smoothness (shock filters only). **/ CImg<T>& sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) { if (is_empty()) return *this; T val_min, val_max = max_min(val_min); const float nedge = edge/2; CImg<Tfloat> val, vec, velocity(_width,_height,_depth,_spectrum); Tfloat *ptrd = velocity._data, veloc_max = 0; if (_depth>1) { // 3d CImg_3x3x3(I,Tfloat); if (sharpen_type) { // Shock filters. CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); Tfloat *ptrG0 = G.data(0,0,0,0), *ptrG1 = G.data(0,0,0,1), *ptrG2 = G.data(0,0,0,2), *ptrG3 = G.data(0,0,0,3); cimg_forXYZ(G,x,y,z) { G.get_tensor_at(x,y,z).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; if (val[2]<0) val[2] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = vec(0,2); *(ptrG3++) = 1 - (Tfloat)std::pow(1+val[0]+val[1]+val[2],-(Tfloat)nedge); } cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat u = G(x,y,z,0), v = G(x,y,z,1), w = G(x,y,z,2), amp = G(x,y,z,3), ixx = Incc + Ipcc - 2*Iccc, ixy = (Innc + Ippc - Inpc - Ipnc)/4, ixz = (Incn + Ipcp - Incp - Ipcn)/4, iyy = Icnc + Icpc - 2*Iccc, iyz = (Icnn + Icpp - Icnp - Icpn)/4, izz = Iccn + Iccp - 2*Iccc, ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp, itt = u*u*ixx + v*v*iyy + w*w*izz + 2*u*v*ixy + 2*u*w*ixz + 2*v*w*iyz, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb) + w*cimg::minmod(izf,izb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { // Inverse diffusion. const Tfloat veloc = -Ipcc - Incc - Icpc - Icnc - Iccp - Iccn + 6*Iccc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else { CImg_3x3(I,Tfloat); if (sharpen_type) { // Shock filters. CImg<Tfloat> G = (alpha>0?get_blur(alpha).get_structure_tensors():get_structure_tensors()); if (sigma>0) G.blur(sigma); Tfloat *ptrG0 = G.data(0,0,0,0), *ptrG1 = G.data(0,0,0,1), *ptrG2 = G.data(0,0,0,2); cimg_forXY(G,x,y) { G.get_tensor_at(x,y).symmetric_eigen(val,vec); if (val[0]<0) val[0] = 0; if (val[1]<0) val[1] = 0; *(ptrG0++) = vec(0,0); *(ptrG1++) = vec(0,1); *(ptrG2++) = 1 - (Tfloat)std::pow(1 + val[0] + val[1],-(Tfloat)nedge); } cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat u = G(x,y,0), v = G(x,y,1), amp = G(x,y,2), ixx = Inc + Ipc - 2*Icc, ixy = (Inn + Ipp - Inp - Ipn)/4, iyy = Icn + Icp - 2*Icc, ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp, itt = u*u*ixx + v*v*iyy + 2*u*v*ixy, it = u*cimg::minmod(ixf,ixb) + v*cimg::minmod(iyf,iyb), veloc = -amp*cimg::sign(itt)*cimg::abs(it); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } else cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) { // Inverse diffusion. const Tfloat veloc = -Ipc - Inc - Icp - Icn + 4*Icc; *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } } if (veloc_max<=0) return *this; return ((velocity*=amplitude/veloc_max)+=*this).cut(val_min,val_max).move_to(*this); } //! Sharpen image \newinstance. CImg<T> get_sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1, const float alpha=0, const float sigma=0) const { return (+*this).sharpen(amplitude,sharpen_type,edge,alpha,sigma); } //! Return image gradient. /** \param axes Axes considered for the gradient computation, as a C-string (e.g "xy"). \param scheme = Numerical scheme used for the gradient computation: - -1 = Backward finite differences - 0 = Centered finite differences - 1 = Forward finite differences - 2 = Using Sobel masks - 3 = Using rotation invariant masks - 4 = Using Deriche recusrsive filter. **/ CImgList<Tfloat> get_gradient(const char *const axes=0, const int scheme=3) const { CImgList<Tfloat> grad(2,_width,_height,_depth,_spectrum); Tfloat *ptrd0 = grad[0]._data, *ptrd1 = grad[1]._data; bool is_3d = false; if (axes) { for (unsigned int a = 0; axes[a]; ++a) { const char axis = cimg::uncase(axes[a]); switch (axis) { case 'x' : case 'y' : break; case 'z' : is_3d = true; break; default : throw CImgArgumentException(_cimg_instance "get_gradient(): Invalid specified axis '%c'.", cimg_instance, axis); } } } else is_3d = (_depth>1); if (is_3d) { CImg<Tfloat>(_width,_height,_depth,_spectrum).move_to(grad); Tfloat *ptrd2 = grad[2]._data; switch (scheme) { // 3d. case -1 : { // Backward finite differences. CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Iccc - Ipcc; *(ptrd1++) = Iccc - Icpc; *(ptrd2++) = Iccc - Iccp; } } break; case 1 : { // Forward finite differences. CImg_2x2x2(I,Tfloat); cimg_forC(*this,c) cimg_for2x2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Incc - Iccc; *(ptrd1++) = Icnc - Iccc; *(ptrd2++) = Iccn - Iccc; } } break; case 4 : { // Using Deriche filter with low standard variation. grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); grad[2] = get_deriche(0,1,'z'); } break; default : { // Central finite differences. CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Incc - Ipcc)/2; *(ptrd1++) = (Icnc - Icpc)/2; *(ptrd2++) = (Iccn - Iccp)/2; } } } } else switch (scheme) { // 2d. case -1 : { // Backward finite differences. CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Icc - Ipc; *(ptrd1++) = Icc - Icp; } } break; case 1 : { // Forward finite differences. CImg_2x2(I,Tfloat); cimg_forZC(*this,z,c) cimg_for2x2(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Inc - Icc; *(ptrd1++) = Icn - Icc; } } break; case 2 : { // Sobel scheme. CImg_3x3(I,Tfloat); const Tfloat a = 1, b = 2; cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -a*Ipp - b*Ipc - a*Ipn + a*Inp + b*Inc + a*Inn; *(ptrd1++) = -a*Ipp - b*Icp - a*Inp + a*Ipn + b*Icn + a*Inn; } } break; case 3 : { // Rotation invariant mask. CImg_3x3(I,Tfloat); const Tfloat a = (Tfloat)(0.25f*(2-std::sqrt(2.0f))), b = (Tfloat)(0.5f*(std::sqrt(2.0f)-1)); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = -a*Ipp - b*Ipc - a*Ipn + a*Inp + b*Inc + a*Inn; *(ptrd1++) = -a*Ipp - b*Icp - a*Inp + a*Ipn + b*Icn + a*Inn; } } break; case 4 : { // using Deriche filter with low standard variation grad[0] = get_deriche(0,1,'x'); grad[1] = get_deriche(0,1,'y'); } break; default : { // central finite differences CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = (Inc - Ipc)/2; *(ptrd1++) = (Icn - Icp)/2; } } } if (!axes) return grad; CImgList<Tfloat> res; for (unsigned int l = 0; axes[l]; ++l) { const char axis = cimg::uncase(axes[l]); switch (axis) { case 'x' : res.insert(grad[0]); break; case 'y' : res.insert(grad[1]); break; case 'z' : res.insert(grad[2]); break; } } grad.assign(); return res; } //! Return image hessian. /** \param axes Axes considered for the hessian computation, as a C-string (e.g "xy"). **/ CImgList<Tfloat> get_hessian(const char *const axes=0) const { CImgList<Tfloat> res; const char *naxes = axes, *const def_axes2d = "xxxyyy", *const def_axes3d = "xxxyxzyyyzzz"; if (!axes) naxes = _depth>1?def_axes3d:def_axes2d; const unsigned int lmax = std::strlen(naxes); if (lmax%2) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); res.assign(lmax/2,_width,_height,_depth,_spectrum); if (!cimg::strcasecmp(naxes,def_axes3d)) { // 3d Tfloat *ptrd0 = res[0]._data, *ptrd1 = res[1]._data, *ptrd2 = res[2]._data, *ptrd3 = res[3]._data, *ptrd4 = res[4]._data, *ptrd5 = res[5]._data; CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { *(ptrd0++) = Ipcc + Incc - 2*Iccc; // Ixx *(ptrd1++) = (Ippc + Innc - Ipnc - Inpc)/4; // Ixy *(ptrd2++) = (Ipcp + Incn - Ipcn - Incp)/4; // Ixz *(ptrd3++) = Icpc + Icnc - 2*Iccc; // Iyy *(ptrd4++) = (Icpp + Icnn - Icpn - Icnp)/4; // Iyz *(ptrd5++) = Iccn + Iccp - 2*Iccc; // Izz } } else if (!cimg::strcasecmp(naxes,def_axes2d)) { // 2d Tfloat *ptrd0 = res[0]._data, *ptrd1 = res[1]._data, *ptrd2 = res[2]._data; CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) { *(ptrd0++) = Ipc + Inc - 2*Icc; // Ixx *(ptrd1++) = (Ipp + Inn - Ipn - Inp)/4; // Ixy *(ptrd2++) = Icp + Icn - 2*Icc; // Iyy } } else for (unsigned int l = 0; l<lmax; ) { // Version with custom axes. const unsigned int l2 = l/2; char axis1 = naxes[l++], axis2 = naxes[l++]; if (axis1>axis2) cimg::swap(axis1,axis2); bool valid_axis = false; Tfloat *ptrd = res[l2]._data; if (axis1=='x' && axis2=='x') { // Ixx valid_axis = true; CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Ipc + Inc - 2*Icc; } else if (axis1=='x' && axis2=='y') { // Ixy valid_axis = true; CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipp + Inn - Ipn - Inp)/4; } else if (axis1=='x' && axis2=='z') { // Ixz valid_axis = true; CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Ipcp + Incn - Ipcn - Incp)/4; } else if (axis1=='y' && axis2=='y') { // Iyy valid_axis = true; CImg_3x3(I,Tfloat); cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Icp + Icn - 2*Icc; } else if (axis1=='y' && axis2=='z') { // Iyz valid_axis = true; CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = (Icpp + Icnn - Icpn - Icnp)/4; } else if (axis1=='z' && axis2=='z') { // Izz valid_axis = true; CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Iccn + Iccp - 2*Iccc; } else if (!valid_axis) throw CImgArgumentException(_cimg_instance "get_hessian(): Invalid specified axes '%s'.", cimg_instance, naxes); } return res; } //! Compute image laplacian. CImg<T>& laplacian() { return get_laplacian().move_to(*this); } //! Compute image laplacian \newinstance. CImg<Tfloat> get_laplacian() const { if (is_empty()) return CImg<Tfloat>(); CImg<Tfloat> res(_width,_height,_depth,_spectrum); Tfloat *ptrd = res._data; if (_depth>1) { // 3d CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) *(ptrd++) = Incc + Ipcc + Icnc + Icpc + Iccn + Iccp - 6*Iccc; } else if (_height>1) { // 2d CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc + Icn + Icp - 4*Icc; } else { // 1d CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) *(ptrd++) = Inc + Ipc - 2*Icc; } return res; } //! Compute the structure tensor field of an image. /** \param scheme Numerical scheme. Can be <tt>{ 0=central | 1=fwd/bwd1 | 2=fwd/bwd2 }</tt> **/ CImg<T>& structure_tensors(const unsigned int scheme=2) { return get_structure_tensors(scheme).move_to(*this); } //! Compute the structure tensor field of an image \newinstance. CImg<Tfloat> get_structure_tensors(const unsigned int scheme=2) const { if (is_empty()) return *this; CImg<Tfloat> res; if (_depth>1) { // 3d res.assign(_width,_height,_depth,6,0); CImg_3x3x3(I,Tfloat); switch (scheme) { case 0 : { // classical central finite differences cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ix = (Incc - Ipcc)/2, iy = (Icnc - Icpc)/2, iz = (Iccn - Iccp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=ix*iz; *(ptrd3++)+=iy*iy; *(ptrd4++)+=iy*iz; *(ptrd5++)+=iz*iz; } } } break; case 1 : { // Forward/backward finite differences (version 1). cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp; *(ptrd0++)+=(ixf*ixf + ixf*ixb + ixb*ixf + ixb*ixb)/4; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(ixf*izf + ixf*izb + ixb*izf + ixb*izb)/4; *(ptrd3++)+=(iyf*iyf + iyf*iyb + iyb*iyf + iyb*iyb)/4; *(ptrd4++)+=(iyf*izf + iyf*izb + iyb*izf + iyb*izb)/4; *(ptrd5++)+=(izf*izf + izf*izb + izb*izf + izb*izb)/4; } } } break; default : { // Forward/backward finite differences (version 2). cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) { const Tfloat ixf = Incc - Iccc, ixb = Iccc - Ipcc, iyf = Icnc - Iccc, iyb = Iccc - Icpc, izf = Iccn - Iccc, izb = Iccc - Iccp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(ixf*izf + ixf*izb + ixb*izf + ixb*izb)/4; *(ptrd3++)+=(iyf*iyf + iyb*iyb)/2; *(ptrd4++)+=(iyf*izf + iyf*izb + iyb*izf + iyb*izb)/4; *(ptrd5++)+=(izf*izf + izb*izb)/2; } } } break; } } else { // 2d res.assign(_width,_height,_depth,3,0); CImg_3x3(I,Tfloat); switch (scheme) { case 0 : { // classical central finite differences cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ix = (Inc - Ipc)/2, iy = (Icn - Icp)/2; *(ptrd0++)+=ix*ix; *(ptrd1++)+=ix*iy; *(ptrd2++)+=iy*iy; } } } break; case 1 : { // Forward/backward finite differences (version 1). cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp; *(ptrd0++)+=(ixf*ixf + ixf*ixb + ixb*iyf + ixb*ixb)/4; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(iyf*iyf + iyf*iyb + iyb*iyf + iyb*iyb)/4; } } } break; default : { // Forward/backward finite differences (version 2). cimg_forC(*this,c) { Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); cimg_for3x3(*this,x,y,0,c,I,Tfloat) { const Tfloat ixf = Inc - Icc, ixb = Icc - Ipc, iyf = Icn - Icc, iyb = Icc - Icp; *(ptrd0++)+=(ixf*ixf + ixb*ixb)/2; *(ptrd1++)+=(ixf*iyf + ixf*iyb + ixb*iyf + ixb*iyb)/4; *(ptrd2++)+=(iyf*iyf + iyb*iyb)/2; } } } break; } } return res; } //! Compute field of diffusion tensors for edge-preserving smoothing. /** \param sharpness Sharpness \param anisotropy Anisotropy \param alpha Standard deviation of the gradient blur. \param sigma Standard deviation of the structure tensor blur. \param is_sqrt Tells if the square root of the tensor field is computed instead. **/ CImg<T>& diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) { CImg<Tfloat> res; const float nsharpness = cimg::max(sharpness,1e-5f), power1 = (is_sqrt?0.5f:1)*nsharpness, power2 = power1/(1e-7f+1-anisotropy); blur(alpha).normalize(0,(T)255); if (_depth>1) { // 3d CImg<floatT> val(3), vec(3,3); get_structure_tensors().move_to(res).blur(sigma); Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2), *ptrd3 = res.data(0,0,0,3), *ptrd4 = res.data(0,0,0,4), *ptrd5 = res.data(0,0,0,5); cimg_forXYZ(*this,x,y,z) { res.get_tensor_at(x,y,z).symmetric_eigen(val,vec); const float _l1 = val[2], _l2 = val[1], _l3 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, l3 = _l3>0?_l3:0, ux = vec(0,0), uy = vec(0,1), uz = vec(0,2), vx = vec(1,0), vy = vec(1,1), vz = vec(1,2), wx = vec(2,0), wy = vec(2,1), wz = vec(2,2), n1 = (float)std::pow(1+l1+l2+l3,-power1), n2 = (float)std::pow(1+l1+l2+l3,-power2); *(ptrd0++) = n1*(ux*ux + vx*vx) + n2*wx*wx; *(ptrd1++) = n1*(ux*uy + vx*vy) + n2*wx*wy; *(ptrd2++) = n1*(ux*uz + vx*vz) + n2*wx*wz; *(ptrd3++) = n1*(uy*uy + vy*vy) + n2*wy*wy; *(ptrd4++) = n1*(uy*uz + vy*vz) + n2*wy*wz; *(ptrd5++) = n1*(uz*uz + vz*vz) + n2*wz*wz; } } else { // for 2d images CImg<floatT> val(2), vec(2,2); get_structure_tensors().move_to(res).blur(sigma); Tfloat *ptrd0 = res.data(0,0,0,0), *ptrd1 = res.data(0,0,0,1), *ptrd2 = res.data(0,0,0,2); cimg_forXY(*this,x,y) { res.get_tensor_at(x,y).symmetric_eigen(val,vec); const float _l1 = val[1], _l2 = val[0], l1 = _l1>0?_l1:0, l2 = _l2>0?_l2:0, ux = vec(1,0), uy = vec(1,1), vx = vec(0,0), vy = vec(0,1), n1 = (float)std::pow(1+l1+l2,-power1), n2 = (float)std::pow(1+l1+l2,-power2); *(ptrd0++) = n1*ux*ux + n2*vx*vx; *(ptrd1++) = n1*ux*uy + n2*vx*vy; *(ptrd2++) = n1*uy*uy + n2*vy*vy; } } return res.move_to(*this); } //! Compute field of diffusion tensors for edge-preserving smoothing \newinstance. CImg<Tfloat> get_diffusion_tensors(const float sharpness=0.7f, const float anisotropy=0.6f, const float alpha=0.6f, const float sigma=1.1f, const bool is_sqrt=false) const { return CImg<Tfloat>(*this,false).diffusion_tensors(sharpness,anisotropy,alpha,sigma,is_sqrt); } //! Estimate displacement field between two images. /** \param source Reference image. \param smoothness Smoothness of estimated displacement field. \param precision Precision required for algorithm convergence. \param nb_scales Number of scales used to estimate the displacement field. \param iteration_max Maximum number of iterations allowed for one scale. \param is_backward If false, match I2(X+U(X)) = I1(X), else match I2(X) = I1(X-U(X)). **/ CImg<T>& displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.0f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false) { return get_displacement(source,smoothness,precision,nb_scales,iteration_max,is_backward).move_to(*this); } //! Estimate displacement field between two images \newinstance. CImg<Tfloat> get_displacement(const CImg<T>& source, const float smoothness=0.1f, const float precision=5.0f, const unsigned int nb_scales=0, const unsigned int iteration_max=10000, const bool is_backward=false) const { if (is_empty() || !source) return +*this; if (!is_sameXYZC(source)) throw CImgArgumentException(_cimg_instance "displacement(): Instance and source image (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, source._width,source._height,source._depth,source._spectrum,source._data); if (precision<0) throw CImgArgumentException(_cimg_instance "displacement(): Invalid specified precision %g " "(should be >=0)", cimg_instance, precision); const unsigned int _nb_scales = nb_scales>0?nb_scales:(unsigned int)(2*std::log((double)(cimg::max(_width,_height)))); const float _precision = (float)std::pow(10.0,-(double)precision); float sm, sM = source.max_min(sm), tm, tM = max_min(tm); const float sdelta = sm==sM?1:(sM - sm), tdelta = tm==tM?1:(tM - tm); const bool is_3d = source._depth>1; CImg<floatT> U; for (int scale = _nb_scales-1; scale>=0; --scale) { const float factor = (float)std::pow(1.5,(double)scale); const unsigned int _sw = (unsigned int)(_width/factor), sw = _sw?_sw:1, _sh = (unsigned int)(_height/factor), sh = _sh?_sh:1, _sd = (unsigned int)(_depth/factor), sd = _sd?_sd:1; if (sw<5 && sh<5 && (!is_3d || sd<5)) continue; // skip too small scales. const CImg<Tfloat> I1 = (source.get_resize(sw,sh,sd,-100,2)-=sm)/=sdelta, I2 = (get_resize(I1,2)-=tm)/=tdelta; if (U) (U*=1.5f).resize(I2._width,I2._height,I2._depth,-100,3); else U.assign(I2._width,I2._height,I2._depth,is_3d?3:2,0); float dt = 2, energy = cimg::type<float>::max(); const CImgList<Tfloat> dI = is_backward?I1.get_gradient():I2.get_gradient(); for (unsigned int iteration = 0; iteration<iteration_max; ++iteration) { float _energy = 0; if (is_3d) { // 3d version. if (smoothness>=0) cimg_for3XYZ(U,x,y,z) { // Isotropic regularization. const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1.linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2.linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c].linear_atXYZ(X,Y,Z) + smoothness* ( Uxx + Uyy + Uzz)))/(1+6*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy + Uz*Uz; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } else { const float nsmoothness = -smoothness; cimg_for3XYZ(U,x,y,z) { // Anisotropic regularization. const float X = is_backward?x - U(x,y,z,0):x + U(x,y,z,0), Y = is_backward?y - U(x,y,z,1):y + U(x,y,z,1), Z = is_backward?z - U(x,y,z,2):z + U(x,y,z,2); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1.linear_atXYZ(X,Y,Z,c) - I2(x,y,z,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,z,c) - I2.linear_atXYZ(X,Y,Z,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,z,c) - U(_p1x,y,z,c)), Uy = 0.5f*(U(x,_n1y,z,c) - U(x,_p1y,z,c)), Uz = 0.5f*(U(x,y,_n1z,c) - U(x,y,_p1z,c)), N2 = Ux*Ux + Uy*Uy + Uz*Uz, N = std::sqrt(N2), N3 = 1e-5 + N2*N, coef_a = (1 - Ux*Ux/N2)/N, coef_b = -2*Ux*Uy/N3, coef_c = -2*Ux*Uz/N3, coef_d = (1 - Uy*Uy/N2)/N, coef_e = -2*Uy*Uz/N3, coef_f = (1 - Uz*Uz/N2)/N, Uxx = U(_n1x,y,z,c) + U(_p1x,y,z,c), Uyy = U(x,_n1y,z,c) + U(x,_p1y,z,c), Uzz = U(x,y,_n1z,c) + U(x,y,_p1z,c), Uxy = 0.25f*(U(_n1x,_n1y,z,c) + U(_p1x,_p1y,z,c) - U(_n1x,_p1y,z,c) - U(_n1x,_p1y,z,c)), Uxz = 0.25f*(U(_n1x,y,_n1z,c) + U(_p1x,y,_p1z,c) - U(_n1x,y,_p1z,c) - U(_n1x,y,_p1z,c)), Uyz = 0.25f*(U(x,_n1y,_n1z,c) + U(x,_p1y,_p1z,c) - U(x,_n1y,_p1z,c) - U(x,_n1y,_p1z,c)); U(x,y,z,c) = (float)(U(x,y,z,c) + dt*(delta_I*dI[c].linear_atXYZ(X,Y,Z) + nsmoothness* ( coef_a*Uxx + coef_b*Uxy + coef_c*Uxz + coef_d*Uyy + coef_e*Uyz + coef_f*Uzz )) )/(1+2*(coef_a+coef_d+coef_f)*nsmoothness*dt); _energy_regul+=N; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } } } else { // 2d version. if (smoothness>=0) cimg_for3XY(U,x,y) { // Isotropic regularization. const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1.linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2.linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c].linear_atXY(X,Y) + smoothness*( Uxx + Uyy )))/(1+4*smoothness*dt); _energy_regul+=Ux*Ux + Uy*Uy; } _energy+=delta_I*delta_I + smoothness*_energy_regul; } else { const float nsmoothness = -smoothness; cimg_for3XY(U,x,y) { // Anisotropic regularization. const float X = is_backward?x - U(x,y,0):x + U(x,y,0), Y = is_backward?y - U(x,y,1):y + U(x,y,1); float delta_I = 0, _energy_regul = 0; if (is_backward) cimg_forC(I2,c) delta_I+=(float)(I1.linear_atXY(X,Y,c) - I2(x,y,c)); else cimg_forC(I2,c) delta_I+=(float)(I1(x,y,c) - I2.linear_atXY(X,Y,c)); cimg_forC(U,c) { const float Ux = 0.5f*(U(_n1x,y,c) - U(_p1x,y,c)), Uy = 0.5f*(U(x,_n1y,c) - U(x,_p1y,c)), N2 = Ux*Ux + Uy*Uy, N = std::sqrt(N2), N3 = 1e-5 + N2*N, coef_a = Uy*Uy/N3, coef_b = -2*Ux*Uy/N3, coef_c = Ux*Ux/N3, Uxx = U(_n1x,y,c) + U(_p1x,y,c), Uyy = U(x,_n1y,c) + U(x,_p1y,c), Uxy = 0.25f*(U(_n1x,_n1y,c) + U(_p1x,_p1y,c) - U(_n1x,_p1y,c) - U(_n1x,_p1y,c)); U(x,y,c) = (float)(U(x,y,c) + dt*(delta_I*dI[c].linear_atXY(X,Y) + nsmoothness*( coef_a*Uxx + coef_b*Uxy + coef_c*Uyy )))/(1+2*(coef_a+coef_c)*nsmoothness*dt); _energy_regul+=N; } _energy+=delta_I*delta_I + nsmoothness*_energy_regul; } } } const float d_energy = (_energy - energy)/(sw*sh*sd); if (d_energy<=0 && -d_energy<_precision) break; if (d_energy>0) dt*=0.5f; energy = _energy; } } return U; } //! Compute distance to a specified value. /** \param value Reference value. \param metric Type of metric. Can be <tt>{ 0=Chebyshev | 1=Manhattan | 2=Euclidean | 3=Squared-euclidean }</tt>. \note The distance transform implementation has been submitted by A. Meijster, and implements the article 'W.H. Hesselink, A. Meijster, J.B.T.M. Roerdink, "A general algorithm for computing distance transforms in linear time.", In: Mathematical Morphology and its Applications to Image and Signal Processing, J. Goutsias, L. Vincent, and D.S. Bloomberg (eds.), Kluwer, 2000, pp. 331-340.' The submitted code has then been modified to fit CImg coding style and constraints. **/ CImg<T>& distance(const T value, const unsigned int metric=2) { if (is_empty()) return *this; bool is_value = false; cimg_for(*this,ptr,T) *ptr = (T)(*ptr==value?is_value=true,0:999999999); if (!is_value) return fill(cimg::type<T>::max()); switch (metric) { case 0 : return _distance_core(_distance_sep_cdt,_distance_dist_cdt); // Chebyshev. case 1 : return _distance_core(_distance_sep_mdt,_distance_dist_mdt); // Manhattan. case 3 : return _distance_core(_distance_sep_edt,_distance_dist_edt); // Euclidean. default : return _distance_core(_distance_sep_edt,_distance_dist_edt).sqrt(); // Squared Euclidean. } return *this; } //! Compute distance to a specified value \newinstance. CImg<Tfloat> get_distance(const T value, const unsigned int metric=2) const { return CImg<Tfloat>(*this,false).distance((Tfloat)value,metric); } static long _distance_sep_edt(const long i, const long u, const long *const g) { return (u*u-i*i+g[u]-g[i])/(2*(u-i)); } static long _distance_dist_edt(const long x, const long i, const long *const g) { return (x-i)*(x-i) + g[i]; } static long _distance_sep_mdt(const long i, const long u, const long *const g) { return (u-i<=g[u]-g[i]?999999999:(g[u]-g[i]+u+i)/2); } static long _distance_dist_mdt(const long x, const long i, const long *const g) { return (x<i?i-x:x-i) + g[i]; } static long _distance_sep_cdt(const long i, const long u, const long *const g) { const long h = (i+u)/2; if (g[i]<=g[u]) { return h<i+g[u]?i+g[u]:h; } return h<u-g[i]?h:u-g[i]; } static long _distance_dist_cdt(const long x, const long i, const long *const g) { const long d = x<i?i-x:x-i; return d<g[i]?g[i]:d; } static void _distance_scan(const unsigned int len, const long *const g, long (*const sep)(const long, const long, const long *const), long (*const f)(const long, const long, const long *const), long *const s, long *const t, long *const dt) { long q = s[0] = t[0] = 0; for (int u = 1; u<(int)len; ++u) { // Forward scan. while ((q>=0) && f(t[q],s[q],g)>f(t[q],u,g)) { --q; } if (q<0) { q = 0; s[0] = u; } else { const long w = 1 + sep(s[q], u, g); if (w<(long)len) { ++q; s[q] = u; t[q] = w; }} } for (int u = (int)len-1; u>=0; --u) { dt[u] = f(u,s[q],g); if (u==t[q]) --q; } // Backward scan. } CImg<T>& _distance_core(long (*const sep)(const long, const long, const long *const), long (*const f)(const long, const long, const long *const)) { const unsigned long wh = (unsigned long)_width*_height; cimg_forC(*this,c) { CImg<longT> g(_width), dt(_width), s(_width), t(_width); CImg<T> img = get_shared_channel(c); cimg_forYZ(*this,y,z) { // Over X-direction. cimg_forX(*this,x) g[x] = (long)img(x,y,z,0,wh); _distance_scan(_width,g,sep,f,s,t,dt); cimg_forX(*this,x) img(x,y,z,0,wh) = (T)dt[x]; } g.assign(_height); dt.assign(_height); s.assign(_height); t.assign(_height); cimg_forXZ(*this,x,z) { // Over Y-direction. cimg_forY(*this,y) g[y] = (long)img(x,y,z,0,wh); _distance_scan(_height,g,sep,f,s,t,dt); cimg_forY(*this,y) img(x,y,z,0,wh) = (T)dt[y]; } if (_depth>1) { g.assign(_depth); dt.assign(_depth); s.assign(_depth); t.assign(_depth); cimg_forXY(*this,x,y) { // Over Z-direction. cimg_forZ(*this,z) g[z] = (long)img(x,y,z,0,wh); _distance_scan(_depth,g,sep,f,s,t,dt); cimg_forZ(*this,z) img(x,y,z,0,wh) = (T)dt[z]; } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric. /** \param value Reference value. \param metric_mask Metric mask. \note The algorithm code has been initially proposed by A. Meijster, and modified by D. Tschumperlé. **/ template<typename t> CImg<T>& distance(const T value, const CImg<t>& metric_mask) { if (is_empty()) return *this; bool is_value = false; cimg_for(*this,ptr,T) *ptr = (T)(*ptr==value?is_value=true,0:999999999); if (!is_value) return fill(cimg::type<T>::max()); const unsigned long wh = (unsigned long)_width*_height; cimg_forC(*this,c) { CImg<T> img = get_shared_channel(c); cimg_forXYZ(metric_mask,dx,dy,dz) { const t weight = metric_mask(dx,dy,dz); if (weight) { for (int z = dz, nz = 0; z<depth(); ++z,++nz) { // Forward scan. for (int y = dy , ny = 0; y<height(); ++y,++ny) { for (int x = dx, nx = 0; x<width(); ++x,++nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } for (int z = depth() - 1 - dz, nz = depth() - 1; z>=0; --z,--nz) { // Backward scan. for (int y = height() - 1 - dy, ny = height() - 1; y>=0; --y,--ny) { for (int x = width() - 1 - dx, nx = width() - 1; x>=0; --x,--nx) { const T dd = img(nx,ny,nz,0,wh) + weight; if (dd<img(x,y,z,0,wh)) img(x,y,z,0,wh) = dd; } } } } } } return *this; } //! Compute chamfer distance to a specified value, with a custom metric \newinstance. template<typename t> CImg<Tfloat> get_distance(const T value, const CImg<t>& metric_mask) const { return CImg<Tfloat>(*this,false).distance(value,metric_mask); } //! Compute distance map to one source point. /** \param x X-coordinate of the source point. \param y Y-coordinate of the source point. \param z Z-coordinate of the source point. \note At input, image instance represents a field of potentials. **/ CImg<T>& distance_dijkstra(const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) { return get_distance_dijkstra(x,y,z).move_to(*this); } //! Compute distance map to one source point \newinstance. CImg<Tfloat> get_distance_dijkstra(const unsigned int x=0, const unsigned int y=0, const unsigned int z=0) const { if (is_empty()) return *this; if (!containsXYZC(x,y,z,0)) throw CImgArgumentException(_cimg_instance "distance_dijkstra(): image instance does not contain specified starting point (%u,%u,%u).", cimg_instance, x,y,z); if (_spectrum!=1) throw CImgInstanceException(_cimg_instance "distance_dijkstra(): image instance is not a scalar image.", cimg_instance); CImg<Tfloat> res(_width,_height,_depth,2); CImg<boolT> in_queue(_width,_height,_depth,1,0); CImg<Tint> Q; unsigned int sizeQ = 0; // Put specified point in priority queue. Q._priority_queue_insert(in_queue,sizeQ,0,x,y,z); res(x,y,z) = 0; res(x,y,z,1) = 0; // Start distance propagation. while (sizeQ) { // Get and remove point with minimal potential from the queue. const int x = (int)Q(0,1), y = (int)Q(0,2), z = (int)Q(0,3); const Tfloat potential = (Tfloat)-Q(0,0); Q._priority_queue_remove(sizeQ); // Update neighbors. Tfloat npot = 0; if (x-1>=0 && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x-1,y,z)+potential),x-1,y,z)) { res(x-1,y,z) = npot; res(x-1,y,z,1) = 2; } if (x+1<width() && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x+1,y,z)+potential),x+1,y,z)) { res(x+1,y,z) = npot; res(x+1,y,z,1) = 1; } if (y-1>=0 && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x,y-1,z)+potential),x,y-1,z)) { res(x,y-1,z) = npot; res(x,y-1,z,1) = 4; } if (y+1<height() && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x,y+1,z)+potential),x,y+1,z)) { res(x,y+1,z) = npot; res(x,y+1,z,1) = 3; } if (z-1>=0 && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x,y,z-1)+potential),x,y,z-1)) { res(x,y,z-1) = npot; res(x,y,z-1,1) = 6; } if (z+1<depth() && Q._priority_queue_insert(in_queue,sizeQ,-(npot=(*this)(x,y,z+1)+potential),x,y,z+1)) { res(x,y,z+1) = npot; res(x,y,z+1,1) = 5; } } return res; } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE. /** \param nb_iterations Number of PDE iterations. \param band_size Size of the narrow band. \param time_step Time step of the PDE iterations. **/ CImg<T>& distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) { if (is_empty()) return *this; CImg<Tfloat> velocity(*this); for (unsigned int iteration = 0; iteration<nb_iterations; ++iteration) { Tfloat *ptrd = velocity._data, veloc_max = 0; if (_depth>1) { // 3d CImg_3x3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3x3(*this,x,y,z,c,I,Tfloat) if (band_size<=0 || cimg::abs(Iccc)<band_size) { const Tfloat gx = (Incc - Ipcc)/2, gy = (Icnc - Icpc)/2, gz = (Iccn - Iccp)/2, sgn = -cimg::sign(Iccc), ix = gx*sgn>0?(Incc - Iccc):(Iccc - Ipcc), iy = gy*sgn>0?(Icnc - Iccc):(Iccc - Icpc), iz = gz*sgn>0?(Iccn - Iccc):(Iccc - Iccp), ng = (Tfloat)(1e-5f + std::sqrt(gx*gx + gy*gy + gz*gz)), ngx = gx/ng, ngy = gy/ng, ngz = gz/ng, veloc = sgn*(ngx*ix + ngy*iy + ngz*iz - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } else { // 2d version CImg_3x3(I,Tfloat); cimg_forC(*this,c) cimg_for3x3(*this,x,y,0,c,I,Tfloat) if (band_size<=0 || cimg::abs(Icc)<band_size) { const Tfloat gx = (Inc - Ipc)/2, gy = (Icn - Icp)/2, sgn = -cimg::sign(Icc), ix = gx*sgn>0?(Inc - Icc):(Icc - Ipc), iy = gy*sgn>0?(Icn - Icc):(Icc - Icp), ng = (Tfloat)(1e-5f + std::sqrt(gx*gx + gy*gy)), ngx = gx/ng, ngy = gy/ng, veloc = sgn*(ngx*ix + ngy*iy - 1); *(ptrd++) = veloc; if (veloc>veloc_max) veloc_max = veloc; else if (-veloc>veloc_max) veloc_max = -veloc; } else *(ptrd++) = 0; } if (veloc_max>0) *this+=(velocity*=time_step/veloc_max); } return *this; } //! Compute distance function to 0-valued isophotes, using the Eikonal PDE \newinstance. CImg<Tfloat> get_distance_eikonal(const unsigned int nb_iterations, const float band_size=0, const float time_step=0.5f) const { return CImg<Tfloat>(*this,false).distance_eikonal(nb_iterations,band_size,time_step); } //! Compute Haar multiscale wavelet transform. /** \param axis Axis considered for the transform. \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) { return get_haar(axis,invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const char axis, const bool invert=false, const unsigned int nb_scales=1) const { if (is_empty() || !nb_scales) return +*this; CImg<Tfloat> res; const Tfloat sqrt2 = std::sqrt(2); if (nb_scales==1) { switch (cimg::uncase(axis)) { // Single scale transform case 'x' : { const unsigned int w = _width/2; if (w) { if (w%2) throw CImgInstanceException(_cimg_instance "haar(): Sub-image width %u is not even at scale %u.", cimg_instance, w); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forYZC(*this,y,z,c) { // Inverse transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(xw,y,z,c); res(x2++,y,z,c) = val0 - val1; res(x2++,y,z,c) = val0 + val1; } } else cimg_forYZC(*this,y,z,c) { // Direct transform along X for (unsigned int x = 0, xw = w, x2 = 0; x<w; ++x, ++xw) { const Tfloat val0 = (Tfloat)(*this)(x2++,y,z,c), val1 = (Tfloat)(*this)(x2++,y,z,c); res(x,y,z,c) = (val0 + val1)/2; res(xw,y,z,c) = (val1 - val0)/2; } } } else return *this; } break; case 'y' : { const unsigned int h = _height/2; if (h) { if (h%2) throw CImgInstanceException(_cimg_instance "haar(): Sub-image height %u is not even at scale %u.", cimg_instance, h); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXZC(*this,x,z,c) { // Inverse transform along Y for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,yh,z,c); res(x,y2++,z,c) = (val0 - val1)/sqrt2; res(x,y2++,z,c) = (val0 + val1)/sqrt2; } } else cimg_forXZC(*this,x,z,c) { for (unsigned int y = 0, yh = h, y2 = 0; y<h; ++y, ++yh) { // Direct transform along Y const Tfloat val0 = (Tfloat)(*this)(x,y2++,z,c), val1 = (Tfloat)(*this)(x,y2++,z,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,yh,z,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; case 'z' : { const unsigned int d = _depth/2; if (d) { if (d%2) throw CImgInstanceException(_cimg_instance "haar(): Sub-image depth %u is not even at scale %u.", cimg_instance, d); res.assign(_width,_height,_depth,_spectrum); if (invert) cimg_forXYC(*this,x,y,c) { // Inverse transform along Z for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { const Tfloat val0 = (Tfloat)(*this)(x,y,z,c), val1 = (Tfloat)(*this)(x,y,zd,c); res(x,y,z2++,c) = (val0 - val1)/sqrt2; res(x,y,z2++,c) = (val0 + val1)/sqrt2; } } else cimg_forXYC(*this,x,y,c) { for (unsigned int z = 0, zd = d, z2 = 0; z<d; ++z, ++zd) { // Direct transform along Z const Tfloat val0 = (Tfloat)(*this)(x,y,z2++,c), val1 = (Tfloat)(*this)(x,y,z2++,c); res(x,y,z,c) = (val0 + val1)/sqrt2; res(x,y,zd,c) = (val1 - val0)/sqrt2; } } } else return *this; } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Multi-scale version if (invert) { res.assign(*this); switch (cimg::uncase(axis)) { case 'x' : { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,w-1).get_haar('x',true,1)); } break; case 'y' : { unsigned int h = _width; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,_width-1,h-1).get_haar('y',true,1)); } break; case 'z' : { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,_width-1,_height-1,d-1).get_haar('z',true,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } else { // Direct transform res = get_haar(axis,false,1); switch (cimg::uncase(axis)) { case 'x' : { for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,w-1).get_haar('x',false,1)); } break; case 'y' : { for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,_width-1,h-1).get_haar('y',false,1)); } break; case 'z' : { for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,_width-1,_height-1,d-1).get_haar('z',false,1)); } break; default : throw CImgArgumentException(_cimg_instance "haar(): Invalid specified axis '%c' " "(should be { x | y | z }).", cimg_instance, axis); } } } return res; } //! Compute Haar multiscale wavelet transform \overloading. /** \param invert Set inverse of direct transform. \param nb_scales Number of scales used for the transform. **/ CImg<T>& haar(const bool invert=false, const unsigned int nb_scales=1) { return get_haar(invert,nb_scales).move_to(*this); } //! Compute Haar multiscale wavelet transform \newinstance. CImg<Tfloat> get_haar(const bool invert=false, const unsigned int nb_scales=1) const { CImg<Tfloat> res; if (nb_scales==1) { // Single scale transform if (_width>1) get_haar('x',invert,1).move_to(res); if (_height>1) { if (res) res.haar('y',invert,1); else get_haar('y',invert,1).move_to(res); } if (_depth>1) { if (res) res.haar('z',invert,1); else get_haar('z',invert,1).move_to(res); } if (res) return res; } else { // Multi-scale transform if (invert) { // Inverse transform res.assign(*this); if (_width>1) { if (_height>1) { if (_depth>1) { unsigned int w = _width, h = _height, d = _depth; for (unsigned int s = 1; w && h && d && s<nb_scales; ++s) { w/=2; h/=2; d/=2; } for (w = w?w:1, h = h?h:1, d = d?d:1; w<=_width && h<=_height && d<=_depth; w*=2, h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w-1,h-1,d-1).get_haar(true,1)); } else { unsigned int w = _width, h = _height; for (unsigned int s = 1; w && h && s<nb_scales; ++s) { w/=2; h/=2; } for (w = w?w:1, h = h?h:1; w<=_width && h<=_height; w*=2, h*=2) res.draw_image(res.get_crop(0,0,0,w-1,h-1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int w = _width, d = _depth; for (unsigned int s = 1; w && d && s<nb_scales; ++s) { w/=2; d/=2; } for (w = w?w:1, d = d?d:1; w<=_width && d<=_depth; w*=2, d*=2) res.draw_image(res.get_crop(0,0,0,w-1,0,d-1).get_haar(true,1)); } else { unsigned int w = _width; for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2; for (w = w?w:1; w<=_width; w*=2) res.draw_image(res.get_crop(0,0,0,w-1,0,0).get_haar(true,1)); } } } else { if (_height>1) { if (_depth>1) { unsigned int h = _height, d = _depth; for (unsigned int s = 1; h && d && s<nb_scales; ++s) { h/=2; d/=2; } for (h = h?h:1, d = d?d:1; h<=_height && d<=_depth; h*=2, d*=2) res.draw_image(res.get_crop(0,0,0,0,h-1,d-1).get_haar(true,1)); } else { unsigned int h = _height; for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2; for (h = h?h:1; h<=_height; h*=2) res.draw_image(res.get_crop(0,0,0,0,h-1,0).get_haar(true,1)); } } else { if (_depth>1) { unsigned int d = _depth; for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2; for (d = d?d:1; d<=_depth; d*=2) res.draw_image(res.get_crop(0,0,0,0,0,d-1).get_haar(true,1)); } else return *this; } } } else { // Direct transform res = get_haar(false,1); if (_width>1) { if (_height>1) { if (_depth>1) for (unsigned int s = 1, w = _width/2, h = _height/2, d = _depth/2; w && h && d && s<nb_scales; ++s, w/=2, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w-1,h-1,d-1).haar(false,1)); else for (unsigned int s = 1, w = _width/2, h = _height/2; w && h && s<nb_scales; ++s, w/=2, h/=2) res.draw_image(res.get_crop(0,0,0,w-1,h-1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, w = _width/2, d = _depth/2; w && d && s<nb_scales; ++s, w/=2, d/=2) res.draw_image(res.get_crop(0,0,0,w-1,0,d-1).haar(false,1)); else for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2) res.draw_image(res.get_crop(0,0,0,w-1,0,0).haar(false,1)); } } else { if (_height>1) { if (_depth>1) for (unsigned int s = 1, h = _height/2, d = _depth/2; h && d && s<nb_scales; ++s, h/=2, d/=2) res.draw_image(res.get_crop(0,0,0,0,h-1,d-1).haar(false,1)); else for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2) res.draw_image(res.get_crop(0,0,0,0,h-1,0).haar(false,1)); } else { if (_depth>1) for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2) res.draw_image(res.get_crop(0,0,0,0,0,d-1).haar(false,1)); else return *this; } } } return res; } return *this; } //! Compute 1d Fast Fourier Transform, along a specified axis. /** \param axis Axis along which the FFT is computed. \param is_invert Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const char axis, const bool is_invert=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],axis,is_invert); return res; } //! Compute n-d Fast Fourier Transform. /* \param is_invert Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ CImgList<Tfloat> get_FFT(const bool is_invert=false) const { CImgList<Tfloat> res(*this,CImg<Tfloat>()); CImg<Tfloat>::FFT(res[0],res[1],is_invert); return res; } //! Compute 1d Fast Fourier Transform, along a specified axis. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param axis Axis along which the FFT is computed. \param is_invert Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const char axis, const bool is_invert=false) { if (!real) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part is empty.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImg<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); #ifdef cimg_use_fftw3 fftw_complex *data_in; fftw_plan data_plan; switch (cimg::uncase(axis)) { case 'x' : { // Fourier along X, using FFTW library. data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) for computing FFT of image (%u,%u,%u,%u) along the X-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width), real._width,real._height,real._depth,real._spectrum); data_plan = fftw_plan_dft_1d(real._width,data_in,data_in,is_invert?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forYZC(real,y,z,c) { T *ptrr = real.data(0,y,z,c), *ptri = imag.data(0,y,z,c); double *ptrd = (double*)data_in; cimg_forX(real,x) { *(ptrd++) = (double)*(ptrr++); *(ptrd++) = (double)*(ptri++); } fftw_execute(data_plan); const unsigned int fact = real._width; if (is_invert) cimg_forX(real,x) { *(--ptri) = (T)(*(--ptrd)/fact); *(--ptrr) = (T)(*(--ptrd)/fact); } else cimg_forX(real,x) { *(--ptri) = (T)*(--ptrd); *(--ptrr) = (T)*(--ptrd); } } } break; case 'y' : { // Fourier along Y, using FFTW library. data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * real._height); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) for computing FFT of image (%u,%u,%u,%u) along the Y-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._height), real._width,real._height,real._depth,real._spectrum); data_plan = fftw_plan_dft_1d(real._height,data_in,data_in,is_invert?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); const unsigned int off = real._width; cimg_forXZC(real,x,z,c) { T *ptrr = real.data(x,0,z,c), *ptri = imag.data(x,0,z,c); double *ptrd = (double*)data_in; cimg_forY(real,y) { *(ptrd++) = (double)*ptrr; *(ptrd++) = (double)*ptri; ptrr+=off; ptri+=off; } fftw_execute(data_plan); const unsigned int fact = real._height; if (is_invert) cimg_forY(real,y) { ptrr-=off; ptri-=off; *ptri = (T)(*(--ptrd)/fact); *ptrr = (T)(*(--ptrd)/fact); } else cimg_forY(real,y) { ptrr-=off; ptri-=off; *ptri = (T)*(--ptrd); *ptrr = (T)*(--ptrd); } } } break; case 'z' : { // Fourier along Z, using FFTW library. data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) for computing FFT of image (%u,%u,%u,%u) along the Z-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._depth), real._width,real._height,real._depth,real._spectrum); data_plan = fftw_plan_dft_1d(real._depth,data_in,data_in,is_invert?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); const unsigned long off = (unsigned long)real._width*real._height; cimg_forXYC(real,x,y,c) { T *ptrr = real.data(x,y,0,c), *ptri = imag.data(x,y,0,c); double *ptrd = (double*)data_in; cimg_forZ(real,z) { *(ptrd++) = (double)*ptrr; *(ptrd++) = (double)*ptri; ptrr+=off; ptri+=off; } fftw_execute(data_plan); const unsigned int fact = real._depth; if (is_invert) cimg_forZ(real,z) { ptrr-=off; ptri-=off; *ptri = (T)(*(--ptrd)/fact); *ptrr = (T)(*(--ptrd)/fact); } else cimg_forZ(real,z) { ptrr-=off; ptri-=off; *ptri = (T)*(--ptrd); *ptrr = (T)*(--ptrd); } } } break; default : { // Fourier along C, using FFTW library. data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * real._spectrum); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) for computing FFT of image (%u,%u,%u,%u) along the C-axis.", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._spectrum), real._width,real._height,real._depth,real._spectrum); data_plan = fftw_plan_dft_1d(real._spectrum,data_in,data_in,is_invert?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); const unsigned long off = (unsigned long)real._width*real._height*real._depth; cimg_forXYZ(real,x,y,z) { T *ptrr = real.data(x,y,z,0), *ptri = imag.data(x,y,z,0); double *ptrd = (double*)data_in; cimg_forC(real,c) { *(ptrd++) = (double)*ptrr; *(ptrd++) = (double)*ptri; ptrr+=off; ptri+=off; } fftw_execute(data_plan); const unsigned int fact = real._spectrum; if (is_invert) cimg_forC(real,c) { ptrr-=off; ptri-=off; *ptri = (T)(*(--ptrd)/fact); *ptrr = (T)(*(--ptrd)/fact); } else cimg_forC(real,c) { ptrr-=off; ptri-=off; *ptri = (T)*(--ptrd); *ptrr = (T)*(--ptrd); } } } } fftw_destroy_plan(data_plan); fftw_free(data_in); #else switch (cimg::uncase(axis)) { case 'x' : { // Fourier along X, using built-in functions. const unsigned int N = real._width, N2 = (N>>1); if (((N-1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) have non 2^N dimension along the X-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forYZC(real,y,z,c) { cimg::swap(real(i,y,z,c),real(j,y,z,c)); cimg::swap(imag(i,y,z,c),imag(j,y,z,c)); if (j<N2) { const unsigned int ri = N-1-i, rj = N-1-j; cimg::swap(real(ri,y,z,c),real(rj,y,z,c)); cimg::swap(imag(ri,y,z,c),imag(rj,y,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_invert?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forYZC(real,y,z,c) { T &ir = real(j,y,z,c), &ii = imag(j,y,z,c), &nir = real(nj,y,z,c), &nii = imag(nj,y,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_invert) { real/=N; imag/=N; } } break; case 'y' : { // Fourier along Y, using built-in functions. const unsigned int N = real._height, N2 = (N>>1); if (((N-1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) have non 2^N dimension along the Y-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXZC(real,x,z,c) { cimg::swap(real(x,i,z,c),real(x,j,z,c)); cimg::swap(imag(x,i,z,c),imag(x,j,z,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,ri,z,c),real(x,rj,z,c)); cimg::swap(imag(x,ri,z,c),imag(x,rj,z,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_invert?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXZC(real,x,z,c) { T &ir = real(x,j,z,c), &ii = imag(x,j,z,c), &nir = real(x,nj,z,c), &nii = imag(x,nj,z,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_invert) { real/=N; imag/=N; } } break; case 'z' : { // Fourier along Z, using built-in functions. const unsigned int N = real._depth, N2 = (N>>1); if (((N-1)&N) && N!=1) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real and imaginary parts (%u,%u,%u,%u) have non 2^N dimension along the Z-axis.", pixel_type(), real._width,real._height,real._depth,real._spectrum); for (unsigned int i = 0, j = 0; i<N2; ++i) { if (j>i) cimg_forXYC(real,x,y,c) { cimg::swap(real(x,y,i,c),real(x,y,j,c)); cimg::swap(imag(x,y,i,c),imag(x,y,j,c)); if (j<N2) { const unsigned int ri = N - 1 - i, rj = N - 1 - j; cimg::swap(real(x,y,ri,c),real(x,y,rj,c)); cimg::swap(imag(x,y,ri,c),imag(x,y,rj,c)); } } for (unsigned int m = N, n = N2; (j+=n)>=m; j-=m, m = n, n>>=1) {} } for (unsigned int delta = 2; delta<=N; delta<<=1) { const unsigned int delta2 = (delta>>1); for (unsigned int i = 0; i<N; i+=delta) { float wr = 1, wi = 0; const float angle = (float)((is_invert?+1:-1)*2*cimg::PI/delta), ca = (float)std::cos(angle), sa = (float)std::sin(angle); for (unsigned int k = 0; k<delta2; ++k) { const unsigned int j = i + k, nj = j + delta2; cimg_forXYC(real,x,y,c) { T &ir = real(x,y,j,c), &ii = imag(x,y,j,c), &nir = real(x,y,nj,c), &nii = imag(x,y,nj,c); const float tmpr = (float)(wr*nir - wi*nii), tmpi = (float)(wr*nii + wi*nir); nir = (T)(ir - tmpr); nii = (T)(ii - tmpi); ir+=(T)tmpr; ii+=(T)tmpi; } const float nwr = wr*ca-wi*sa; wi = wi*ca + wr*sa; wr = nwr; } } } if (is_invert) { real/=N; imag/=N; } } break; default : throw CImgArgumentException("CImgList<%s>::FFT(): Invalid specified axis '%c' for real and imaginary parts (%u,%u,%u,%u) " "(should be { x | y | z }).", pixel_type(),axis, real._width,real._height,real._depth,real._spectrum); } #endif } //! Compute n-d Fast Fourier Transform. /** \param[in,out] real Real part of the pixel values. \param[in,out] imag Imaginary part of the pixel values. \param is_invert Tells if the forward (\c false) or inverse (\c true) FFT is computed. **/ static void FFT(CImg<T>& real, CImg<T>& imag, const bool is_invert=false) { if (!real) throw CImgInstanceException("CImgList<%s>::FFT(): Empty specified real part.", pixel_type()); if (!imag) imag.assign(real._width,real._height,real._depth,real._spectrum,0); if (!real.is_sameXYZC(imag)) throw CImgInstanceException("CImgList<%s>::FFT(): Specified real part (%u,%u,%u,%u,%p) and imaginary part (%u,%u,%u,%u,%p) have different dimensions.", pixel_type(), real._width,real._height,real._depth,real._spectrum,real._data, imag._width,imag._height,imag._depth,imag._spectrum,imag._data); #ifdef cimg_use_fftw3 fftw_complex *data_in = (fftw_complex*)fftw_malloc(sizeof(fftw_complex)*real._width*real._height*real._depth); if (!data_in) throw CImgInstanceException("CImgList<%s>::FFT(): Failed to allocate memory (%s) for computing FFT of image (%u,%u,%u,%u).", pixel_type(), cimg::strbuffersize(sizeof(fftw_complex)*real._width*real._height*real._depth*real._spectrum), real._width,real._height,real._depth,real._spectrum); fftw_plan data_plan; const unsigned long w = (unsigned long)real._width, wh = w*real._height, whd = wh*real._depth; data_plan = fftw_plan_dft_3d(real._width,real._height,real._depth,data_in,data_in,is_invert?FFTW_BACKWARD:FFTW_FORWARD,FFTW_ESTIMATE); cimg_forC(real,c) { T *ptrr = real.data(0,0,0,c), *ptri = imag.data(0,0,0,c); double *ptrd = (double*)data_in; for (unsigned int x = 0; x<real._width; ++x, ptrr-=wh-1, ptri-=wh-1) for (unsigned int y = 0; y<real._height; ++y, ptrr-=whd-w, ptri-=whd-w) for (unsigned int z = 0; z<real._depth; ++z, ptrr+=wh, ptri+=wh) { *(ptrd++) = (double)*ptrr; *(ptrd++) = (double)*ptri; } fftw_execute(data_plan); ptrd = (double*)data_in; ptrr = real.data(0,0,0,c); ptri = imag.data(0,0,0,c); if (!is_invert) for (unsigned int x = 0; x<real._width; ++x, ptrr-=wh-1, ptri-=wh-1) for (unsigned int y = 0; y<real._height; ++y, ptrr-=whd-w, ptri-=whd-w) for (unsigned int z = 0; z<real._depth; ++z, ptrr+=wh, ptri+=wh) { *ptrr = (T)*(ptrd++); *ptri = (T)*(ptrd++); } else for (unsigned int x = 0; x<real._width; ++x, ptrr-=wh-1, ptri-=wh-1) for (unsigned int y = 0; y<real._height; ++y, ptrr-=whd-w, ptri-=whd-w) for (unsigned int z = 0; z<real._depth; ++z, ptrr+=wh, ptri+=wh) { *ptrr = (T)(*(ptrd++)/whd); *ptri = (T)(*(ptrd++)/whd); } } fftw_destroy_plan(data_plan); fftw_free(data_in); #else if (real._depth>1) FFT(real,imag,'z',is_invert); if (real._height>1) FFT(real,imag,'y',is_invert); if (real._width>1) FFT(real,imag,'x',is_invert); #endif } //@} //------------------------------------- // //! \name 3d Objects Management //@{ //------------------------------------- //! Shift 3d object's vertices. /** \param tx X-coordinate of the 3d displacement vector. \param ty Y-coordinate of the 3d displacement vector. \param tz Z-coordinate of the 3d displacement vector. **/ CImg<T>& shift_object3d(const float tx, const float ty=0, const float tz=0) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3d vertices.", cimg_instance); get_shared_row(0)+=tx; get_shared_row(1)+=ty; get_shared_row(2)+=tz; return *this; } //! Shift 3d object's vertices \newinstance. CImg<Tfloat> get_shift_object3d(const float tx, const float ty=0, const float tz=0) const { return CImg<Tfloat>(*this,false).shift_object3d(tx,ty,tz); } //! Shift 3d object's vertices, so that it becomes centered. /** \note The object center is computed as its barycenter. **/ CImg<T>& shift_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "shift_object3d(): Instance is not a set of 3d vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); xcoords-=(xm + xM)/2; ycoords-=(ym + yM)/2; zcoords-=(zm + zM)/2; return *this; } //! Shift 3d object's vertices, so that it becomes centered \newinstance. CImg<Tfloat> get_shift_object3d() const { return CImg<Tfloat>(*this,false).shift_object3d(); } //! Resize 3d object. /** \param sx Width of the 3d object's bounding box. \param sy Height of the 3d object's bounding box. \param sz Depth of the 3d object's bounding box. **/ CImg<T>& resize_object3d(const float sx, const float sy=-100, const float sz=-100) { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3d vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); if (xm<xM) { if (sx>0) xcoords*=sx/(xM-xm); else xcoords*=-sx/100; } if (ym<yM) { if (sy>0) ycoords*=sy/(yM-ym); else ycoords*=-sy/100; } if (zm<zM) { if (sz>0) zcoords*=sz/(zM-zm); else zcoords*=-sz/100; } return *this; } //! Resize 3d object \newinstance. CImg<Tfloat> get_resize_object3d(const float sx, const float sy=-100, const float sz=-100) const { return CImg<Tfloat>(*this,false).resize_object3d(sx,sy,sz); } //! Resize 3d object to unit size. CImg<T> resize_object3d() { if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "resize_object3d(): Instance is not a set of 3d vertices.", cimg_instance); CImg<T> xcoords = get_shared_row(0), ycoords = get_shared_row(1), zcoords = get_shared_row(2); float xm, xM = (float)xcoords.max_min(xm), ym, yM = (float)ycoords.max_min(ym), zm, zM = (float)zcoords.max_min(zm); const float dx = xM - xm, dy = yM - ym, dz = zM - zm, dmax = cimg::max(dx,dy,dz); if (dmax>0) { xcoords/=dmax; ycoords/=dmax; zcoords/=dmax; } return *this; } //! Resize 3d object to unit size \newinstance. CImg<Tfloat> get_resize_object3d() const { return CImg<Tfloat>(*this,false).resize_object3d(); } //! Merge two 3d objects together. /** \param[in,out] primitives Primitives data of the current 3d object. \param obj_vertices Vertices data of the additional 3d object. \param obj_primitives Primitives data of the additional 3d object. **/ template<typename tf, typename tp, typename tff> CImg<T>& append_object3d(CImgList<tf>& primitives, const CImg<tp>& obj_vertices, const CImgList<tff>& obj_primitives) { if (!obj_vertices || !obj_primitives) return *this; if (obj_vertices._height!=3 || obj_vertices._depth>1 || obj_vertices._spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Specified vertice image (%u,%u,%u,%u,%p) is not a set of 3d vertices.", cimg_instance, obj_vertices._width,obj_vertices._height,obj_vertices._depth,obj_vertices._spectrum,obj_vertices._data); if (is_empty()) { primitives.assign(obj_primitives); return assign(obj_vertices); } if (_height!=3 || _depth>1 || _spectrum>1) throw CImgInstanceException(_cimg_instance "append_object3d(): Instance is not a set of 3d vertices.", cimg_instance); const unsigned int P = _width; append(obj_vertices,'x'); const unsigned int N = primitives._width; primitives.insert(obj_primitives); for (unsigned int i = N; i<primitives._width; ++i) { CImg<tf> &p = primitives[i]; switch (p.size()) { case 1 : p[0]+=P; break; // Point. case 5 : p[0]+=P; p[1]+=P; break; // Sphere. case 2 : case 6 : p[0]+=P; p[1]+=P; break; // Segment. case 3 : case 9 : p[0]+=P; p[1]+=P; p[2]+=P; break; // Triangle. case 4 : case 12 : p[0]+=P; p[1]+=P; p[2]+=P; p[3]+=P; break; // Rectangle. } } return *this; } //! Texturize primitives of a 3d object. /** \param[in,out] primitives Primitives data of the 3d object. \param[in,out] colors Colors data of the 3d object. \param texture Texture image to map to 3d object. \param coords Texture-mapping coordinates. **/ template<typename tp, typename tc, typename tt, typename tx> const CImg<T>& texturize_object3d(CImgList<tp>& primitives, CImgList<tc>& colors, const CImg<tt>& texture, const CImg<tx>& coords=CImg<tx>::empty()) const { if (is_empty()) return *this; if (_height!=3) throw CImgInstanceException(_cimg_instance "texturize_object3d(): image instance is not a set of 3d points.", cimg_instance); if (coords && (coords._width!=_width || coords._height!=2)) throw CImgArgumentException(_cimg_instance "texturize_object3d(): Invalid specified texture coordinates (%u,%u,%u,%u,%p).", cimg_instance, coords._width,coords._height,coords._depth,coords._spectrum,coords._data); CImg<unsigned int> _coords; if (!coords) { // If no texture coordinates specified, do a default XY-projection. _coords.assign(_width,2); float xmin, xmax = (float)get_shared_row(0).max_min(xmin), ymin, ymax = (float)get_shared_row(1).max_min(ymin), dx = xmax>xmin?xmax-xmin:1, dy = ymax>ymin?ymax-ymin:1; cimg_forX(*this,p) { _coords(p,0) = (unsigned int)(((*this)(p,0)-xmin)*(texture._width-1)/dx); _coords(p,1) = (unsigned int)(((*this)(p,1)-ymin)*(texture._height-1)/dy); } } else _coords = coords; int texture_ind = -1; cimglist_for(primitives,l) { CImg<tp> &p = primitives[l]; const unsigned int siz = p.size(); switch (siz) { case 1 : { // Point. const unsigned int i0 = (unsigned int)p[0], x0 = (unsigned int)_coords(i0,0), y0 = (unsigned int)_coords(i0,1); texture.get_vector_at(x0,y0).move_to(colors[l]); } break; case 2 : case 6 : { // Line. const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], x0 = (unsigned int)_coords(i0,0), y0 = (unsigned int)_coords(i0,1), x1 = (unsigned int)_coords(i1,0), y1 = (unsigned int)_coords(i1,1); if (texture_ind<0) colors[texture_ind=l] = texture; else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,x0,y0,x1,y1).move_to(p); } break; case 3 : case 9 : { // Triangle. const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2], x0 = (unsigned int)_coords(i0,0), y0 = (unsigned int)_coords(i0,1), x1 = (unsigned int)_coords(i1,0), y1 = (unsigned int)_coords(i1,1), x2 = (unsigned int)_coords(i2,0), y2 = (unsigned int)_coords(i2,1); if (texture_ind<0) colors[texture_ind=l] = texture; else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,x0,y0,x1,y1,x2,y2).move_to(p); } break; case 4 : case 12 : { // Quadrangle. const unsigned int i0 = (unsigned int)p[0], i1 = (unsigned int)p[1], i2 = (unsigned int)p[2], i3 = (unsigned int)p[3], x0 = (unsigned int)_coords(i0,0), y0 = (unsigned int)_coords(i0,1), x1 = (unsigned int)_coords(i1,0), y1 = (unsigned int)_coords(i1,1), x2 = (unsigned int)_coords(i2,0), y2 = (unsigned int)_coords(i2,1), x3 = (unsigned int)_coords(i3,0), y3 = (unsigned int)_coords(i3,1); if (texture_ind<0) colors[texture_ind=l] = texture; else colors[l].assign(colors[texture_ind],true); CImg<tp>::vector(i0,i1,i2,i3,x0,y0,x1,y1,x2,y2,x3,y3).move_to(p); } break; } } return *this; } //! Generate a 3d elevation of the image instance. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param[out] colors The returned list of the 3d object colors. \param elevation The input elevation map. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; CImgList<unsigned char> colors3d; const CImg<float> points3d = img.get_elevation3d(faces3d,colors,img.get_norm()*0.2); CImg<unsigned char>().display_object3d("Elevation3d",points3d,faces3d,colors3d); \endcode \image html ref_elevation3d.jpg **/ template<typename tf, typename tc, typename te> CImg<floatT> get_elevation3d(CImgList<tf>& primitives, CImgList<tc>& colors, const CImg<te>& elevation) const { if (!is_sameXY(elevation) || elevation._depth>1 || elevation._spectrum>1) throw CImgArgumentException(_cimg_instance "get_elevation3d(): Instance and specified elevation (%u,%u,%u,%u,%p) " "have incompatible dimensions.", cimg_instance, elevation._width,elevation._height,elevation._depth,elevation._spectrum,elevation._data); if (is_empty()) return *this; float m, M = (float)max_min(m); if (M==m) ++M; colors.assign(); const unsigned int size_x1 = _width - 1, size_y1 = _height - 1; for (unsigned int y = 0; y<size_y1; ++y) for (unsigned int x = 0; x<size_x1; ++x) { const unsigned char r = (unsigned char)(((*this)(x,y,0) - m)*255/(M-m)), g = _spectrum>1?(unsigned char)(((*this)(x,y,1) - m)*255/(M-m)):r, b = _spectrum>2?(unsigned char)(((*this)(x,y,2) - m)*255/(M-m)):(_spectrum>1?0:r); CImg<tc>::vector((tc)r,(tc)g,(tc)b).move_to(colors); } const typename CImg<te>::_functor2d_int func(elevation); return elevation3d(primitives,func,0,0,_width-1.0f,_height-1.0f,_width,_height); } //! Generate the 3d projection planes of the image instance. /** \param[out] primitives Primitives data of the returned 3d object. \param[out] colors Colors data of the returned 3d object. \param x0 X-coordinate of the projection point. \param y0 Y-coordinate of the projection point. \param z0 Z-coordinate of the projection point. \param normalize_colors Tells if the created textures have normalized colors. **/ template<typename tf, typename tc> CImg<floatT> get_projections3d(CImgList<tf>& primitives, CImgList<tc>& colors, const unsigned int x0, const unsigned int y0, const unsigned int z0, const bool normalize_colors=false) const { float m = 0, M = 0, delta = 1; if (normalize_colors) { m = (float)min_max(M); delta = 255/(m==M?1:M-m); } const unsigned int _x0 = (x0>=_width)?_width - 1:x0, _y0 = (y0>=_height)?_height - 1:y0, _z0 = (z0>=_depth)?_depth - 1:z0; CImg<tc> img_xy, img_xz, img_yz; if (normalize_colors) { ((get_crop(0,0,_z0,0,_width-1,_height-1,_z0,_spectrum-1)-=m)*=delta).move_to(img_xy); ((get_crop(0,_y0,0,0,_width-1,_y0,_depth-1,_spectrum-1)-=m)*=delta).resize(_width,_depth,1,-100,-1).move_to(img_xz); ((get_crop(_x0,0,0,0,_x0,_height-1,_depth-1,_spectrum-1)-=m)*=delta).resize(_height,_depth,1,-100,-1).move_to(img_yz); } else { get_crop(0,0,_z0,0,_width-1,_height-1,_z0,_spectrum-1).move_to(img_xy); get_crop(0,_y0,0,0,_width-1,_y0,_depth-1,_spectrum-1).resize(_width,_depth,1,-100,-1).move_to(img_xz); get_crop(_x0,0,0,0,_x0,_height-1,_depth-1,_spectrum-1).resize(_height,_depth,1,-100,-1).move_to(img_yz); } CImg<floatT> points(12,3,1,1, 0,_width-1,_width-1,0, 0,_width-1,_width-1,0, _x0,_x0,_x0,_x0, 0,0,_height-1,_height-1, _y0,_y0,_y0,_y0, 0,_height-1,_height-1,0, _z0,_z0,_z0,_z0, 0,0,_depth-1,_depth-1, 0,0,_depth-1,_depth-1); primitives.assign(); CImg<tf>::vector(0,1,2,3,0,0,img_xy._width-1,0,img_xy._width-1,img_xy._height-1,0,img_xy._height-1).move_to(primitives); CImg<tf>::vector(4,5,6,7,0,0,img_xz._width-1,0,img_xz._width-1,img_xz._height-1,0,img_xz._height-1).move_to(primitives); CImg<tf>::vector(8,9,10,11,0,0,img_yz._width-1,0,img_yz._width-1,img_yz._height-1,0,img_yz._height-1).move_to(primitives); colors.assign(); img_xy.move_to(colors); img_xz.move_to(colors); img_yz.move_to(colors); return points; } //! Generate a isoline of the image instance as a 3d object. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3d object colors. \param size_x The number of subdivisions along the X-axis. \param size_y The number of subdisivions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code const CImg<float> img("reference.jpg"); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isoline3d(faces3d,100); CImg<unsigned char>().display_object3d("Isoline3d",points3d,faces3d,colors3d); \endcode \image html ref_isoline3d.jpg **/ template<typename tf> CImg<floatT> get_isoline3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a scalar image.", cimg_instance); if (_depth>1) throw CImgInstanceException(_cimg_instance "get_isoline3d(): Instance is not a 2d image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100) || (size_x==width() && size_y==height())) { const _functor2d_int func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width()-1.0f,height()-1.0f,width(),height()); } else { const _functor2d_float func(*this); vertices = isoline3d(primitives,func,isovalue,0,0,width()-1.0f,height()-1.0f,size_x,size_y); } return vertices; } //! Generate an isosurface of the image instance as a 3d object. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param isovalue The returned list of the 3d object colors. \param size_x Number of subdivisions along the X-axis. \param size_y Number of subdisivions along the Y-axis. \param size_z Number of subdisivions along the Z-axis. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code const CImg<float> img = CImg<unsigned char>("reference.jpg").resize(-100,-100,20); CImgList<unsigned int> faces3d; const CImg<float> points3d = img.get_isosurface3d(faces3d,100); CImg<unsigned char>().display_object3d("Isosurface3d",points3d,faces3d,colors3d); \endcode \image html ref_isosurface3d.jpg **/ template<typename tf> CImg<floatT> get_isosurface3d(CImgList<tf>& primitives, const float isovalue, const int size_x=-100, const int size_y=-100, const int size_z=-100) const { if (_spectrum>1) throw CImgInstanceException(_cimg_instance "get_isosurface3d(): Instance is not a scalar image.", cimg_instance); primitives.assign(); if (is_empty()) return *this; CImg<floatT> vertices; if ((size_x==-100 && size_y==-100 && size_z==-100) || (size_x==width() && size_y==height() && size_z==depth())) { const _functor3d_int func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width()-1.0f,height()-1.0f,depth()-1.0f,width(),height(),depth()); } else { const _functor3d_float func(*this); vertices = isosurface3d(primitives,func,isovalue,0,0,0,width()-1.0f,height()-1.0f,depth()-1.0f,size_x,size_y,size_z); } return vertices; } //! Compute 3d elevation of a function as a 3d object. /** \param[out] primitives Primitives data of the resulting 3d object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. **/ template<typename tf, typename tfunc> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const tfunc& func, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const float nx0 = x0<x1?x0:x1, ny0 = y0<y1?y0:y1, nx1 = x0<x1?x1:x0, ny1 = y0<y1?y1:y0; const unsigned int _nsize_x = (unsigned int)(size_x>=0?size_x:(nx1-nx0)*-size_x/100), nsize_x = _nsize_x?_nsize_x:1, nsize_x1 = nsize_x - 1, _nsize_y = (unsigned int)(size_y>=0?size_y:(ny1-ny0)*-size_y/100), nsize_y = _nsize_y?_nsize_y:1, nsize_y1 = nsize_y - 1; if (nsize_x<2 || nsize_y<2) throw CImgArgumentException("CImg<%s>::elevation3d(): Invalid specified size (%d,%d).", pixel_type(), nsize_x,nsize_y); CImg<floatT> vertices(nsize_x*nsize_y,3); floatT *ptr_x = vertices.data(0,0), *ptr_y = vertices.data(0,1), *ptr_z = vertices.data(0,2); for (unsigned int y = 0; y<nsize_y; ++y) { const float Y = ny0 + y*(ny1-ny0)/nsize_y1; for (unsigned int x = 0; x<nsize_x; ++x) { const float X = nx0 + x*(nx1-nx0)/nsize_x1; *(ptr_x++) = (float)x; *(ptr_y++) = (float)y; *(ptr_z++) = (float)func(X,Y); } } primitives.assign(nsize_x1*nsize_y1,1,4); for (unsigned int p = 0, y = 0; y<nsize_y1; ++y) { const unsigned int yw = y*nsize_x; for (unsigned int x = 0; x<nsize_x1; ++x) { const unsigned int xpyw = x + yw, xpyww = xpyw + nsize_x; primitives[p++].fill(xpyw,xpyww,xpyww+1,xpyw+1); } } return vertices; } //! Compute 3d elevation of a function, as a 3d object \overloading. template<typename tf> static CImg<floatT> elevation3d(CImgList<tf>& primitives, const char *const expression, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return elevation3d(primitives,func,x0,y0,x1,y1,size_x,size_y); } //! Compute 0-isolines of a function, as a 3d object. /** \param[out] primitives Primitives data of the resulting 3d object. \param func Elevation function. Is of type <tt>float (*func)(const float x,const float y)</tt>. \param isovalue Isovalue to extract from function. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param size_x Resolution of the function along the X-axis. \param size_y Resolution of the function along the Y-axis. \note Use the marching squares algorithm for extracting the isolines. **/ template<typename tf, typename tfunc> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { static const unsigned int edges[16] = { 0x0, 0x9, 0x3, 0xa, 0x6, 0xf, 0x5, 0xc, 0xc, 0x5, 0xf, 0x6, 0xa, 0x3, 0x9, 0x0 }; static const int segments[16][4] = { { -1,-1,-1,-1 }, { 0,3,-1,-1 }, { 0,1,-1,-1 }, { 1,3,-1,-1 }, { 1,2,-1,-1 }, { 0,1,2,3 }, { 0,2,-1,-1 }, { 2,3,-1,-1 }, { 2,3,-1,-1 }, { 0,2,-1,-1}, { 0,3,1,2 }, { 1,2,-1,-1 }, { 1,3,-1,-1 }, { 0,1,-1,-1}, { 0,3,-1,-1}, { -1,-1,-1,-1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nxm1 = nx - 1, nym1 = ny - 1; primitives.assign(); if (!nxm1 || !nym1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1; CImgList<floatT> vertices; CImg<intT> indices1(nx,1,1,2,-1), indices2(nx,1,1,2); CImg<floatT> values1(nx), values2(nx); float X = x0, Y = y0, nX = X + dx, nY = Y + dy; // Fill first line with values cimg_forX(values1,x) { values1(x) = (float)func(X,Y); X+=dx; } // Run the marching squares algorithm for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y=nY, nY+=dy) { X = x0; nX = X + dx; indices2.fill(-1); for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X=nX, nX+=dx) { // Determine square configuration const float val0 = values1(xi), val1 = values1(nxi), val2 = values2(nxi) = (float)func(nX,nY), val3 = values2(xi) = (float)func(X,nY); const unsigned int configuration = (val0<isovalue?1:0) | (val1<isovalue?2:0) | (val2<isovalue?4:0) | (val3<isovalue?8:0), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,0) = vertices._width; CImg<floatT>::vector(Xi,Y,0).move_to(vertices); } if ((edge&2) && indices1(nxi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,1) = vertices._width; CImg<floatT>::vector(nX,Yi,0).move_to(vertices); } if ((edge&4) && indices2(xi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices2(xi,0) = vertices._width; CImg<floatT>::vector(Xi,nY,0).move_to(vertices); } if ((edge&8) && indices1(xi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,1) = vertices._width; CImg<floatT>::vector(X,Yi,0).move_to(vertices); } // Create segments for (const int *segment = segments[configuration]; *segment!=-1; ) { const unsigned int p0 = *(segment++), p1 = *(segment++); const tf i0 = (tf)(_isoline3d_indice(p0,indices1,indices2,xi,nxi)), i1 = (tf)(_isoline3d_indice(p1,indices1,indices2,xi,nxi)); CImg<tf>::vector(i0,i1).move_to(primitives); } } } values1.swap(values2); indices1.swap(indices2); } return vertices>'x'; } //! Compute isolines of a function, as a 3d object \overloading. template<typename tf> static CImg<floatT> isoline3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float x1, const float y1, const int size_x=256, const int size_y=256) { const _functor2d_expr func(expression); return isoline3d(primitives,func,isovalue,x0,y0,x1,y1,size_x,size_y); } template<typename t> static int _isoline3d_indice(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int nx) { switch (edge) { case 0 : return (int)indices1(x,0); case 1 : return (int)indices1(nx,1); case 2 : return (int)indices2(x,0); case 3 : return (int)indices1(x,1); } return 0; } //! Compute isosurface of a function, as a 3d object. /** \param[out] primitives Primitives data of the resulting 3d object. \param func Implicit function. Is of type <tt>float (*func)(const float x, const float y, const float z)</tt>. \param isovalue Isovalue to extract. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point. \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param size_x Resolution of the elevation function along the X-axis. \param size_y Resolution of the elevation function along the Y-axis. \param size_z Resolution of the elevation function along the Z-axis. \note Use the marching cubes algorithm for extracting the isosurface. **/ template<typename tf, typename tfunc> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const tfunc& func, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int size_x=32, const int size_y=32, const int size_z=32) { static unsigned int edges[256] = { 0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000 }; static int triangles[256][16] = { { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1 }, { 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1 }, { 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1 }, { 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1 }, { 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1 }, { 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1 }, { 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1 }, { 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1 }, { 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1 }, { 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1 }, { 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1 }, { 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1 }, { 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1 }, { 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1 }, { 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1 }, { 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1 }, { 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1 }, { 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1 }, { 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1 }, { 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1 }, { 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1 }, { 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1 }, { 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1 }, { 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1 }, { 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1 }, { 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1 }, { 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1 }, { 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1 }, { 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1 }, { 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1 }, { 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1 }, { 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1 }, { 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1 }, { 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1 }, { 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1 }, { 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1 }, { 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1 }, { 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1 }, { 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1 }, { 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1 }, { 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1 }, { 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1 }, { 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1 }, { 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1 }, { 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1 }, { 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1 }, { 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1 }, { 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1 }, { 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1 }, { 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1 }, { 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1 }, { 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1 }, { 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1 }, { 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1 }, { 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1 }, { 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1 }, { 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1 }, { 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1 }, { 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1 }, { 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1 }, { 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1 }, { 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1 }, { 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1 }, { 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1 }, { 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1 }, { 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1 }, { 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1 }, { 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1 }, { 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1 }, { 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1 }, { 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1 }, { 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1 }, { 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1 }, { 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1 }, { 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1 }, { 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1 }, { 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1 }, { 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1 }, { 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1 }, { 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1 }, { 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1 }, { 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1 }, { 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1 }, { 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1 }, { 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1 }, { 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1 }, { 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1 }, { 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1 }, { 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1 }, { 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1 }, { 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1 }, { 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1 }, { 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1 }, { 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1 }, { 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1 }, { 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1 }, { 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1 }, { 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1 }, { 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1 }, { 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1 }, { 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1 }, { 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1 }, { 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1 }, { 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1 }, { 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1 }, { 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1 }, { 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1 }, { 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1 }, { 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1 }, { 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1 }, { 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1 }, { 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1 }, { 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1 }, { 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1 }, { 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1 }, { 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1 }, { 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1 }, { 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1 }, { 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1 }, { 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1 }, { 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1 }, { 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1 }, { 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1 }, { 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1 }, { 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1 }, { 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }, { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } }; const unsigned int _nx = (unsigned int)(size_x>=0?size_x:cimg::round((x1-x0)*-size_x/100 + 1)), _ny = (unsigned int)(size_y>=0?size_y:cimg::round((y1-y0)*-size_y/100 + 1)), _nz = (unsigned int)(size_z>=0?size_z:cimg::round((z1-z0)*-size_z/100 + 1)), nx = _nx?_nx:1, ny = _ny?_ny:1, nz = _nz?_nz:1, nxm1 = nx - 1, nym1 = ny - 1, nzm1 = nz - 1; primitives.assign(); if (!nxm1 || !nym1 || !nzm1) return CImg<floatT>(); const float dx = (x1 - x0)/nxm1, dy = (y1 - y0)/nym1, dz = (z1 - z0)/nzm1; CImgList<floatT> vertices; CImg<intT> indices1(nx,ny,1,3,-1), indices2(indices1); CImg<floatT> values1(nx,ny), values2(nx,ny); float X = 0, Y = 0, Z = 0, nX = 0, nY = 0, nZ = 0; // Fill the first plane with function values Y = y0; cimg_forY(values1,y) { X = x0; cimg_forX(values1,x) { values1(x,y) = (float)func(X,Y,z0); X+=dx; } Y+=dy; } // Run Marching Cubes algorithm Z = z0; nZ = Z + dz; for (unsigned int zi = 0; zi<nzm1; ++zi, Z = nZ, nZ+=dz) { Y = y0; nY = Y + dy; indices2.fill(-1); for (unsigned int yi = 0, nyi = 1; yi<nym1; ++yi, ++nyi, Y = nY, nY+=dy) { X = x0; nX = X + dx; for (unsigned int xi = 0, nxi = 1; xi<nxm1; ++xi, ++nxi, X = nX, nX+=dx) { // Determine cube configuration const float val0 = values1(xi,yi), val1 = values1(nxi,yi), val2 = values1(nxi,nyi), val3 = values1(xi,nyi), val4 = values2(xi,yi) = (float)func(X,Y,nZ), val5 = values2(nxi,yi) = (float)func(nX,Y,nZ), val6 = values2(nxi,nyi) = (float)func(nX,nY,nZ), val7 = values2(xi,nyi) = (float)func(X,nY,nZ); const unsigned int configuration = (val0<isovalue?1:0) | (val1<isovalue?2:0) | (val2<isovalue?4:0) | (val3<isovalue?8:0) | (val4<isovalue?16:0) | (val5<isovalue?32:0) | (val6<isovalue?64:0) | (val7<isovalue?128:0), edge = edges[configuration]; // Compute intersection vertices if (edge) { if ((edge&1) && indices1(xi,yi,0)<0) { const float Xi = X + (isovalue-val0)*dx/(val1-val0); indices1(xi,yi,0) = vertices._width; CImg<floatT>::vector(Xi,Y,Z).move_to(vertices); } if ((edge&2) && indices1(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val1)*dy/(val2-val1); indices1(nxi,yi,1) = vertices._width; CImg<floatT>::vector(nX,Yi,Z).move_to(vertices); } if ((edge&4) && indices1(xi,nyi,0)<0) { const float Xi = X + (isovalue-val3)*dx/(val2-val3); indices1(xi,nyi,0) = vertices._width; CImg<floatT>::vector(Xi,nY,Z).move_to(vertices); } if ((edge&8) && indices1(xi,yi,1)<0) { const float Yi = Y + (isovalue-val0)*dy/(val3-val0); indices1(xi,yi,1) = vertices._width; CImg<floatT>::vector(X,Yi,Z).move_to(vertices); } if ((edge&16) && indices2(xi,yi,0)<0) { const float Xi = X + (isovalue-val4)*dx/(val5-val4); indices2(xi,yi,0) = vertices._width; CImg<floatT>::vector(Xi,Y,nZ).move_to(vertices); } if ((edge&32) && indices2(nxi,yi,1)<0) { const float Yi = Y + (isovalue-val5)*dy/(val6-val5); indices2(nxi,yi,1) = vertices._width; CImg<floatT>::vector(nX,Yi,nZ).move_to(vertices); } if ((edge&64) && indices2(xi,nyi,0)<0) { const float Xi = X + (isovalue-val7)*dx/(val6-val7); indices2(xi,nyi,0) = vertices._width; CImg<floatT>::vector(Xi,nY,nZ).move_to(vertices); } if ((edge&128) && indices2(xi,yi,1)<0) { const float Yi = Y + (isovalue-val4)*dy/(val7-val4); indices2(xi,yi,1) = vertices._width; CImg<floatT>::vector(X,Yi,nZ).move_to(vertices); } if ((edge&256) && indices1(xi,yi,2)<0) { const float Zi = Z+ (isovalue-val0)*dz/(val4-val0); indices1(xi,yi,2) = vertices._width; CImg<floatT>::vector(X,Y,Zi).move_to(vertices); } if ((edge&512) && indices1(nxi,yi,2)<0) { const float Zi = Z + (isovalue-val1)*dz/(val5-val1); indices1(nxi,yi,2) = vertices._width; CImg<floatT>::vector(nX,Y,Zi).move_to(vertices); } if ((edge&1024) && indices1(nxi,nyi,2)<0) { const float Zi = Z + (isovalue-val2)*dz/(val6-val2); indices1(nxi,nyi,2) = vertices._width; CImg<floatT>::vector(nX,nY,Zi).move_to(vertices); } if ((edge&2048) && indices1(xi,nyi,2)<0) { const float Zi = Z + (isovalue-val3)*dz/(val7-val3); indices1(xi,nyi,2) = vertices._width; CImg<floatT>::vector(X,nY,Zi).move_to(vertices); } // Create triangles for (const int *triangle = triangles[configuration]; *triangle!=-1; ) { const unsigned int p0 = *(triangle++), p1 = *(triangle++), p2 = *(triangle++); const tf i0 = (tf)(_isosurface3d_indice(p0,indices1,indices2,xi,yi,nxi,nyi)), i1 = (tf)(_isosurface3d_indice(p1,indices1,indices2,xi,yi,nxi,nyi)), i2 = (tf)(_isosurface3d_indice(p2,indices1,indices2,xi,yi,nxi,nyi)); CImg<tf>::vector(i0,i2,i1).move_to(primitives); } } } } cimg::swap(values1,values2); cimg::swap(indices1,indices2); } return vertices>'x'; } //! Compute isosurface of a function, as a 3d object \overloading. template<typename tf> static CImg<floatT> isosurface3d(CImgList<tf>& primitives, const char *const expression, const float isovalue, const float x0, const float y0, const float z0, const float x1, const float y1, const float z1, const int dx=32, const int dy=32, const int dz=32) { const _functor3d_expr func(expression); return isosurface3d(primitives,func,isovalue,x0,y0,z0,x1,y1,z1,dx,dy,dz); } template<typename t> static int _isosurface3d_indice(const unsigned int edge, const CImg<t>& indices1, const CImg<t>& indices2, const unsigned int x, const unsigned int y, const unsigned int nx, const unsigned int ny) { switch (edge) { case 0 : return indices1(x,y,0); case 1 : return indices1(nx,y,1); case 2 : return indices1(x,ny,0); case 3 : return indices1(x,y,1); case 4 : return indices2(x,y,0); case 5 : return indices2(nx,y,1); case 6 : return indices2(x,ny,0); case 7 : return indices2(x,y,1); case 8 : return indices1(x,y,2); case 9 : return indices1(nx,y,2); case 10 : return indices1(nx,ny,2); case 11 : return indices1(x,ny,2); } return 0; } // Define functors for accessing image values (used in previous functions). struct _functor2d_int { const CImg<T>& ref; _functor2d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref((int)x,(int)y); } }; struct _functor2d_float { const CImg<T>& ref; _functor2d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y) const { return (float)ref._linear_atXY(x,y); } }; struct _functor2d_expr { _cimg_math_parser *mp; _functor2d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(CImg<T>::empty(),expr,0); } ~_functor2d_expr() { delete mp; } float operator()(const float x, const float y) const { return (float)mp->eval(x,y,0,0); } }; struct _functor3d_int { const CImg<T>& ref; _functor3d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref((int)x,(int)y,(int)z); } }; struct _functor3d_float { const CImg<T>& ref; _functor3d_float(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z) const { return (float)ref._linear_atXYZ(x,y,z); } }; struct _functor3d_expr { _cimg_math_parser *mp; ~_functor3d_expr() { delete mp; } _functor3d_expr(const char *const expr):mp(0) { mp = new _cimg_math_parser(CImg<T>::empty(),expr,0); } float operator()(const float x, const float y, const float z) const { return (float)mp->eval(x,y,z,0); } }; struct _functor4d_int { const CImg<T>& ref; _functor4d_int(const CImg<T>& pref):ref(pref) {} float operator()(const float x, const float y, const float z, const unsigned int c) const { return (float)ref((int)x,(int)y,(int)z,c); } }; //! Generate a 3d box object. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the box (dimension along the X-axis). \param size_y The height of the box (dimension along the Y-axis). \param size_z The depth of the box (dimension along the Z-axis). \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::box3d(faces3d,10,20,30); CImg<unsigned char>().display_object3d("Box3d",points3d,faces3d); \endcode \image html ref_box3d.jpg **/ template<typename tf> static CImg<floatT> box3d(CImgList<tf>& primitives, const float size_x=200, const float size_y=100, const float size_z=100) { primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 0,1,5,4, 3,7,6,2, 0,4,7,3, 1,2,6,5); return CImg<floatT>(8,3,1,1, 0.,size_x,size_x, 0., 0.,size_x,size_x, 0., 0., 0.,size_y,size_y, 0., 0.,size_y,size_y, 0., 0., 0., 0.,size_z,size_z,size_z,size_z); } //! Generate a 3d cone. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cone basis. \param size_z The cone's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cone3d(faces3d,50); CImg<unsigned char>().display_object3d("Cone3d",points3d,faces3d); \endcode \image html ref_cone3d.jpg **/ template<typename tf> static CImg<floatT> cone3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,size_z, 0.,0.,0.); for (float delta = 360.0f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0).move_to(vertices); } const unsigned int nbr = vertices._width - 2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2 + p, next = 2 + ((p+1)%nbr); CImg<tf>::vector(1,next,curr).move_to(primitives); CImg<tf>::vector(0,curr,next).move_to(primitives); } return vertices>'x'; } //! Generate a 3d cylinder. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the cylinder basis. \param size_z The cylinder's height. \param subdivisions The number of basis angular subdivisions. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::cylinder3d(faces3d,50); CImg<unsigned char>().display_object3d("Cylinder3d",points3d,faces3d); \endcode \image html ref_cylinder3d.jpg **/ template<typename tf> static CImg<floatT> cylinder3d(CImgList<tf>& primitives, const float radius=50, const float size_z=100, const unsigned int subdivisions=24) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImgList<floatT> vertices(2,1,3,1,1, 0.,0.,0., 0.,0.,size_z); for (float delta = 360.0f/subdivisions, angle = 0; angle<360; angle+=delta) { const float a = (float)(angle*cimg::PI/180); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),0.0f).move_to(vertices); CImg<floatT>::vector((float)(radius*std::cos(a)),(float)(radius*std::sin(a)),size_z).move_to(vertices); } const unsigned int nbr = (vertices._width - 2)/2; for (unsigned int p = 0; p<nbr; ++p) { const unsigned int curr = 2+2*p, next = 2+(2*((p+1)%nbr)); CImg<tf>::vector(0,next,curr).move_to(primitives); CImg<tf>::vector(1,curr+1,next+1).move_to(primitives); CImg<tf>::vector(curr,next,next+1,curr+1).move_to(primitives); } return vertices>'x'; } //! Generate a 3d torus. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param radius1 The large radius. \param radius2 The small radius. \param subdivisions1 The number of angular subdivisions for the large radius. \param subdivisions2 The number of angular subdivisions for the small radius. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::torus3d(faces3d,20,4); CImg<unsigned char>().display_object3d("Torus3d",points3d,faces3d); \endcode \image html ref_torus3d.jpg **/ template<typename tf> static CImg<floatT> torus3d(CImgList<tf>& primitives, const float radius1=100, const float radius2=30, const unsigned int subdivisions1=24, const unsigned int subdivisions2=12) { primitives.assign(); if (!subdivisions1 || !subdivisions2) return CImg<floatT>(); CImgList<floatT> vertices; for (unsigned int v = 0; v<subdivisions1; ++v) { const float beta = (float)(v*2*cimg::PI/subdivisions1), xc = radius1*(float)std::cos(beta), yc = radius1*(float)std::sin(beta); for (unsigned int u = 0; u<subdivisions2; ++u) { const float alpha = (float)(u*2*cimg::PI/subdivisions2), x = xc + radius2*(float)(std::cos(alpha)*std::cos(beta)), y = yc + radius2*(float)(std::cos(alpha)*std::sin(beta)), z = radius2*(float)std::sin(alpha); CImg<floatT>::vector(x,y,z).move_to(vertices); } } for (unsigned int vv = 0; vv<subdivisions1; ++vv) { const unsigned int nv = (vv+1)%subdivisions1; for (unsigned int uu = 0; uu<subdivisions2; ++uu) { const unsigned int nu = (uu+1)%subdivisions2, svv = subdivisions2*vv, snv = subdivisions2*nv; CImg<tf>::vector(svv+nu,svv+uu,snv+uu,snv+nu).move_to(primitives); } } return vertices>'x'; } //! Generate a 3d XY-plane. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param size_x The width of the plane (dimension along the X-axis). \param size_y The height of the plane (dimensions along the Y-axis). \param subdivisions_x The number of planar subdivisions along the X-axis. \param subdivisions_y The number of planar subdivisions along the Y-axis. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::plane3d(faces3d,100,50); CImg<unsigned char>().display_object3d("Plane3d",points3d,faces3d); \endcode \image html ref_plane3d.jpg **/ template<typename tf> static CImg<floatT> plane3d(CImgList<tf>& primitives, const float size_x=100, const float size_y=100, const unsigned int subdivisions_x=10, const unsigned int subdivisions_y=10) { primitives.assign(); if (!subdivisions_x || !subdivisions_y) return CImg<floatT>(); CImgList<floatT> vertices; const unsigned int w = subdivisions_x + 1, h = subdivisions_y + 1; const float fx = (float)size_x/w, fy = (float)size_y/h; for (unsigned int y = 0; y<h; ++y) for (unsigned int x = 0; x<w; ++x) CImg<floatT>::vector(fx*x,fy*y,0).move_to(vertices); for (unsigned int y = 0; y<subdivisions_y; ++y) for (unsigned int x = 0; x<subdivisions_x; ++x) { const int off1 = x+y*w, off2 = x+1+y*w, off3 = x+1+(y+1)*w, off4 = x+(y+1)*w; CImg<tf>::vector(off1,off4,off3,off2).move_to(primitives); } return vertices>'x'; } //! Generate a 3d sphere. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param radius The radius of the sphere (dimension along the X-axis). \param subdivisions The number of recursive subdivisions from an initial icosahedron. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> points3d = CImg<float>::sphere3d(faces3d,100,4); CImg<unsigned char>().display_object3d("Sphere3d",points3d,faces3d); \endcode \image html ref_sphere3d.jpg **/ template<typename tf> static CImg<floatT> sphere3d(CImgList<tf>& primitives, const float radius=50, const unsigned int subdivisions=3) { // Create initial icosahedron primitives.assign(); const double tmp = (1+std::sqrt(5.0f))/2, a = 1.0/std::sqrt(1+tmp*tmp), b = tmp*a; CImgList<floatT> vertices(12,1,3,1,1, b,a,0.0, -b,a,0.0, -b,-a,0.0, b,-a,0.0, a,0.0,b, a,0.0,-b, -a,0.0,-b, -a,0.0,b, 0.0,b,a, 0.0,-b,a, 0.0,-b,-a, 0.0,b,-a); primitives.assign(20,1,3,1,1, 4,8,7, 4,7,9, 5,6,11, 5,10,6, 0,4,3, 0,3,5, 2,7,1, 2,1,6, 8,0,11, 8,11,1, 9,10,3, 9,2,10, 8,4,0, 11,0,5, 4,9,3, 5,3,10, 7,8,1, 6,1,11, 7,2,9, 6,10,2); // edge - length/2 float he = (float)a; // Recurse subdivisions for (unsigned int i = 0; i<subdivisions; ++i) { const unsigned int L = primitives._width; he/=2; const float he2 = he*he; for (unsigned int l = 0; l<L; ++l) { const unsigned int p0 = (unsigned int)primitives(0,0), p1 = (unsigned int)primitives(0,1), p2 = (unsigned int)primitives(0,2); const float x0 = vertices(p0,0), y0 = vertices(p0,1), z0 = vertices(p0,2), x1 = vertices(p1,0), y1 = vertices(p1,1), z1 = vertices(p1,2), x2 = vertices(p2,0), y2 = vertices(p2,1), z2 = vertices(p2,2), tnx0 = (x0+x1)/2, tny0 = (y0+y1)/2, tnz0 = (z0+z1)/2, nn0 = (float)std::sqrt(tnx0*tnx0+tny0*tny0+tnz0*tnz0), tnx1 = (x0+x2)/2, tny1 = (y0+y2)/2, tnz1 = (z0+z2)/2, nn1 = (float)std::sqrt(tnx1*tnx1+tny1*tny1+tnz1*tnz1), tnx2 = (x1+x2)/2, tny2 = (y1+y2)/2, tnz2 = (z1+z2)/2, nn2 = (float)std::sqrt(tnx2*tnx2+tny2*tny2+tnz2*tnz2), nx0 = tnx0/nn0, ny0 = tny0/nn0, nz0 = tnz0/nn0, nx1 = tnx1/nn1, ny1 = tny1/nn1, nz1 = tnz1/nn1, nx2 = tnx2/nn2, ny2 = tny2/nn2, nz2 = tnz2/nn2; int i0 = -1, i1 = -1, i2 = -1; cimglist_for(vertices,p) { const float x = (float)vertices(p,0), y = (float)vertices(p,1), z = (float)vertices(p,2); if (cimg::sqr(x-nx0) + cimg::sqr(y-ny0) + cimg::sqr(z-nz0)<he2) i0 = p; if (cimg::sqr(x-nx1) + cimg::sqr(y-ny1) + cimg::sqr(z-nz1)<he2) i1 = p; if (cimg::sqr(x-nx2) + cimg::sqr(y-ny2) + cimg::sqr(z-nz2)<he2) i2 = p; } if (i0<0) { CImg<floatT>::vector(nx0,ny0,nz0).move_to(vertices); i0 = vertices._width - 1; } if (i1<0) { CImg<floatT>::vector(nx1,ny1,nz1).move_to(vertices); i1 = vertices._width - 1; } if (i2<0) { CImg<floatT>::vector(nx2,ny2,nz2).move_to(vertices); i2 = vertices._width - 1; } primitives.remove(0); CImg<tf>::vector(p0,i0,i1).move_to(primitives); CImg<tf>::vector((tf)i0,(tf)p1,(tf)i2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i2,(tf)p2).move_to(primitives); CImg<tf>::vector((tf)i1,(tf)i0,(tf)i2).move_to(primitives); } } return (vertices>'x')*=radius; } //! Generate a 3d ellipsoid. /** \param[out] primitives The returned list of the 3d object primitives (template type \e tf should be at least \e unsigned \e int). \param tensor The tensor which gives the shape and size of the ellipsoid. \param subdivisions The number of recursive subdivisions from an initial stretched icosahedron. \return The N vertices (xi,yi,zi) of the 3d object as a Nx3 CImg<float> image (0<=i<=N-1). \par Example \code CImgList<unsigned int> faces3d; const CImg<float> tensor = CImg<float>::diagonal(10,7,3), points3d = CImg<float>::ellipsoid3d(faces3d,tensor,4); CImg<unsigned char>().display_object3d("Ellipsoid3d",points3d,faces3d); \endcode \image html ref_ellipsoid3d.jpg **/ template<typename tf, typename t> static CImg<floatT> ellipsoid3d(CImgList<tf>& primitives, const CImg<t>& tensor, const unsigned int subdivisions=3) { primitives.assign(); if (!subdivisions) return CImg<floatT>(); CImg<floatT> S, V; tensor.symmetric_eigen(S,V); const float orient = (V(0,1)*V(1,2) - V(0,2)*V(1,1))*V(2,0) + (V(0,2)*V(1,0) - V(0,0)*V(1,2))*V(2,1) + (V(0,0)*V(1,1) - V(0,1)*V(1,0))*V(2,2); if (orient<0) { V(2,0) = -V(2,0); V(2,1) = -V(2,1); V(2,2) = -V(2,2); } const float l0 = S[0], l1 = S[1], l2 = S[2]; CImg<floatT> vertices = sphere3d(primitives,1.0,subdivisions); vertices.get_shared_row(0)*=l0; vertices.get_shared_row(1)*=l1; vertices.get_shared_row(2)*=l2; return V*vertices; } //! Convert 3d object into a CImg3d representation. /** \param primitives Primitives data of the 3d object. \param colors Colors data of the 3d object. \param opacities Opacities data of the 3d object. **/ template<typename tp, typename tc, typename to> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities) { return get_object3dtoCImg3d(primitives,colors,opacities).move_to(*this); } //! Convert 3d object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors) { return get_object3dtoCImg3d(primitives,colors).move_to(*this); } //! Convert 3d object into a CImg3d representation \overloading. template<typename tp> CImg<T>& object3dtoCImg3d(const CImgList<tp>& primitives) { return get_object3dtoCImg3d(primitives).move_to(*this); } //! Convert 3d object into a CImg3d representation \overloading. CImg<T>& object3dtoCImg3d() { return get_object3dtoCImg3d().move_to(*this); } //! Convert 3d object into a CImg3d representation \newinstance. template<typename tp, typename tc, typename to> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const to& opacities) const { char error_message[1024] = { 0 }; if (!is_object3d(primitives,colors,opacities,true,error_message)) throw CImgInstanceException(_cimg_instance "object3dtoCImg3d(): Invalid specified 3d object (%u,%u) (%s).", cimg_instance,_width,primitives._width,error_message); CImg<floatT> res(1,_size_object3dtoCImg3d(primitives,colors,opacities)); float *ptrd = res._data; // Put magick number. *(ptrd++) = 'C' + 0.5f; *(ptrd++) = 'I' + 0.5f; *(ptrd++) = 'm' + 0.5f; *(ptrd++) = 'g' + 0.5f; *(ptrd++) = '3' + 0.5f; *(ptrd++) = 'd' + 0.5f; // Put number of vertices and primitives. *(ptrd++) = cimg::uint2float(_width); *(ptrd++) = cimg::uint2float(primitives._width); // Put vertex data. if (is_empty() || !primitives) return res; const T *ptrx = data(0,0), *ptry = data(0,1), *ptrz = data(0,2); cimg_forX(*this,p) { *(ptrd++) = (float)*(ptrx++); *(ptrd++) = (float)*(ptry++); *(ptrd++) = (float)*(ptrz++); } // Put primitive data. cimglist_for(primitives,p) { *(ptrd++) = (float)primitives[p].size(); const tp *ptrp = primitives[p]._data; cimg_foroff(primitives[p],i) *(ptrd++) = cimg::uint2float((unsigned int)*(ptrp++)); } // Put color/texture data. const unsigned int csiz = cimg::min(colors._width,primitives._width); for (int c = 0; c<(int)csiz; ++c) { const CImg<tc>& color = colors[c]; const tc *ptrc = color._data; if (color.size()==3) { *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*(ptrc++); *(ptrd++) = (float)*ptrc; } else { *(ptrd++) = -128.0f; int shared_ind = -1; if (color.is_shared()) for (int i = 0; i<c; ++i) if (ptrc==colors[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)color._width; *(ptrd++) = (float)color._height; *(ptrd++) = (float)color._spectrum; cimg_foroff(color,l) *(ptrd++) = (float)*(ptrc++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } const int csiz2 = primitives._width - colors._width; for (int c = 0; c<csiz2; ++c) { *(ptrd++) = 200.0f; *(ptrd++) = 200.0f; *(ptrd++) = 200.0f; } // Put opacity data. ptrd = _object3dtoCImg3d(opacities,ptrd); const float *ptre = res.end(); while (ptrd<ptre) *(ptrd++) = 1.0f; return res; } template<typename to> float* _object3dtoCImg3d(const CImgList<to>& opacities, float *ptrd) const { cimglist_for(opacities,o) { const CImg<to>& opacity = opacities[o]; const to *ptro = opacity._data; if (opacity.size()==1) *(ptrd++) = (float)*ptro; else { *(ptrd++) = -128.0f; int shared_ind = -1; if (opacity.is_shared()) for (int i = 0; i<o; ++i) if (ptro==opacities[i]._data) { shared_ind = i; break; } if (shared_ind<0) { *(ptrd++) = (float)opacity._width; *(ptrd++) = (float)opacity._height; *(ptrd++) = (float)opacity._spectrum; cimg_foroff(opacity,l) *(ptrd++) = (float)*(ptro++); } else { *(ptrd++) = (float)shared_ind; *(ptrd++) = 0; *(ptrd++) = 0; } } } return ptrd; } template<typename to> float* _object3dtoCImg3d(const CImg<to>& opacities, float *ptrd) const { const to *ptro = opacities._data; cimg_foroff(opacities,o) *(ptrd++) = (float)*(ptro++); return ptrd; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities) const { unsigned int siz = 8 + 3*width(); cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = cimg::min(primitives._width,colors._width)-1; c>=0; --c) { if (colors[c].is_shared()) siz+=4; else { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4+csiz:3; } } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); cimglist_for(opacities,o) { if (opacities[o].is_shared()) siz+=4; else { const unsigned int osiz = opacities[o].size(); siz+=(osiz!=1)?4+osiz:1; } } siz+=primitives._width - opacities._width; return siz; } template<typename tp, typename tc, typename to> unsigned int _size_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities) const { unsigned int siz = 8 + 3*width(); cimglist_for(primitives,p) siz+=primitives[p].size() + 1; for (int c = cimg::min(primitives._width,colors._width)-1; c>=0; --c) { const unsigned int csiz = colors[c].size(); siz+=(csiz!=3)?4+csiz:3; } if (colors._width<primitives._width) siz+=3*(primitives._width - colors._width); siz+=primitives.size(); cimg::unused(opacities); return siz; } //! Convert 3d object into a CImg3d representation \overloading. template<typename tp, typename tc> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives, const CImgList<tc>& colors) const { CImgList<T> opacities; return get_object3dtoCImg3d(primitives,colors,opacities); } //! Convert 3d object into a CImg3d representation \overloading. template<typename tp> CImg<floatT> get_object3dtoCImg3d(const CImgList<tp>& primitives) const { CImgList<T> colors, opacities; return get_object3dtoCImg3d(primitives,colors,opacities); } //! Convert 3d object into a CImg3d representation \overloading. CImg<floatT> get_object3dtoCImg3d() const { CImgList<T> opacities, colors; CImgList<uintT> primitives(width(),1,1,1,1); cimglist_for(primitives,p) primitives(p,0) = p; return get_object3dtoCImg3d(primitives,colors,opacities); } //! Convert CImg3d representation into a 3d object. /** \param[out] primitives Primitives data of the 3d object. \param[out] colors Colors data of the 3d object. \param[out] opacities Opacities data of the 3d object. **/ template<typename tp, typename tc, typename to> CImg<T>& CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities) { return get_CImg3dtoobject3d(primitives,colors,opacities).move_to(*this); } //! Convert CImg3d representation into a 3d object \newinstance. template<typename tp, typename tc, typename to> CImg<T> get_CImg3dtoobject3d(CImgList<tp>& primitives, CImgList<tc>& colors, CImgList<to>& opacities) const { char error_message[1024] = { 0 }; if (!is_CImg3d(true,error_message)) throw CImgInstanceException(_cimg_instance "CImg3dtoobject3d(): image instance is not a CImg3d (%s).", cimg_instance,error_message); const T *ptrs = _data + 6; const unsigned int nb_points = cimg::float2uint((float)*(ptrs++)), nb_primitives = cimg::float2uint((float)*(ptrs++)); const CImg<T> points = CImg<T>(ptrs,3,nb_points,1,1,true).get_transpose(); ptrs+=3*nb_points; primitives.assign(nb_primitives); cimglist_for(primitives,p) { const unsigned int nb_inds = (unsigned int)*(ptrs++); primitives[p].assign(1,nb_inds); tp *ptrp = primitives[p]._data; for (unsigned int i = 0; i<nb_inds; ++i) *(ptrp++) = (tp)cimg::float2uint((float)*(ptrs++)); } colors.assign(nb_primitives); cimglist_for(colors,c) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) colors[c].assign(colors[w],true); else { colors[c].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else { colors[c].assign(ptrs,1,1,1,3,false); ptrs+=3; } } opacities.assign(nb_primitives); cimglist_for(opacities,o) { if (*ptrs==(T)-128) { ++ptrs; const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++); if (!h && !s) opacities[o].assign(opacities[w],true); else { opacities[o].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; } } else opacities[o].assign(1,1,1,1,*(ptrs++)); } return points; } //@} //--------------------------- // //! \name Drawing Functions //@{ //--------------------------- // [internal] The following _draw_scanline() routines are *non user-friendly functions*, used only for internal purpose. // Pre-requisites: x0<x1, y-coordinate is valid, col is valid. template<typename tc> CImg<T>& _draw_scanline(const int x0, const int x1, const int y, const tc *const color, const float opacity=1, const float brightness=1, const bool init=false) { static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); static float nopacity = 0, copacity = 0; static unsigned long whd = 0; static const tc *col = 0; if (init) { nopacity = cimg::abs(opacity); copacity = 1 - cimg::max(opacity,0); whd = (unsigned long)_width*_height*_depth; } else { const int nx0 = x0>0?x0:0, nx1 = x1<width()?x1:width()-1, dx = nx1 - nx0; if (dx>=0) { col = color; const unsigned long off = whd - dx - 1; T *ptrd = data(nx0,y); if (opacity>=1) { // ** Opaque drawing ** if (brightness==1) { // Brightness==1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)*(col++); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)*(col++); std::memset(ptrd,(int)val,dx+1); ptrd+=whd; } } else if (brightness<1) { // Brightness<1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); std::memset(ptrd,(int)val,dx+1); ptrd+=whd; } } else { // Brightness>1 if (sizeof(T)!=1) cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness-1)*maxval); for (int x = dx; x>=0; --x) *(ptrd++) = val; ptrd+=off; } else cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness-1)*maxval); std::memset(ptrd,(int)val,dx+1); ptrd+=whd; } } } else { // ** Transparent drawing ** if (brightness==1) { // Brightness==1 cimg_forC(*this,c) { const T val = (T)*(col++); for (int x = dx; x>=0; --x) { *ptrd = (T)(val*nopacity + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else if (brightness<=1) { // Brightness<1 cimg_forC(*this,c) { const T val = (T)(*(col++)*brightness); for (int x = dx; x>=0; --x) { *ptrd = (T)(val*nopacity + *ptrd*copacity); ++ptrd; } ptrd+=off; } } else { // Brightness>1 cimg_forC(*this,c) { const T val = (T)((2-brightness)**(col++) + (brightness-1)*maxval); for (int x = dx; x>=0; --x) { *ptrd = (T)(val*nopacity + *ptrd*copacity); ++ptrd; } ptrd+=off; } } } } } return *this; } template<typename tc> CImg<T>& _draw_scanline(const tc *const color, const float opacity=1) { return _draw_scanline(0,0,0,color,opacity,0,true); } //! Draw a 3d point. /** \param x0 X-coordinate of the point. \param y0 Y-coordinate of the point. \param z0 Z-coordinate of the point. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - To set pixel values without clipping needs, you should use the faster CImg::operator()() function. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_point(50,50,color); \endcode **/ template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const int z0, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_point(): Specified color is (null).", cimg_instance); if (x0>=0 && y0>=0 && z0>=0 && x0<width() && y0<height() && z0<depth()) { const unsigned long whd = (unsigned long)_width*_height*_depth; const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); T *ptrd = data(x0,y0,z0,0); const tc *col = color; if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(*(col++)*nopacity + *ptrd*copacity); ptrd+=whd; } } return *this; } //! Draw a 2d point \simplification. template<typename tc> CImg<T>& draw_point(const int x0, const int y0, const tc *const color, const float opacity=1) { return draw_point(x0,y0,0,color,opacity); } // Draw a points cloud. /** \param points Image of vertices coordinates. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_point(const CImg<t>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points) return *this; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_point(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),color,opacity); } break; default : { cimg_forX(points,i) draw_point((int)points(i,0),(int)points(i,1),(int)points(i,2),color,opacity); } } return *this; } //! Draw a 2d line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. \note - Line routine uses Bresenham's algorithm. - Set \p init_hatch = false to draw consecutive hatched segments without breaking the line pattern. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,color); \endcode **/ template<typename tc> CImg<T>& draw_line(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_line(): Specified color is (null).", cimg_instance); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); const bool xdir = x0<x1, ydir = y0<y1; int nx0 = x0, nx1 = x1, ny0 = y0, ny1 = y1, &xleft = xdir?nx0:nx1, &yleft = xdir?ny0:ny1, &xright = xdir?nx1:nx0, &yright = xdir?ny1:ny0, &xup = ydir?nx0:nx1, &yup = ydir?ny0:ny1, &xdown = ydir?nx1:nx0, &ydown = ydir?ny1:ny0; if (xright<0 || xleft>=width()) return *this; if (xleft<0) { yleft-=(int)((float)xleft*((float)yright - yleft)/((float)xright - xleft)); xleft = 0; } if (xright>=width()) { yright-=(int)(((float)xright - width())*((float)yright - yleft)/((float)xright - xleft)); xright = width() - 1; } if (ydown<0 || yup>=height()) return *this; if (yup<0) { xup-=(int)((float)yup*((float)xdown - xup)/((float)ydown - yup)); yup = 0; } if (ydown>=height()) { xdown-=(int)(((float)ydown - height())*((float)xdown - xup)/((float)ydown - yup)); ydown = height() - 1; } T *ptrd0 = data(nx0,ny0); int dx = xright - xleft, dy = ydown - yup; const bool steep = dy>dx; if (steep) cimg::swap(nx0,ny0,nx1,ny1,dx,dy); const long offx = (nx0<nx1?1:-1)*(steep?width():1), offy = (ny0<ny1?1:-1)*(steep?1:width()); const unsigned long wh = (unsigned long)_width*_height; if (opacity>=1) { if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { T *ptrd = ptrd0; const tc* col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { T *ptrd = ptrd0; const tc* col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { T *ptrd = ptrd0; const tc* col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity**(col++) + *ptrd*copacity); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { T *ptrd = ptrd0; const tc* col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity**(col++) + *ptrd*copacity); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } return *this; } //! Draw a 2d line, with z-buffering. /** \param zbuffer Zbuffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. **/ template<typename tz,typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_line(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); const bool xdir = x0<x1, ydir = y0<y1; int nx0 = x0, nx1 = x1, ny0 = y0, ny1 = y1, &xleft = xdir?nx0:nx1, &yleft = xdir?ny0:ny1, &xright = xdir?nx1:nx0, &yright = xdir?ny1:ny0, &xup = ydir?nx0:nx1, &yup = ydir?ny0:ny1, &xdown = ydir?nx1:nx0, &ydown = ydir?ny1:ny0; tzfloat Z0 = 1/(tzfloat)z0, Z1 = 1/(tzfloat)z1, nz0 = Z0, nz1 = Z1, dz = Z1 - Z0, &zleft = xdir?nz0:nz1, &zright = xdir?nz1:nz0, &zup = ydir?nz0:nz1, &zdown = ydir?nz1:nz0; if (xright<0 || xleft>=width()) return *this; if (xleft<0) { const float D = (float)xright - xleft; yleft-=(int)((float)xleft*((float)yright - yleft)/D); zleft-=(tzfloat)xleft*(zright - zleft)/D; xleft = 0; } if (xright>=width()) { const float d = (float)xright - width(), D = (float)xright - xleft; yright-=(int)(d*((float)yright - yleft)/D); zright-=(tzfloat)d*(zright - zleft)/D; xright = width() - 1; } if (ydown<0 || yup>=height()) return *this; if (yup<0) { const float D = (float)ydown - yup; xup-=(int)((float)yup*((float)xdown - xup)/D); zup-=(tzfloat)yup*(zdown - zup)/D; yup = 0; } if (ydown>=height()) { const float d = (float)ydown - height(), D = (float)ydown - yup; xdown-=(int)(d*((float)xdown - xup)/D); zdown-=(tzfloat)d*(zdown - zup)/D; ydown = height() - 1; } T *ptrd0 = data(nx0,ny0); tz *ptrz = zbuffer.data(nx0,ny0); int dx = xright - xleft, dy = ydown - yup; const bool steep = dy>dx; if (steep) cimg::swap(nx0,ny0,nx1,ny1,dx,dy); const long offx = (nx0<nx1?1:-1)*(steep?width():1), offy = (ny0<ny1?1:-1)*(steep?1:width()); const unsigned long wh = (unsigned long)_width*_height, ndx = dx>0?dx:1; if (opacity>=1) { if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz && pattern&hatch) { *ptrz = (tz)z; T *ptrd = ptrd0; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; T *ptrd = ptrd0; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=wh; } } ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz && pattern&hatch) { *ptrz = (tz)z; T *ptrd = ptrd0; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity**(col++) + *ptrd*copacity); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; T *ptrd = ptrd0; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity**(col++) + *ptrd*copacity); ptrd+=wh; } } ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } } return *this; } //! Draw a 3d line. /** \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if a reinitialization of the hash state must be done. **/ template<typename tc> CImg<T>& draw_line(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_line(): Specified color is (null).", cimg_instance); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); int nx0 = x0, ny0 = y0, nz0 = z0, nx1 = x1, ny1 = y1, nz1 = z1; if (nx0>nx1) cimg::swap(nx0,nx1,ny0,ny1,nz0,nz1); if (nx1<0 || nx0>=width()) return *this; if (nx0<0) { const float D = 1.0f + nx1 - nx0; ny0-=(int)((float)nx0*(1.0f + ny1 - ny0)/D); nz0-=(int)((float)nx0*(1.0f + nz1 - nz0)/D); nx0 = 0; } if (nx1>=width()) { const float d = (float)nx1 - width(), D = 1.0f + nx1 - nx0; ny1+=(int)(d*(1.0f + ny0 - ny1)/D); nz1+=(int)(d*(1.0f + nz0 - nz1)/D); nx1 = width() - 1; } if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nz0,nz1); if (ny1<0 || ny0>=height()) return *this; if (ny0<0) { const float D = 1.0f + ny1 - ny0; nx0-=(int)((float)ny0*(1.0f + nx1 - nx0)/D); nz0-=(int)((float)ny0*(1.0f + nz1 - nz0)/D); ny0 = 0; } if (ny1>=height()) { const float d = (float)ny1 - height(), D = 1.0f + ny1 - ny0; nx1+=(int)(d*(1.0f + nx0 - nx1)/D); nz1+=(int)(d*(1.0f + nz0 - nz1)/D); ny1 = height() - 1; } if (nz0>nz1) cimg::swap(nx0,nx1,ny0,ny1,nz0,nz1); if (nz1<0 || nz0>=depth()) return *this; if (nz0<0) { const float D = 1.0f + nz1 - nz0; nx0-=(int)((float)nz0*(1.0f + nx1 - nx0)/D); ny0-=(int)((float)nz0*(1.0f + ny1 - ny0)/D); nz0 = 0; } if (nz1>=depth()) { const float d = (float)nz1 - depth(), D = 1.0f + nz1 - nz0; nx1+=(int)(d*(1.0f + nx0 - nx1)/D); ny1+=(int)(d*(1.0f + ny0 - ny1)/D); nz1 = depth() - 1; } const unsigned int dmax = cimg::max(cimg::abs(nx1 - nx0),cimg::abs(ny1 - ny0),nz1 - nz0); const unsigned long whd = (unsigned long)_width*_height*_depth; const float px = (nx1 - nx0)/(float)dmax, py = (ny1 - ny0)/(float)dmax, pz = (nz1 - nz0)/(float)dmax; float x = (float)nx0, y = (float)ny0, z = (float)nz0; if (opacity>=1) for (unsigned int t = 0; t<=dmax; ++t) { if (!(~pattern) || (~pattern && pattern&hatch)) { T* ptrd = data((unsigned int)x,(unsigned int)y,(unsigned int)z); const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } } x+=px; y+=py; z+=pz; if (pattern) { hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); for (unsigned int t = 0; t<=dmax; ++t) { if (!(~pattern) || (~pattern && pattern&hatch)) { T* ptrd = data((unsigned int)x,(unsigned int)y,(unsigned int)z); const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(*(col++)*nopacity + *ptrd*copacity); ptrd+=whd; } } x+=px; y+=py; z+=pz; if (pattern) { hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); } } } return *this; } //! Draw a textured 2d line. /** \param x0 X-coordinate of the starting line point. \param y0 Y-coordinate of the starting line point. \param x1 X-coordinate of the ending line point. \param y1 Y-coordinate of the ending line point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. \note - Line routine uses the well known Bresenham's algorithm. \par Example: \code CImg<unsigned char> img(100,100,1,3,0), texture("texture256x256.ppm"); const unsigned char color[] = { 255,128,64 }; img.draw_line(40,40,80,70,texture,0,0,255,255); \endcode **/ template<typename tc> CImg<T>& draw_line(const int x0, const int y0, const int x1, const int y1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,x1,y1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); const bool xdir = x0<x1, ydir = y0<y1; int dtx = tx1-tx0, dty = ty1-ty0, nx0 = x0, nx1 = x1, ny0 = y0, ny1 = y1, tnx0 = tx0, tnx1 = tx1, tny0 = ty0, tny1 = ty1, &xleft = xdir?nx0:nx1, &yleft = xdir?ny0:ny1, &xright = xdir?nx1:nx0, &yright = xdir?ny1:ny0, &txleft = xdir?tnx0:tnx1, &tyleft = xdir?tny0:tny1, &txright = xdir?tnx1:tnx0, &tyright = xdir?tny1:tny0, &xup = ydir?nx0:nx1, &yup = ydir?ny0:ny1, &xdown = ydir?nx1:nx0, &ydown = ydir?ny1:ny0, &txup = ydir?tnx0:tnx1, &tyup = ydir?tny0:tny1, &txdown = ydir?tnx1:tnx0, &tydown = ydir?tny1:tny0; if (xright<0 || xleft>=width()) return *this; if (xleft<0) { const float D = (float)xright - xleft; yleft-=(int)((float)xleft*((float)yright - yleft)/D); txleft-=(int)((float)xleft*((float)txright - txleft)/D); tyleft-=(int)((float)xleft*((float)tyright - tyleft)/D); xleft = 0; } if (xright>=width()) { const float d = (float)xright - width(), D = (float)xright - xleft; yright-=(int)(d*((float)yright - yleft)/D); txright-=(int)(d*((float)txright - txleft)/D); tyright-=(int)(d*((float)tyright - tyleft)/D); xright = width() - 1; } if (ydown<0 || yup>=height()) return *this; if (yup<0) { const float D = (float)ydown - yup; xup-=(int)((float)yup*((float)xdown - xup)/D); txup-=(int)((float)yup*((float)txdown - txup)/D); tyup-=(int)((float)yup*((float)tydown - tyup)/D); yup = 0; } if (ydown>=height()) { const float d = (float)ydown - height(), D = (float)ydown - yup; xdown-=(int)(d*((float)xdown - xup)/D); txdown-=(int)(d*((float)txdown - txup)/D); tydown-=(int)(d*((float)tydown - tyup)/D); ydown = height() - 1; } T *ptrd0 = data(nx0,ny0); int dx = xright - xleft, dy = ydown - yup; const bool steep = dy>dx; if (steep) cimg::swap(nx0,ny0,nx1,ny1,dx,dy); const long offx = (nx0<nx1?1:-1)*(steep?width():1), offy = (ny0<ny1?1:-1)*(steep?1:width()), ndx = dx>0?dx:1; const unsigned long wh = (unsigned long)_width*_height; if (opacity>=1) { if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { T *ptrd = ptrd0; const int tx = tx0 + x*dtx/ndx, ty = ty0 + x*dty/ndx; cimg_forC(*this,c) { *ptrd = (T)texture(tx,ty,0,c); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { T *ptrd = ptrd0; const int tx = tx0 + x*dtx/ndx, ty = ty0 + x*dty/ndx; cimg_forC(*this,c) { *ptrd = (T)texture(tx,ty,0,c); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { T *ptrd = ptrd0; if (pattern&hatch) { const int tx = tx0 + x*dtx/ndx, ty = ty0 + x*dty/ndx; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture(tx,ty,0,c) + *ptrd*copacity); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { T *ptrd = ptrd0; const int tx = tx0 + x*dtx/ndx, ty = ty0 + x*dty/ndx; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture(tx,ty,0,c) + *ptrd*copacity); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } return *this; } //! Draw a textured 2d line, with perspective correction. /** \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tc> CImg<T>& draw_line(const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() && z0<=0 && z1<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); const bool xdir = x0<x1, ydir = y0<y1; int nx0 = x0, nx1 = x1, ny0 = y0, ny1 = y1, &xleft = xdir?nx0:nx1, &yleft = xdir?ny0:ny1, &xright = xdir?nx1:nx0, &yright = xdir?ny1:ny0, &xup = ydir?nx0:nx1, &yup = ydir?ny0:ny1, &xdown = ydir?nx1:nx0, &ydown = ydir?ny1:ny0; float Tx0 = tx0/z0, Tx1 = tx1/z1, Ty0 = ty0/z0, Ty1 = ty1/z1, Z0 = 1/z0, Z1 = 1/z1, dz = Z1 - Z0, dtx = Tx1 - Tx0, dty = Ty1 - Ty0, tnx0 = Tx0, tnx1 = Tx1, tny0 = Ty0, tny1 = Ty1, nz0 = Z0, nz1 = Z1, &zleft = xdir?nz0:nz1, &txleft = xdir?tnx0:tnx1, &tyleft = xdir?tny0:tny1, &zright = xdir?nz1:nz0, &txright = xdir?tnx1:tnx0, &tyright = xdir?tny1:tny0, &zup = ydir?nz0:nz1, &txup = ydir?tnx0:tnx1, &tyup = ydir?tny0:tny1, &zdown = ydir?nz1:nz0, &txdown = ydir?tnx1:tnx0, &tydown = ydir?tny1:tny0; if (xright<0 || xleft>=width()) return *this; if (xleft<0) { const float D = (float)xright - xleft; yleft-=(int)((float)xleft*((float)yright - yleft)/D); zleft-=(float)xleft*(zright - zleft)/D; txleft-=(float)xleft*(txright - txleft)/D; tyleft-=(float)xleft*(tyright - tyleft)/D; xleft = 0; } if (xright>=width()) { const float d = (float)xright - width(), D = (float)xright - xleft; yright-=(int)(d*((float)yright - yleft)/D); zright-=d*(zright - zleft)/D; txright-=d*(txright - txleft)/D; tyright-=d*(tyright - tyleft)/D; xright = width() - 1; } if (ydown<0 || yup>=height()) return *this; if (yup<0) { const float D = (float)ydown - yup; xup-=(int)((float)yup*((float)xdown - xup)/D); zup-=(float)yup*(zdown - zup)/D; txup-=(float)yup*(txdown - txup)/D; tyup-=(float)yup*(tydown - tyup)/D; yup = 0; } if (ydown>=height()) { const float d = (float)ydown - height(), D = (float)ydown - yup; xdown-=(int)(d*((float)xdown - xup)/D); zdown-=d*(zdown - zup)/D; txdown-=d*(txdown - txup)/D; tydown-=d*(tydown - tyup)/D; ydown = height() - 1; } T *ptrd0 = data(nx0,ny0); int dx = xright - xleft, dy = ydown - yup; const bool steep = dy>dx; if (steep) cimg::swap(nx0,ny0,nx1,ny1,dx,dy); const long offx = (nx0<nx1?1:-1)*(steep?width():1), offy = (ny0<ny1?1:-1)*(steep?1:width()), ndx = dx>0?dx:1; const unsigned long wh = (unsigned long)_width*_height; if (opacity>=1) { if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { const float z = Z0 + x*dz/ndx, tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)texture((int)(tx/z),(int)(ty/z),0,c); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const float z = Z0 + x*dz/ndx, tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)texture((int)(tx/z),(int)(ty/z),0,c); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { const float z = Z0 + x*dz/ndx, tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture((int)(tx/z),(int)(ty/z),0,c) + *ptrd*copacity); ptrd+=wh; } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const float z = Z0 + x*dz/ndx, tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture((int)(tx/z),(int)(ty/z),0,c) + *ptrd*copacity); ptrd+=wh; } ptrd0+=offx; if ((error-=dy)<0) { ptrd0+=offy; error+=dx; } } } return *this; } //! Draw a textured 2d line, with perspective correction and z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the starting point. \param y0 Y-coordinate of the starting point. \param z0 Z-coordinate of the starting point \param x1 X-coordinate of the ending point. \param y1 Y-coordinate of the ending point. \param z1 Z-coordinate of the ending point. \param texture Texture image defining the pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch Tells if the hash variable must be reinitialized. **/ template<typename tz, typename tc> CImg<T>& draw_line(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_line(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_line(zbuffer,x0,y0,z0,x1,y1,z1,+texture,tx0,ty0,tx1,ty1,opacity,pattern,init_hatch); static unsigned int hatch = ~0U - (~0U>>1); if (init_hatch) hatch = ~0U - (~0U>>1); const bool xdir = x0<x1, ydir = y0<y1; int nx0 = x0, nx1 = x1, ny0 = y0, ny1 = y1, &xleft = xdir?nx0:nx1, &yleft = xdir?ny0:ny1, &xright = xdir?nx1:nx0, &yright = xdir?ny1:ny0, &xup = ydir?nx0:nx1, &yup = ydir?ny0:ny1, &xdown = ydir?nx1:nx0, &ydown = ydir?ny1:ny0; float Tx0 = tx0/z0, Tx1 = tx1/z1, Ty0 = ty0/z0, Ty1 = ty1/z1, dtx = Tx1 - Tx0, dty = Ty1 - Ty0, tnx0 = Tx0, tnx1 = Tx1, tny0 = Ty0, tny1 = Ty1, &txleft = xdir?tnx0:tnx1, &tyleft = xdir?tny0:tny1, &txright = xdir?tnx1:tnx0, &tyright = xdir?tny1:tny0, &txup = ydir?tnx0:tnx1, &tyup = ydir?tny0:tny1, &txdown = ydir?tnx1:tnx0, &tydown = ydir?tny1:tny0; tzfloat Z0 = 1/(tzfloat)z0, Z1 = 1/(tzfloat)z1, dz = Z1 - Z0, nz0 = Z0, nz1 = Z1, &zleft = xdir?nz0:nz1, &zright = xdir?nz1:nz0, &zup = ydir?nz0:nz1, &zdown = ydir?nz1:nz0; if (xright<0 || xleft>=width()) return *this; if (xleft<0) { const float D = (float)xright - xleft; yleft-=(int)((float)xleft*((float)yright - yleft)/D); zleft-=(float)xleft*(zright - zleft)/D; txleft-=(float)xleft*(txright - txleft)/D; tyleft-=(float)xleft*(tyright - tyleft)/D; xleft = 0; } if (xright>=width()) { const float d = (float)xright - width(), D = (float)xright - xleft; yright-=(int)(d*((float)yright - yleft)/D); zright-=d*(zright - zleft)/D; txright-=d*(txright - txleft)/D; tyright-=d*(tyright - tyleft)/D; xright = width()-1; } if (ydown<0 || yup>=height()) return *this; if (yup<0) { const float D = (float)ydown - yup; xup-=(int)((float)yup*((float)xdown - xup)/D); zup-=yup*(zdown - zup)/D; txup-=yup*(txdown - txup)/D; tyup-=yup*(tydown - tyup)/D; yup = 0; } if (ydown>=height()) { const float d = (float)ydown - height(), D = (float)ydown - yup; xdown-=(int)(d*((float)xdown - xup)/D); zdown-=d*(zdown - zup)/D; txdown-=d*(txdown - txup)/D; tydown-=d*(tydown - tyup)/D; ydown = height()-1; } T *ptrd0 = data(nx0,ny0); tz *ptrz = zbuffer.data(nx0,ny0); int dx = xright - xleft, dy = ydown - yup; const bool steep = dy>dx; if (steep) cimg::swap(nx0,ny0,nx1,ny1,dx,dy); const long offx = (nx0<nx1?1:-1)*(steep?width():1), offy = (ny0<ny1?1:-1)*(steep?1:width()), ndx = dx>0?dx:1; const unsigned long wh = (unsigned long)_width*_height; if (opacity>=1) { if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; const float tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)texture((int)(tx/z),(int)(ty/z),0,c); ptrd+=wh; } } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; const float tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)texture((int)(tx/z),(int)(ty/z),0,c); ptrd+=wh; } } ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } } else { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (~pattern) for (int error = dx>>1, x = 0; x<=dx; ++x) { if (pattern&hatch) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; const float tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture((int)(tx/z),(int)(ty/z),0,c) + *ptrd*copacity); ptrd+=wh; } } } hatch>>=1; if (!hatch) hatch = ~0U - (~0U>>1); ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offy; error+=dx; } } else for (int error = dx>>1, x = 0; x<=dx; ++x) { const tzfloat z = Z0 + x*dz/ndx; if (z>=(tzfloat)*ptrz) { *ptrz = (tz)z; const float tx = Tx0 + x*dtx/ndx, ty = Ty0 + x*dty/ndx; T *ptrd = ptrd0; cimg_forC(*this,c) { *ptrd = (T)(nopacity*texture((int)(tx/z),(int)(ty/z),0,c) + *ptrd*copacity); ptrd+=wh; } } ptrd0+=offx; ptrz+=offx; if ((error-=dy)<0) { ptrd0+=offy; ptrz+=offx; error+=dx; } } } return *this; } //! Draw a set of consecutive lines. /** \param points Coordinates of vertices, stored as a list of vectors. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If set to true, init hatch motif. \note - This function uses several call to the single CImg::draw_line() procedure, depending on the vectors size in \p points. \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,128,64 }; CImgList<int> points; points.insert(CImg<int>::vector(0,0)). .insert(CImg<int>::vector(70,10)). .insert(CImg<int>::vector(80,60)). .insert(CImg<int>::vector(10,90)); img.draw_line(points,color); \endcode **/ template<typename t, typename tc> CImg<T>& draw_line(const CImg<t>& points, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_line(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); draw_line(ox,oy,x,y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; } } break; default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1), z0 = (int)points(0,2); int ox = x0, oy = y0, oz = z0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1), z = (int)points(i,2); draw_line(ox,oy,oz,x,y,z,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; oz = z; } } } return *this; } //! Draw a 2d arrow. /** \param x0 X-coordinate of the starting arrow point (tail). \param y0 Y-coordinate of the starting arrow point (tail). \param x1 X-coordinate of the ending arrow point (head). \param y1 Y-coordinate of the ending arrow point (head). \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param angle Aperture angle of the arrow head. \param length Length of the arrow head. If negative, describes a percentage of the arrow length. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. **/ template<typename tc> CImg<T>& draw_arrow(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1, const float angle=30, const float length=-10, const unsigned int pattern=~0U) { if (is_empty()) return *this; const float u = (float)(x0 - x1), v = (float)(y0 - y1), sq = u*u + v*v, deg = (float)(angle*cimg::PI/180), ang = (sq>0)?(float)std::atan2(v,u):0.0f, l = (length>=0)?length:-length*(float)std::sqrt(sq)/100; if (sq>0) { const float cl = (float)std::cos(ang - deg), sl = (float)std::sin(ang - deg), cr = (float)std::cos(ang + deg), sr = (float)std::sin(ang + deg); const int xl = x1 + (int)(l*cl), yl = y1 + (int)(l*sl), xr = x1 + (int)(l*cr), yr = y1 + (int)(l*sr), xc = x1 + (int)((l+1)*(cl+cr))/2, yc = y1 + (int)((l+1)*(sl+sr))/2; draw_line(x0,y0,xc,yc,color,opacity,pattern).draw_triangle(x1,y1,xl,yl,xr,yr,color,opacity); } else draw_point(x0,y0,color,opacity); return *this; } //! Draw a 2d spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. \note - The curve is a 2d cubic Bezier spline, from the set of specified starting/ending points and corresponding velocity vectors. - The spline is drawn as a serie of connected segments. The \p precision parameter sets the average number of pixels in each drawn segment. - A cubic Bezier curve is sometimes defined by a set of 4 points { (\p x0,\p y0), (\p xa,\p ya), (\p xb,\p yb), (\p x1,\p y1) } where (\p x0,\p y0) is the starting point, (\p x1,\p y1) is the ending point and (\p xa,\p ya), (\p xb,\p yb) are two \e control points. The starting and ending velocities (\p u0,\p v0) and (\p u1,\p v1) can be deduced easily from the control points as \p u0 = (\p xa - \p x0), \p v0 = (\p ya - \p y0), \p u1 = (\p x1 - \p xb) and \p v1 = (\p y1 - \p yb). \par Example: \code CImg<unsigned char> img(100,100,1,3,0); const unsigned char color[] = { 255,255,255 }; img.draw_spline(30,30,0,100,90,40,0,-100,color); \endcode **/ template<typename tc> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const tc *const color, const float opacity=1, const float precision=0.25, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_spline(): Specified color is (null).", cimg_instance); if (x0==x1 && y0==y1) return draw_point(x0,y0,color,opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(std::sqrt(cimg::sqr((float)x0-x1)+cimg::sqr((float)y0-y1))*(precision>0?precision:1)); int ox = x0, oy = y0; for (float t = 0; t<1; t+=_precision) { const float t2 = t*t, t3 = t2*t; const int nx = (int)(ax*t3 + bx*t2 + u0*t + x0), ny = (int)(ay*t3 + by*t2 + v0*t + y0); draw_line(ox,oy,nx,ny,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; } return draw_line(ox,oy,x1,y1,color,opacity,pattern,false); } //! Draw a 3d spline \overloading. /** \note - Similar to CImg::draw_spline() for a 3d spline in a volumetric image. **/ template<typename tc> CImg<T>& draw_spline(const int x0, const int y0, const int z0, const float u0, const float v0, const float w0, const int x1, const int y1, const int z1, const float u1, const float v1, const float w1, const tc *const color, const float opacity=1, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_spline(): Specified color is (null).", cimg_instance); if (x0==x1 && y0==y1 && z0==z1) return draw_point(x0,y0,z0,color,opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, az = w0 + w1 + 2*(z0 - z1), bz = 3*(z1 - z0) - 2*w0 - w1, _precision = 1/(std::sqrt(cimg::sqr(x0-x1)+cimg::sqr(y0-y1))*(precision>0?precision:1)); int ox = x0, oy = y0, oz = z0; for (float t = 0; t<1; t+=_precision) { const float t2 = t*t, t3 = t2*t; const int nx = (int)(ax*t3 + bx*t2 + u0*t + x0), ny = (int)(ay*t3 + by*t2 + v0*t + y0), nz = (int)(az*t3 + bz*t2 + w0*t + z0); draw_line(ox,oy,oz,nx,ny,nz,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; oz = nz; } return draw_line(ox,oy,oz,x1,y1,z1,color,opacity,pattern,false); } //! Draw a textured 2d spline. /** \param x0 X-coordinate of the starting curve point \param y0 Y-coordinate of the starting curve point \param u0 X-coordinate of the starting velocity \param v0 Y-coordinate of the starting velocity \param x1 X-coordinate of the ending curve point \param y1 Y-coordinate of the ending curve point \param u1 X-coordinate of the ending velocity \param v1 Y-coordinate of the ending velocity \param texture Texture image defining line pixel colors. \param tx0 X-coordinate of the starting texture point. \param ty0 Y-coordinate of the starting texture point. \param tx1 X-coordinate of the ending texture point. \param ty1 Y-coordinate of the ending texture point. \param precision Curve drawing precision. \param opacity Drawing opacity. \param pattern An integer whose bits describe the line pattern. \param init_hatch if \c true, reinit hatch motif. **/ template<typename t> CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0, const int x1, const int y1, const float u1, const float v1, const CImg<t>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const float opacity=1, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_empty()) return *this; if (is_overlapped(texture)) return draw_spline(x0,y0,u0,v0,x1,y1,u1,v1,+texture,tx0,ty0,tx1,ty1,precision,opacity,pattern,init_hatch); if (x0==x1 && y0==y1) return draw_point(x0,y0,texture.get_vector_at(x0,y0),opacity); bool ninit_hatch = init_hatch; const float ax = u0 + u1 + 2*(x0 - x1), bx = 3*(x1 - x0) - 2*u0 - u1, ay = v0 + v1 + 2*(y0 - y1), by = 3*(y1 - y0) - 2*v0 - v1, _precision = 1/(std::sqrt(cimg::sqr(x0-x1)+cimg::sqr(y0-y1))*(precision>0?precision:1)); int ox = x0, oy = y0, otx = tx0, oty = ty0; for (float t1 = 0; t1<1; t1+=_precision) { const float t2 = t1*t1, t3 = t2*t1; const int nx = (int)(ax*t3 + bx*t2 + u0*t1 + x0), ny = (int)(ay*t3 + by*t2 + v0*t1 + y0), ntx = tx0 + (int)((tx1-tx0)*t1), nty = ty0 + (int)((ty1-ty0)*t1); draw_line(ox,oy,nx,ny,texture,otx,oty,ntx,nty,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = nx; oy = ny; otx = ntx; oty = nty; } return draw_line(ox,oy,x1,y1,texture,otx,oty,tx1,ty1,opacity,pattern,false); } //! Draw a set of consecutive splines. /** \param points Vertices data. \param tangents Tangents data. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param is_closed_set Tells if the drawn spline set is closed. \param precision Precision of the drawing. \param pattern An integer whose bits describe the line pattern. \param init_hatch If \c true, init hatch motif. **/ template<typename tp, typename tt, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const CImg<tt>& tangents, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || !tangents || points._width<2 || tangents._width<2) return *this; bool ninit_hatch = init_hatch; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { const int x0 = (int)points(0,0), y0 = (int)points(0,1); const float u0 = (float)tangents(0,0), v0 = (float)tangents(0,1); int ox = x0, oy = y0; float ou = u0, ov = v0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1); const float u = (float)tangents(i,0), v = (float)tangents(i,1); draw_spline(ox,oy,ou,ov,x,y,u,v,color,precision,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; ou = u; ov = v; } if (is_closed_set) draw_spline(ox,oy,ou,ov,x0,y0,u0,v0,color,precision,opacity,pattern,false); } break; default : { const int x0 = (int)points(0,0), y0 = (int)points(0,1), z0 = (int)points(0,2); const float u0 = (float)tangents(0,0), v0 = (float)tangents(0,1), w0 = (float)tangents(0,2); int ox = x0, oy = y0, oz = z0; float ou = u0, ov = v0, ow = w0; for (unsigned int i = 1; i<points._width; ++i) { const int x = (int)points(i,0), y = (int)points(i,1), z = (int)points(i,2); const float u = (float)tangents(i,0), v = (float)tangents(i,1), w = (float)tangents(i,2); draw_spline(ox,oy,oz,ou,ov,ow,x,y,z,u,v,w,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; oz = z; ou = u; ov = v; ow = w; } if (is_closed_set) draw_spline(ox,oy,oz,ou,ov,ow,x0,y0,z0,u0,v0,w0,color,precision,opacity,pattern,false); } } return *this; } //! Draw a set of consecutive splines \overloading. /** Similar to previous function, with the point tangents automatically estimated from the given points set. **/ template<typename tp, typename tc> CImg<T>& draw_spline(const CImg<tp>& points, const tc *const color, const float opacity=1, const bool is_closed_set=false, const float precision=4, const unsigned int pattern=~0U, const bool init_hatch=true) { if (is_empty() || !points || points._width<2) return *this; CImg<Tfloat> tangents; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).", cimg_instance, points._width,points._height,points._depth,points._spectrum,points._data); case 2 : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p+points._width-1)%points._width:(p?p-1:0), p1 = is_closed_set?(p+1)%points._width:(p+1<points._width?p+1:p); const float x = (float)points(p,0), y = (float)points(p,1), x0 = (float)points(p0,0), y0 = (float)points(p0,1), x1 = (float)points(p1,0), y1 = (float)points(p1,1), u0 = x - x0, v0 = y - y0, n0 = 1e-8f + (float)std::sqrt(u0*u0 + v0*v0), u1 = x1 - x, v1 = y1 - y, n1 = 1e-8f + (float)std::sqrt(u1*u1 + v1*v1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, n = 1e-8f + (float)std::sqrt(u*u + v*v), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); } } break; default : { tangents.assign(points._width,points._height); cimg_forX(points,p) { const unsigned int p0 = is_closed_set?(p+points._width-1)%points._width:(p?p-1:0), p1 = is_closed_set?(p+1)%points._width:(p+1<points._width?p+1:p); const float x = (float)points(p,0), y = (float)points(p,1), z = (float)points(p,2), x0 = (float)points(p0,0), y0 = (float)points(p0,1), z0 = (float)points(p0,2), x1 = (float)points(p1,0), y1 = (float)points(p1,1), z1 = (float)points(p1,2), u0 = x - x0, v0 = y - y0, w0 = z - z0, n0 = 1e-8f + (float)std::sqrt(u0*u0 + v0*v0 + w0*w0), u1 = x1 - x, v1 = y1 - y, w1 = z1 - z, n1 = 1e-8f + (float)std::sqrt(u1*u1 + v1*v1 + w1*w1), u = u0/n0 + u1/n1, v = v0/n0 + v1/n1, w = w0/n0 + w1/n1, n = 1e-8f + (float)std::sqrt(u*u + v*v + w*w), fact = 0.5f*(n0 + n1); tangents(p,0) = (Tfloat)(fact*u/n); tangents(p,1) = (Tfloat)(fact*v/n); tangents(p,2) = (Tfloat)(fact*w/n); } } } return draw_spline(points,tangents,color,opacity,is_closed_set,precision,pattern,init_hatch); } // Inner macro for drawing triangles. #define _cimg_for_triangle1(img,xl,xr,y,x0,y0,x1,y1,x2,y2) \ for (int y = y0<0?0:y0, \ xr = y0>=0?x0:(x0-y0*(x2-x0)/(y2-y0)), \ xl = y1>=0?(y0>=0?(y0==y1?x1:x0):(x0-y0*(x1-x0)/(y1-y0))):(x1-y1*(x2-x1)/(y2-y1)), \ _sxn=1, \ _sxr=1, \ _sxl=1, \ _dxn = x2>x1?x2-x1:(_sxn=-1,x1-x2), \ _dxr = x2>x0?x2-x0:(_sxr=-1,x0-x2), \ _dxl = x1>x0?x1-x0:(_sxl=-1,x0-x1), \ _dyn = y2-y1, \ _dyr = y2-y0, \ _dyl = y1-y0, \ _counter = (_dxn-=_dyn?_dyn*(_dxn/_dyn):0, \ _dxr-=_dyr?_dyr*(_dxr/_dyr):0, \ _dxl-=_dyl?_dyl*(_dxl/_dyl):0, \ cimg::min((int)(img)._height-y-1,y2-y)), \ _errn = _dyn/2, \ _errr = _dyr/2, \ _errl = _dyl/2, \ _rxn = _dyn?(x2-x1)/_dyn:0, \ _rxr = _dyr?(x2-x0)/_dyr:0, \ _rxl = (y0!=y1 && y1>0)?(_dyl?(x1-x0)/_dyl:0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxn); \ _counter>=0; --_counter, ++y, \ xr+=_rxr+((_errr-=_dxr)<0?_errr+=_dyr,_sxr:0), \ xl+=(y!=y1)?_rxl+((_errl-=_dxl)<0?(_errl+=_dyl,_sxl):0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxl=_rxn, x1-xl)) #define _cimg_for_triangle2(img,xl,cl,xr,cr,y,x0,y0,c0,x1,y1,c1,x2,y2,c2) \ for (int y = y0<0?0:y0, \ xr = y0>=0?x0:(x0-y0*(x2-x0)/(y2-y0)), \ cr = y0>=0?c0:(c0-y0*(c2-c0)/(y2-y0)), \ xl = y1>=0?(y0>=0?(y0==y1?x1:x0):(x0-y0*(x1-x0)/(y1-y0))):(x1-y1*(x2-x1)/(y2-y1)), \ cl = y1>=0?(y0>=0?(y0==y1?c1:c0):(c0-y0*(c1-c0)/(y1-y0))):(c1-y1*(c2-c1)/(y2-y1)), \ _sxn=1, _scn=1, \ _sxr=1, _scr=1, \ _sxl=1, _scl=1, \ _dxn = x2>x1?x2-x1:(_sxn=-1,x1-x2), \ _dxr = x2>x0?x2-x0:(_sxr=-1,x0-x2), \ _dxl = x1>x0?x1-x0:(_sxl=-1,x0-x1), \ _dcn = c2>c1?c2-c1:(_scn=-1,c1-c2), \ _dcr = c2>c0?c2-c0:(_scr=-1,c0-c2), \ _dcl = c1>c0?c1-c0:(_scl=-1,c0-c1), \ _dyn = y2-y1, \ _dyr = y2-y0, \ _dyl = y1-y0, \ _counter =(_dxn-=_dyn?_dyn*(_dxn/_dyn):0, \ _dxr-=_dyr?_dyr*(_dxr/_dyr):0, \ _dxl-=_dyl?_dyl*(_dxl/_dyl):0, \ _dcn-=_dyn?_dyn*(_dcn/_dyn):0, \ _dcr-=_dyr?_dyr*(_dcr/_dyr):0, \ _dcl-=_dyl?_dyl*(_dcl/_dyl):0, \ cimg::min((int)(img)._height-y-1,y2-y)), \ _errn = _dyn/2, _errcn = _errn, \ _errr = _dyr/2, _errcr = _errr, \ _errl = _dyl/2, _errcl = _errl, \ _rxn = _dyn?(x2-x1)/_dyn:0, \ _rcn = _dyn?(c2-c1)/_dyn:0, \ _rxr = _dyr?(x2-x0)/_dyr:0, \ _rcr = _dyr?(c2-c0)/_dyr:0, \ _rxl = (y0!=y1 && y1>0)?(_dyl?(x1-x0)/_dyl:0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxn), \ _rcl = (y0!=y1 && y1>0)?(_dyl?(c1-c0)/_dyl:0): \ (_errcl=_errcn, _dcl=_dcn, _dyl=_dyn, _scl=_scn, _rcn ); \ _counter>=0; --_counter, ++y, \ xr+=_rxr+((_errr-=_dxr)<0?_errr+=_dyr,_sxr:0), \ cr+=_rcr+((_errcr-=_dcr)<0?_errcr+=_dyr,_scr:0), \ xl+=(y!=y1)?(cl+=_rcl+((_errcl-=_dcl)<0?(_errcl+=_dyl,_scl):0), \ _rxl+((_errl-=_dxl)<0?(_errl+=_dyl,_sxl):0)): \ (_errcl=_errcn, _dcl=_dcn, _dyl=_dyn, _scl=_scn, _rcl=_rcn, cl=c1, \ _errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxl=_rxn, x1-xl)) #define _cimg_for_triangle3(img,xl,txl,tyl,xr,txr,tyr,y,x0,y0,tx0,ty0,x1,y1,tx1,ty1,x2,y2,tx2,ty2) \ for (int y = y0<0?0:y0, \ xr = y0>=0?x0:(x0-y0*(x2-x0)/(y2-y0)), \ txr = y0>=0?tx0:(tx0-y0*(tx2-tx0)/(y2-y0)), \ tyr = y0>=0?ty0:(ty0-y0*(ty2-ty0)/(y2-y0)), \ xl = y1>=0?(y0>=0?(y0==y1?x1:x0):(x0-y0*(x1-x0)/(y1-y0))):(x1-y1*(x2-x1)/(y2-y1)), \ txl = y1>=0?(y0>=0?(y0==y1?tx1:tx0):(tx0-y0*(tx1-tx0)/(y1-y0))):(tx1-y1*(tx2-tx1)/(y2-y1)), \ tyl = y1>=0?(y0>=0?(y0==y1?ty1:ty0):(ty0-y0*(ty1-ty0)/(y1-y0))):(ty1-y1*(ty2-ty1)/(y2-y1)), \ _sxn=1, _stxn=1, _styn=1, \ _sxr=1, _stxr=1, _styr=1, \ _sxl=1, _stxl=1, _styl=1, \ _dxn = x2>x1?x2-x1:(_sxn=-1,x1-x2), \ _dxr = x2>x0?x2-x0:(_sxr=-1,x0-x2), \ _dxl = x1>x0?x1-x0:(_sxl=-1,x0-x1), \ _dtxn = tx2>tx1?tx2-tx1:(_stxn=-1,tx1-tx2), \ _dtxr = tx2>tx0?tx2-tx0:(_stxr=-1,tx0-tx2), \ _dtxl = tx1>tx0?tx1-tx0:(_stxl=-1,tx0-tx1), \ _dtyn = ty2>ty1?ty2-ty1:(_styn=-1,ty1-ty2), \ _dtyr = ty2>ty0?ty2-ty0:(_styr=-1,ty0-ty2), \ _dtyl = ty1>ty0?ty1-ty0:(_styl=-1,ty0-ty1), \ _dyn = y2-y1, \ _dyr = y2-y0, \ _dyl = y1-y0, \ _counter =(_dxn-=_dyn?_dyn*(_dxn/_dyn):0, \ _dxr-=_dyr?_dyr*(_dxr/_dyr):0, \ _dxl-=_dyl?_dyl*(_dxl/_dyl):0, \ _dtxn-=_dyn?_dyn*(_dtxn/_dyn):0, \ _dtxr-=_dyr?_dyr*(_dtxr/_dyr):0, \ _dtxl-=_dyl?_dyl*(_dtxl/_dyl):0, \ _dtyn-=_dyn?_dyn*(_dtyn/_dyn):0, \ _dtyr-=_dyr?_dyr*(_dtyr/_dyr):0, \ _dtyl-=_dyl?_dyl*(_dtyl/_dyl):0, \ cimg::min((int)(img)._height-y-1,y2-y)), \ _errn = _dyn/2, _errtxn = _errn, _errtyn = _errn, \ _errr = _dyr/2, _errtxr = _errr, _errtyr = _errr, \ _errl = _dyl/2, _errtxl = _errl, _errtyl = _errl, \ _rxn = _dyn?(x2-x1)/_dyn:0, \ _rtxn = _dyn?(tx2-tx1)/_dyn:0, \ _rtyn = _dyn?(ty2-ty1)/_dyn:0, \ _rxr = _dyr?(x2-x0)/_dyr:0, \ _rtxr = _dyr?(tx2-tx0)/_dyr:0, \ _rtyr = _dyr?(ty2-ty0)/_dyr:0, \ _rxl = (y0!=y1 && y1>0)?(_dyl?(x1-x0)/_dyl:0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxn), \ _rtxl = (y0!=y1 && y1>0)?(_dyl?(tx1-tx0)/_dyl:0): \ (_errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxn ), \ _rtyl = (y0!=y1 && y1>0)?(_dyl?(ty1-ty0)/_dyl:0): \ (_errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyn ); \ _counter>=0; --_counter, ++y, \ xr+=_rxr+((_errr-=_dxr)<0?_errr+=_dyr,_sxr:0), \ txr+=_rtxr+((_errtxr-=_dtxr)<0?_errtxr+=_dyr,_stxr:0), \ tyr+=_rtyr+((_errtyr-=_dtyr)<0?_errtyr+=_dyr,_styr:0), \ xl+=(y!=y1)?(txl+=_rtxl+((_errtxl-=_dtxl)<0?(_errtxl+=_dyl,_stxl):0), \ tyl+=_rtyl+((_errtyl-=_dtyl)<0?(_errtyl+=_dyl,_styl):0), \ _rxl+((_errl-=_dxl)<0?(_errl+=_dyl,_sxl):0)): \ (_errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxl=_rtxn, txl=tx1, \ _errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyl=_rtyn, tyl=ty1,\ _errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxl=_rxn, x1-xl)) #define _cimg_for_triangle4(img,xl,cl,txl,tyl,xr,cr,txr,tyr,y,x0,y0,c0,tx0,ty0,x1,y1,c1,tx1,ty1,x2,y2,c2,tx2,ty2) \ for (int y = y0<0?0:y0, \ xr = y0>=0?x0:(x0-y0*(x2-x0)/(y2-y0)), \ cr = y0>=0?c0:(c0-y0*(c2-c0)/(y2-y0)), \ txr = y0>=0?tx0:(tx0-y0*(tx2-tx0)/(y2-y0)), \ tyr = y0>=0?ty0:(ty0-y0*(ty2-ty0)/(y2-y0)), \ xl = y1>=0?(y0>=0?(y0==y1?x1:x0):(x0-y0*(x1-x0)/(y1-y0))):(x1-y1*(x2-x1)/(y2-y1)), \ cl = y1>=0?(y0>=0?(y0==y1?c1:c0):(c0-y0*(c1-c0)/(y1-y0))):(c1-y1*(c2-c1)/(y2-y1)), \ txl = y1>=0?(y0>=0?(y0==y1?tx1:tx0):(tx0-y0*(tx1-tx0)/(y1-y0))):(tx1-y1*(tx2-tx1)/(y2-y1)), \ tyl = y1>=0?(y0>=0?(y0==y1?ty1:ty0):(ty0-y0*(ty1-ty0)/(y1-y0))):(ty1-y1*(ty2-ty1)/(y2-y1)), \ _sxn=1, _scn=1, _stxn=1, _styn=1, \ _sxr=1, _scr=1, _stxr=1, _styr=1, \ _sxl=1, _scl=1, _stxl=1, _styl=1, \ _dxn = x2>x1?x2-x1:(_sxn=-1,x1-x2), \ _dxr = x2>x0?x2-x0:(_sxr=-1,x0-x2), \ _dxl = x1>x0?x1-x0:(_sxl=-1,x0-x1), \ _dcn = c2>c1?c2-c1:(_scn=-1,c1-c2), \ _dcr = c2>c0?c2-c0:(_scr=-1,c0-c2), \ _dcl = c1>c0?c1-c0:(_scl=-1,c0-c1), \ _dtxn = tx2>tx1?tx2-tx1:(_stxn=-1,tx1-tx2), \ _dtxr = tx2>tx0?tx2-tx0:(_stxr=-1,tx0-tx2), \ _dtxl = tx1>tx0?tx1-tx0:(_stxl=-1,tx0-tx1), \ _dtyn = ty2>ty1?ty2-ty1:(_styn=-1,ty1-ty2), \ _dtyr = ty2>ty0?ty2-ty0:(_styr=-1,ty0-ty2), \ _dtyl = ty1>ty0?ty1-ty0:(_styl=-1,ty0-ty1), \ _dyn = y2-y1, \ _dyr = y2-y0, \ _dyl = y1-y0, \ _counter =(_dxn-=_dyn?_dyn*(_dxn/_dyn):0, \ _dxr-=_dyr?_dyr*(_dxr/_dyr):0, \ _dxl-=_dyl?_dyl*(_dxl/_dyl):0, \ _dcn-=_dyn?_dyn*(_dcn/_dyn):0, \ _dcr-=_dyr?_dyr*(_dcr/_dyr):0, \ _dcl-=_dyl?_dyl*(_dcl/_dyl):0, \ _dtxn-=_dyn?_dyn*(_dtxn/_dyn):0, \ _dtxr-=_dyr?_dyr*(_dtxr/_dyr):0, \ _dtxl-=_dyl?_dyl*(_dtxl/_dyl):0, \ _dtyn-=_dyn?_dyn*(_dtyn/_dyn):0, \ _dtyr-=_dyr?_dyr*(_dtyr/_dyr):0, \ _dtyl-=_dyl?_dyl*(_dtyl/_dyl):0, \ cimg::min((int)(img)._height-y-1,y2-y)), \ _errn = _dyn/2, _errcn = _errn, _errtxn = _errn, _errtyn = _errn, \ _errr = _dyr/2, _errcr = _errr, _errtxr = _errr, _errtyr = _errr, \ _errl = _dyl/2, _errcl = _errl, _errtxl = _errl, _errtyl = _errl, \ _rxn = _dyn?(x2-x1)/_dyn:0, \ _rcn = _dyn?(c2-c1)/_dyn:0, \ _rtxn = _dyn?(tx2-tx1)/_dyn:0, \ _rtyn = _dyn?(ty2-ty1)/_dyn:0, \ _rxr = _dyr?(x2-x0)/_dyr:0, \ _rcr = _dyr?(c2-c0)/_dyr:0, \ _rtxr = _dyr?(tx2-tx0)/_dyr:0, \ _rtyr = _dyr?(ty2-ty0)/_dyr:0, \ _rxl = (y0!=y1 && y1>0)?(_dyl?(x1-x0)/_dyl:0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxn), \ _rcl = (y0!=y1 && y1>0)?(_dyl?(c1-c0)/_dyl:0): \ (_errcl=_errcn, _dcl=_dcn, _dyl=_dyn, _scl=_scn, _rcn ), \ _rtxl = (y0!=y1 && y1>0)?(_dyl?(tx1-tx0)/_dyl:0): \ (_errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxn ), \ _rtyl = (y0!=y1 && y1>0)?(_dyl?(ty1-ty0)/_dyl:0): \ (_errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyn ); \ _counter>=0; --_counter, ++y, \ xr+=_rxr+((_errr-=_dxr)<0?_errr+=_dyr,_sxr:0), \ cr+=_rcr+((_errcr-=_dcr)<0?_errcr+=_dyr,_scr:0), \ txr+=_rtxr+((_errtxr-=_dtxr)<0?_errtxr+=_dyr,_stxr:0), \ tyr+=_rtyr+((_errtyr-=_dtyr)<0?_errtyr+=_dyr,_styr:0), \ xl+=(y!=y1)?(cl+=_rcl+((_errcl-=_dcl)<0?(_errcl+=_dyl,_scl):0), \ txl+=_rtxl+((_errtxl-=_dtxl)<0?(_errtxl+=_dyl,_stxl):0), \ tyl+=_rtyl+((_errtyl-=_dtyl)<0?(_errtyl+=_dyl,_styl):0), \ _rxl+((_errl-=_dxl)<0?(_errl+=_dyl,_sxl):0)): \ (_errcl=_errcn, _dcl=_dcn, _dyl=_dyn, _scl=_scn, _rcl=_rcn, cl=c1, \ _errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxl=_rtxn, txl=tx1, \ _errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyl=_rtyn, tyl=ty1, \ _errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxl=_rxn, x1-xl)) #define _cimg_for_triangle5(img,xl,txl,tyl,lxl,lyl,xr,txr,tyr,lxr,lyr,y,x0,y0,tx0,ty0,lx0,ly0,x1,y1,tx1,ty1,lx1,ly1,x2,y2,tx2,ty2,lx2,ly2) \ for (int y = y0<0?0:y0, \ xr = y0>=0?x0:(x0-y0*(x2-x0)/(y2-y0)), \ txr = y0>=0?tx0:(tx0-y0*(tx2-tx0)/(y2-y0)), \ tyr = y0>=0?ty0:(ty0-y0*(ty2-ty0)/(y2-y0)), \ lxr = y0>=0?lx0:(lx0-y0*(lx2-lx0)/(y2-y0)), \ lyr = y0>=0?ly0:(ly0-y0*(ly2-ly0)/(y2-y0)), \ xl = y1>=0?(y0>=0?(y0==y1?x1:x0):(x0-y0*(x1-x0)/(y1-y0))):(x1-y1*(x2-x1)/(y2-y1)), \ txl = y1>=0?(y0>=0?(y0==y1?tx1:tx0):(tx0-y0*(tx1-tx0)/(y1-y0))):(tx1-y1*(tx2-tx1)/(y2-y1)), \ tyl = y1>=0?(y0>=0?(y0==y1?ty1:ty0):(ty0-y0*(ty1-ty0)/(y1-y0))):(ty1-y1*(ty2-ty1)/(y2-y1)), \ lxl = y1>=0?(y0>=0?(y0==y1?lx1:lx0):(lx0-y0*(lx1-lx0)/(y1-y0))):(lx1-y1*(lx2-lx1)/(y2-y1)), \ lyl = y1>=0?(y0>=0?(y0==y1?ly1:ly0):(ly0-y0*(ly1-ly0)/(y1-y0))):(ly1-y1*(ly2-ly1)/(y2-y1)), \ _sxn=1, _stxn=1, _styn=1, _slxn=1, _slyn=1, \ _sxr=1, _stxr=1, _styr=1, _slxr=1, _slyr=1, \ _sxl=1, _stxl=1, _styl=1, _slxl=1, _slyl=1, \ _dxn = x2>x1?x2-x1:(_sxn=-1,x1-x2), _dyn = y2-y1, \ _dxr = x2>x0?x2-x0:(_sxr=-1,x0-x2), _dyr = y2-y0, \ _dxl = x1>x0?x1-x0:(_sxl=-1,x0-x1), _dyl = y1-y0, \ _dtxn = tx2>tx1?tx2-tx1:(_stxn=-1,tx1-tx2), \ _dtxr = tx2>tx0?tx2-tx0:(_stxr=-1,tx0-tx2), \ _dtxl = tx1>tx0?tx1-tx0:(_stxl=-1,tx0-tx1), \ _dtyn = ty2>ty1?ty2-ty1:(_styn=-1,ty1-ty2), \ _dtyr = ty2>ty0?ty2-ty0:(_styr=-1,ty0-ty2), \ _dtyl = ty1>ty0?ty1-ty0:(_styl=-1,ty0-ty1), \ _dlxn = lx2>lx1?lx2-lx1:(_slxn=-1,lx1-lx2), \ _dlxr = lx2>lx0?lx2-lx0:(_slxr=-1,lx0-lx2), \ _dlxl = lx1>lx0?lx1-lx0:(_slxl=-1,lx0-lx1), \ _dlyn = ly2>ly1?ly2-ly1:(_slyn=-1,ly1-ly2), \ _dlyr = ly2>ly0?ly2-ly0:(_slyr=-1,ly0-ly2), \ _dlyl = ly1>ly0?ly1-ly0:(_slyl=-1,ly0-ly1), \ _counter =(_dxn-=_dyn?_dyn*(_dxn/_dyn):0, \ _dxr-=_dyr?_dyr*(_dxr/_dyr):0, \ _dxl-=_dyl?_dyl*(_dxl/_dyl):0, \ _dtxn-=_dyn?_dyn*(_dtxn/_dyn):0, \ _dtxr-=_dyr?_dyr*(_dtxr/_dyr):0, \ _dtxl-=_dyl?_dyl*(_dtxl/_dyl):0, \ _dtyn-=_dyn?_dyn*(_dtyn/_dyn):0, \ _dtyr-=_dyr?_dyr*(_dtyr/_dyr):0, \ _dtyl-=_dyl?_dyl*(_dtyl/_dyl):0, \ _dlxn-=_dyn?_dyn*(_dlxn/_dyn):0, \ _dlxr-=_dyr?_dyr*(_dlxr/_dyr):0, \ _dlxl-=_dyl?_dyl*(_dlxl/_dyl):0, \ _dlyn-=_dyn?_dyn*(_dlyn/_dyn):0, \ _dlyr-=_dyr?_dyr*(_dlyr/_dyr):0, \ _dlyl-=_dyl?_dyl*(_dlyl/_dyl):0, \ cimg::min((int)(img)._height-y-1,y2-y)), \ _errn = _dyn/2, _errtxn = _errn, _errtyn = _errn, _errlxn = _errn, _errlyn = _errn, \ _errr = _dyr/2, _errtxr = _errr, _errtyr = _errr, _errlxr = _errr, _errlyr = _errr, \ _errl = _dyl/2, _errtxl = _errl, _errtyl = _errl, _errlxl = _errl, _errlyl = _errl, \ _rxn = _dyn?(x2-x1)/_dyn:0, \ _rtxn = _dyn?(tx2-tx1)/_dyn:0, \ _rtyn = _dyn?(ty2-ty1)/_dyn:0, \ _rlxn = _dyn?(lx2-lx1)/_dyn:0, \ _rlyn = _dyn?(ly2-ly1)/_dyn:0, \ _rxr = _dyr?(x2-x0)/_dyr:0, \ _rtxr = _dyr?(tx2-tx0)/_dyr:0, \ _rtyr = _dyr?(ty2-ty0)/_dyr:0, \ _rlxr = _dyr?(lx2-lx0)/_dyr:0, \ _rlyr = _dyr?(ly2-ly0)/_dyr:0, \ _rxl = (y0!=y1 && y1>0)?(_dyl?(x1-x0)/_dyl:0): \ (_errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxn), \ _rtxl = (y0!=y1 && y1>0)?(_dyl?(tx1-tx0)/_dyl:0): \ (_errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxn ), \ _rtyl = (y0!=y1 && y1>0)?(_dyl?(ty1-ty0)/_dyl:0): \ (_errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyn ), \ _rlxl = (y0!=y1 && y1>0)?(_dyl?(lx1-lx0)/_dyl:0): \ (_errlxl=_errlxn, _dlxl=_dlxn, _dyl=_dyn, _slxl=_slxn, _rlxn ), \ _rlyl = (y0!=y1 && y1>0)?(_dyl?(ly1-ly0)/_dyl:0): \ (_errlyl=_errlyn, _dlyl=_dlyn, _dyl=_dyn, _slyl=_slyn, _rlyn ); \ _counter>=0; --_counter, ++y, \ xr+=_rxr+((_errr-=_dxr)<0?_errr+=_dyr,_sxr:0), \ txr+=_rtxr+((_errtxr-=_dtxr)<0?_errtxr+=_dyr,_stxr:0), \ tyr+=_rtyr+((_errtyr-=_dtyr)<0?_errtyr+=_dyr,_styr:0), \ lxr+=_rlxr+((_errlxr-=_dlxr)<0?_errlxr+=_dyr,_slxr:0), \ lyr+=_rlyr+((_errlyr-=_dlyr)<0?_errlyr+=_dyr,_slyr:0), \ xl+=(y!=y1)?(txl+=_rtxl+((_errtxl-=_dtxl)<0?(_errtxl+=_dyl,_stxl):0), \ tyl+=_rtyl+((_errtyl-=_dtyl)<0?(_errtyl+=_dyl,_styl):0), \ lxl+=_rlxl+((_errlxl-=_dlxl)<0?(_errlxl+=_dyl,_slxl):0), \ lyl+=_rlyl+((_errlyl-=_dlyl)<0?(_errlyl+=_dyl,_slyl):0), \ _rxl+((_errl-=_dxl)<0?(_errl+=_dyl,_sxl):0)): \ (_errtxl=_errtxn, _dtxl=_dtxn, _dyl=_dyn, _stxl=_stxn, _rtxl=_rtxn, txl=tx1, \ _errtyl=_errtyn, _dtyl=_dtyn, _dyl=_dyn, _styl=_styn, _rtyl=_rtyn, tyl=ty1, \ _errlxl=_errlxn, _dlxl=_dlxn, _dyl=_dyn, _slxl=_slxn, _rlxl=_rlxn, lxl=lx1, \ _errlyl=_errlyn, _dlyl=_dlyn, _dyl=_dyn, _slyl=_slyn, _rlyl=_rlyn, lyl=ly1, \ _errl=_errn, _dxl=_dxn, _dyl=_dyn, _sxl=_sxn, _rxl=_rxn, x1-xl)) // [internal] Draw a filled triangle. template<typename tc> CImg<T>& _draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity, const float brightness) { _draw_scanline(color,opacity); const float nbrightness = brightness<0?0:(brightness>2?2:brightness); int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2); if (ny0<height() && ny2>=0) { if ((nx1 - nx0)*(ny2 - ny0) - (nx2 - nx0)*(ny1 - ny0)<0) _cimg_for_triangle1(*this,xl,xr,y,nx0,ny0,nx1,ny1,nx2,ny2) _draw_scanline(xl,xr,y,color,opacity,nbrightness); else _cimg_for_triangle1(*this,xl,xr,y,nx0,ny0,nx1,ny1,nx2,ny2) _draw_scanline(xr,xl,y,color,opacity,nbrightness); } return *this; } //! Draw a filled 2d triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); _draw_triangle(x0,y0,x1,y1,x2,y2,color,opacity,1); return *this; } //! Draw a outlined 2d triangle. /** \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); draw_line(x0,y0,x1,y1,color,opacity,pattern,true). draw_line(x1,y1,x2,y2,color,opacity,pattern,false). draw_line(x2,y2,x0,y0,color,opacity,pattern,false); return *this; } //! Draw a filled 2d triangle, with z-buffering. /** \param zbuffer Z-buffer image. \param x0 X-coordinate of the first vertex. \param y0 Y-coordinate of the first vertex. \param z0 Z-coordinate of the first vertex. \param x1 X-coordinate of the second vertex. \param y1 Y-coordinate of the second vertex. \param z1 Z-coordinate of the second vertex. \param x2 X-coordinate of the third vertex. \param y2 Y-coordinate of the third vertex. \param z2 Z-coordinate of the third vertex. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. \param brightness Brightness factor. **/ template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const tc *const color, const float opacity=1, const float brightness=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0), nbrightness = brightness<0?0:(brightness>2?2:brightness); const long whd = (long)_width*_height*_depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2; tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle1(*this,xleft0,xright0,y,nx0,ny0,nx1,ny1,nx2,ny2) { if (y==ny1) { zl = nz1; pzl = pzn; } int xleft = xleft0, xright = xright0; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright); const int dx = xright - xleft; const tzfloat pentez = (zright - zleft)/dx; if (xleft<0 && dx) zleft-=xleft*(zright - zleft)/dx; if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width() - 1; T* ptrd = data(xleft,y,0,0); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) { if (nbrightness==1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(nbrightness*(*col++)); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)((2-nbrightness)**(col++) + (nbrightness-1)*maxval); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } } else { if (nbrightness==1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity**(col++) + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(nopacity*nbrightness**(col++) + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { const T val = (T)((2-nbrightness)**(col++) + (nbrightness-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; } } zr+=pzr; zl+=pzl; } return *this; } //! Draw a Gouraud-shaded 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param brightness0 Brightness factor of the first vertex (in [0,2]). \param brightness1 brightness factor of the second vertex (in [0,2]). \param brightness2 brightness factor of the third vertex (in [0,2]). \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const float brightness0, const float brightness1, const float brightness2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nc0 = (int)((brightness0<0.0f?0.0f:(brightness0>2.0f?2.0f:brightness0))*256.0f), nc1 = (int)((brightness1<0.0f?0.0f:(brightness1>2.0f?2.0f:brightness1))*256.0f), nc2 = (int)((brightness2<0.0f?0.0f:(brightness2>2.0f?2.0f:brightness2))*256.0f); if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nc0,nc1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,nc0,nc2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,nc1,nc2); if (ny0>=height() || ny2<0) return *this; _cimg_for_triangle2(*this,xleft0,cleft0,xright0,cright0,y,nx0,ny0,nc0,nx1,ny1,nc1,nx2,ny2,nc2) { int xleft = xleft0, xright = xright0, cleft = cleft0, cright = cright0; if (xright<xleft) cimg::swap(xleft,xright,cleft,cright); const int dx = xright - xleft, dc = cright>cleft?cright - cleft:cleft - cright, rc = dx?(cright - cleft)/dx:0, sc = cright>cleft?1:-1, ndc = dc-(dx?dx*(dc/dx):0); int errc = dx>>1; if (xleft<0 && dx) cleft-=xleft*(cright - cleft)/dx; if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width() - 1; T* ptrd = data(xleft,y); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(cleft<256?cleft**(col++)/256:((512-cleft)**(col++)+(cleft-256)*maxval)/256); ptrd+=whd; } ptrd-=offx; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = color; cimg_forC(*this,c) { const T val = (T)(cleft<256?cleft**(col++)/256:((512-cleft)**(col++)+(cleft-256)*maxval)/256); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } } return *this; } //! Draw a Gouraud-shaded 2d triangle, with z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const tc *const color, const float brightness0, const float brightness1, const float brightness2, const float opacity=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nc0 = (int)((brightness0<0.0f?0.0f:(brightness0>2.0f?2.0f:brightness0))*256.0f), nc1 = (int)((brightness1<0.0f?0.0f:(brightness1>2.0f?2.0f:brightness1))*256.0f), nc2 = (int)((brightness2<0.0f?0.0f:(brightness2>2.0f?2.0f:brightness2))*256.0f); tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nz0,nz1,nc0,nc1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,nz0,nz2,nc0,nc2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,nz1,nz2,nc1,nc2); if (ny0>=height() || ny2<0) return *this; tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle2(*this,xleft0,cleft0,xright0,cright0,y,nx0,ny0,nc0,nx1,ny1,nc1,nx2,ny2,nc2) { if (y==ny1) { zl = nz1; pzl = pzn; } int xleft = xleft0, xright = xright0, cleft = cleft0, cright = cright0; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,cleft,cright); const int dx = xright - xleft, dc = cright>cleft?cright - cleft:cleft - cright, rc = dx?(cright-cleft)/dx:0, sc = cright>cleft?1:-1, ndc = dc-(dx?dx*(dc/dx):0); const tzfloat pentez = (zright - zleft)/dx; int errc = dx>>1; if (xleft<0 && dx) { cleft-=xleft*(cright - cleft)/dx; zleft-=xleft*(zright - zleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T *ptrd = data(xleft,y); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) for (int x = xleft; x<=xright; ++x, ++ptrd, ++ptrz) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { *ptrd = (T)(cleft<256?cleft**(col++)/256:((512-cleft)**(col++)+(cleft-256)*maxval)/256); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } else for (int x = xleft; x<=xright; ++x, ++ptrd, ++ptrz) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { const T val = (T)(cleft<256?cleft**(col++)/256:((512-cleft)**(col++)+(cleft-256)*maxval)/256); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } zr+=pzr; zl+=pzl; } return *this; } //! Draw a color-interpolated 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color1 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the first vertex. \param color2 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the seconf vertex. \param color3 Pointer to \c spectrum() consecutive values of type \c T, defining the color of the third vertex. \param opacity Drawing opacity. **/ template<typename tc1, typename tc2, typename tc3> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc1 *const color1, const tc2 *const color2, const tc3 *const color3, const float opacity=1) { const unsigned char one = 1; cimg_forC(*this,c) get_shared_channel(c).draw_triangle(x0,y0,x1,y1,x2,y2,&one,color1[c],color2[c],color3[c],opacity); return *this; } //! Draw a textured 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param opacity Drawing opacity. \param brightness Brightness factor of the drawing (in [0,2]). **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float opacity=1, const float brightness=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0), nbrightness = brightness<0?0:(brightness>2?2:brightness); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, ntx0 = tx0, nty0 = ty0, ntx1 = tx1, nty1 = ty1, ntx2 = tx2, nty2 = ty2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2); if (ny0>=height() || ny2<0) return *this; _cimg_for_triangle3(*this,xleft0,txleft0,tyleft0,xright0,txright0,tyright0,y, nx0,ny0,ntx0,nty0,nx1,ny1,ntx1,nty1,nx2,ny2,ntx2,nty2) { int xleft = xleft0, xright = xright0, txleft = txleft0, txright = txright0, tyleft = tyleft0, tyright = tyright0; if (xright<xleft) cimg::swap(xleft,xright,txleft,txright,tyleft,tyright); const int dx = xright - xleft, dtx = txright>txleft?txright - txleft:txleft - txright, dty = tyright>tyleft?tyright - tyleft:tyleft - tyright, rtx = dx?(txright - txleft)/dx:0, rty = dx?(tyright - tyleft)/dx:0, stx = txright>txleft?1:-1, sty = tyright>tyleft?1:-1, ndtx = dtx - (dx?dx*(dtx/dx):0), ndty = dty - (dx?dx*(dty/dx):0); int errtx = dx>>1, errty = errtx; if (xleft<0 && dx) { txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) { if (nbrightness==1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)*col; ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)(nbrightness**col); ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)((2-nbrightness)**(col++) + (nbrightness-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } } else { if (nbrightness==1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)(nopacity**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)(nopacity*nbrightness**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { const T val = (T)((2-nbrightness)**(col++) + (nbrightness-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } } } return *this; } //! Draw a 2d textured triangle, with perspective correction. template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float opacity=1, const float brightness=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0), nbrightness = brightness<0?0:(brightness>2?2:brightness); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2; float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2, nz0 = 1/z0, nz1 = 1/z1, nz2 = 1/z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); _cimg_for_triangle1(*this,xleft0,xright0,y,nx0,ny0,nx1,ny1,nx2,ny2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0; float zleft = zl, zright = zr, txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright); const int dx = xright - xleft; const float pentez = (zright - zleft)/dx, pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; if (xleft<0 && dx) { zleft-=xleft*(zright - zleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) { if (nbrightness==1) for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)*col; ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else if (nbrightness<1) for (int x=xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nbrightness**col); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)((2-nbrightness)**col + (nbrightness-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } } else { if (nbrightness==1) for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nopacity**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nopacity*nbrightness**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const T val = (T)((2-nbrightness)**col + (nbrightness-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a textured 2d triangle, with perspective correction and z-buffering. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float opacity=1, const float brightness=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,opacity,brightness); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0), nbrightness = brightness<0?0:(brightness>2?2:brightness); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2; float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2; tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle1(*this,xleft0,xright0,y,nx0,ny0,nx1,ny1,nx2,ny2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0; float txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright); const int dx = xright - xleft; const float pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; const tzfloat pentez = (zright - zleft)/dx; if (xleft<0 && dx) { zleft-=xleft*(zright - zleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T *ptrd = data(xleft,y,0,0); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) { if (nbrightness==1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)*col; ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nbrightness**col); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)((2-nbrightness)**col + (nbrightness-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } } else { if (nbrightness==1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nopacity**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else if (nbrightness<1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(nopacity*nbrightness**col + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const T val = (T)((2-nbrightness)**col + (nbrightness-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; } } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a Phong-shaded 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const tc *const color, const CImg<tl>& light, const int lx0, const int ly0, const int lx1, const int ly1, const int lx2, const int ly2, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(light)) return draw_triangle(x0,y0,x1,y1,x2,y2,color,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nlx0 = lx0, nly0 = ly0, nlx1 = lx1, nly1 = ly1, nlx2 = lx2, nly2 = ly2; const long whd = (long)_width*_height*_depth, offx = _spectrum*whd-1; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nlx0,nlx1,nly0,nly1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,nlx0,nlx2,nly0,nly2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,nlx1,nlx2,nly1,nly2); if (ny0>=height() || ny2<0) return *this; _cimg_for_triangle3(*this,xleft0,lxleft0,lyleft0,xright0,lxright0,lyright0,y, nx0,ny0,nlx0,nly0,nx1,ny1,nlx1,nly1,nx2,ny2,nlx2,nly2) { int xleft = xleft0, xright = xright0, lxleft = lxleft0, lxright = lxright0, lyleft = lyleft0, lyright = lyright0; if (xright<xleft) cimg::swap(xleft,xright,lxleft,lxright,lyleft,lyright); const int dx = xright - xleft, dlx = lxright>lxleft?lxright - lxleft:lxleft - lxright, dly = lyright>lyleft?lyright - lyleft:lyleft - lyright, rlx = dx?(lxright - lxleft)/dx:0, rly = dx?(lyright - lyleft)/dx:0, slx = lxright>lxleft?1:-1, sly = lyright>lyleft?1:-1, ndlx = dlx - (dx?dx*(dlx/dx):0), ndly = dly - (dx?dx*(dly/dx):0); int errlx = dx>>1, errly = errlx; if (xleft<0 && dx) { lxleft-=xleft*(lxright - lxleft)/dx; lyleft-=xleft*(lyright - lyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const tc *col = color; cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); *ptrd = (T)(l<1?l**(col++):((2-l)**(col++)+(l-1)*maxval)); ptrd+=whd; } ptrd-=offx; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = color; cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const T val = (T)(l<1?l**(col++):((2-l)**(col++)+(l-1)*maxval)); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } } return *this; } //! Draw a Phong-shaded 2d triangle, with z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const tc *const color, const CImg<tl>& light, const int lx0, const int ly0, const int lx1, const int ly1, const int lx2, const int ly2, const float opacity=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_triangle(): Specified color is (null).", cimg_instance); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color, +light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nlx0 = lx0, nly0 = ly0, nlx1 = lx1, nly1 = ly1, nlx2 = lx2, nly2 = ly2; tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,nlx0,nlx1,nly0,nly1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,nlx0,nlx2,nly0,nly2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,nlx1,nlx2,nly1,nly2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle3(*this,xleft0,lxleft0,lyleft0,xright0,lxright0,lyright0,y, nx0,ny0,nlx0,nly0,nx1,ny1,nlx1,nly1,nx2,ny2,nlx2,nly2) { if (y==ny1) { zl = nz1; pzl = pzn; } int xleft = xleft0, xright = xright0, lxleft = lxleft0, lxright = lxright0, lyleft = lyleft0, lyright = lyright0; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,lxleft,lxright,lyleft,lyright); const int dx = xright - xleft, dlx = lxright>lxleft?lxright - lxleft:lxleft - lxright, dly = lyright>lyleft?lyright - lyleft:lyleft - lyright, rlx = dx?(lxright - lxleft)/dx:0, rly = dx?(lyright - lyleft)/dx:0, slx = lxright>lxleft?1:-1, sly = lyright>lyleft?1:-1, ndlx = dlx - (dx?dx*(dlx/dx):0), ndly = dly - (dx?dx*(dly/dx):0); const tzfloat pentez = (zright - zleft)/dx; int errlx = dx>>1, errly = errlx; if (xleft<0 && dx) { zleft-=xleft*(zright - zleft)/dx; lxleft-=xleft*(lxright - lxleft)/dx; lyleft-=xleft*(lyright - lyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T *ptrd = data(xleft,y,0,0); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const tc cval = *(col++); *ptrd = (T)(l<1?l*cval:(2-l)*cval+(l-1)*maxval); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tc *col = color; cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const tc cval = *(col++); const T val = (T)(l<1?l*cval:(2-l)*cval+(l-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; } ptrd-=offx; } zleft+=pentez; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } zr+=pzr; zl+=pzl; } return *this; } //! Draw a textured Gouraud-shaded 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param brightness0 Brightness factor of the first vertex. \param brightness1 Brightness factor of the second vertex. \param brightness2 Brightness factor of the third vertex. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float brightness0, const float brightness1, const float brightness2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,brightness0,brightness1,brightness2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, ntx0 = tx0, nty0 = ty0, ntx1 = tx1, nty1 = ty1, ntx2 = tx2, nty2 = ty2, nc0 = (int)((brightness0<0.0f?0.0f:(brightness0>2.0f?2.0f:brightness0))*256.0f), nc1 = (int)((brightness1<0.0f?0.0f:(brightness1>2.0f?2.0f:brightness1))*256.0f), nc2 = (int)((brightness2<0.0f?0.0f:(brightness2>2.0f?2.0f:brightness2))*256.0f); if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nc0,nc1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nc0,nc2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nc1,nc2); if (ny0>=height() || ny2<0) return *this; _cimg_for_triangle4(*this,xleft0,cleft0,txleft0,tyleft0,xright0,cright0,txright0,tyright0,y, nx0,ny0,nc0,ntx0,nty0,nx1,ny1,nc1,ntx1,nty1,nx2,ny2,nc2,ntx2,nty2) { int xleft = xleft0, xright = xright0, cleft = cleft0, cright = cright0, txleft = txleft0, txright = txright0, tyleft = tyleft0, tyright = tyright0; if (xright<xleft) cimg::swap(xleft,xright,cleft,cright,txleft,txright,tyleft,tyright); const int dx = xright - xleft, dc = cright>cleft?cright - cleft:cleft - cright, dtx = txright>txleft?txright - txleft:txleft - txright, dty = tyright>tyleft?tyright - tyleft:tyleft - tyright, rc = dx?(cright - cleft)/dx:0, rtx = dx?(txright - txleft)/dx:0, rty = dx?(tyright - tyleft)/dx:0, sc = cright>cleft?1:-1, stx = txright>txleft?1:-1, sty = tyright>tyleft?1:-1, ndc = dc - (dx?dx*(dc/dx):0), ndtx = dtx - (dx?dx*(dtx/dx):0), ndty = dty - (dx?dx*(dty/dx):0); int errc = dx>>1, errtx = errc, errty = errc; if (xleft<0 && dx) { cleft-=xleft*(cright - cleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { *ptrd = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); ptrd+=whd; col+=twhd; } ptrd-=offx; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { const T val = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } } return *this; } //! Draw a textured Gouraud-shaded 2d triangle, with perspective correction \overloading. template<typename tc> CImg<T>& draw_triangle(const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float brightness0, const float brightness1, const float brightness2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, brightness0,brightness1,brightness2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nc0 = (int)((brightness0<0.0f?0.0f:(brightness0>2.0f?2.0f:brightness0))*256.0f), nc1 = (int)((brightness1<0.0f?0.0f:(brightness1>2.0f?2.0f:brightness1))*256.0f), nc2 = (int)((brightness2<0.0f?0.0f:(brightness2>2.0f?2.0f:brightness2))*256.0f); float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2, nz0 = 1/z0, nz1 = 1/z1, nz2 = 1/z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nz0,nz1,nc0,nc1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nz0,nz2,nc0,nc2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nz1,nz2,nc1,nc2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); _cimg_for_triangle2(*this,xleft0,cleft0,xright0,cright0,y,nx0,ny0,nc0,nx1,ny1,nc1,nx2,ny2,nc2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0, cleft = cleft0, cright = cright0; float zleft = zl, zright = zr, txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright,cleft,cright); const int dx = xright - xleft, dc = cright>cleft?cright - cleft:cleft - cright, rc = dx?(cright - cleft)/dx:0, sc = cright>cleft?1:-1, ndc = dc - (dx?dx*(dc/dx):0); const float pentez = (zright - zleft)/dx, pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; int errc = dx>>1; if (xleft<0 && dx) { cleft-=xleft*(cright - cleft)/dx; zleft-=xleft*(zright - zleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } else for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const T val = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a textured Gouraud-shaded 2d triangle, with perspective correction and z-buffering \overloading. template<typename tz, typename tc> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const float brightness0, const float brightness1, const float brightness2, const float opacity=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2, brightness0,brightness1,brightness2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nc0 = (int)((brightness0<0.0f?0.0f:(brightness0>2.0f?2.0f:brightness0))*256.0f), nc1 = (int)((brightness1<0.0f?0.0f:(brightness1>2.0f?2.0f:brightness1))*256.0f), nc2 = (int)((brightness2<0.0f?0.0f:(brightness2>2.0f?2.0f:brightness2))*256.0f); float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2; tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nz0,nz1,nc0,nc1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nz0,nz2,nc0,nc2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nz1,nz2,nc1,nc2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle2(*this,xleft0,cleft0,xright0,cright0,y,nx0,ny0,nc0,nx1,ny1,nc1,nx2,ny2,nc2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0, cleft = cleft0, cright = cright0; float txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright,cleft,cright); const int dx = xright - xleft, dc = cright>cleft?cright - cleft:cleft - cright, rc = dx?(cright - cleft)/dx:0, sc = cright>cleft?1:-1, ndc = dc - (dx?dx*(dc/dx):0); float pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; const tzfloat pentez = (zright - zleft)/dx; int errc = dx>>1; if (xleft<0 && dx) { cleft-=xleft*(cright - cleft)/dx; zleft-=xleft*(zright - zleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) for (int x = xleft; x<=xright; ++x, ++ptrd, ++ptrz) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { *ptrd = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } else for (int x = xleft; x<=xright; ++x, ++ptrd, ++ptrz) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const T val = (T)(cleft<256?cleft**col/256:((512-cleft)**col+(cleft-256)*maxval)/256); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; cleft+=rc+((errc-=ndc)<0?errc+=dx,sc:0); } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a textured Phong-shaded 2d triangle. /** \param x0 X-coordinate of the first vertex in the image instance. \param y0 Y-coordinate of the first vertex in the image instance. \param x1 X-coordinate of the second vertex in the image instance. \param y1 Y-coordinate of the second vertex in the image instance. \param x2 X-coordinate of the third vertex in the image instance. \param y2 Y-coordinate of the third vertex in the image instance. \param texture Texture image used to fill the triangle. \param tx0 X-coordinate of the first vertex in the texture image. \param ty0 Y-coordinate of the first vertex in the texture image. \param tx1 X-coordinate of the second vertex in the texture image. \param ty1 Y-coordinate of the second vertex in the texture image. \param tx2 X-coordinate of the third vertex in the texture image. \param ty2 Y-coordinate of the third vertex in the texture image. \param light Light image. \param lx0 X-coordinate of the first vertex in the light image. \param ly0 Y-coordinate of the first vertex in the light image. \param lx1 X-coordinate of the second vertex in the light image. \param ly1 Y-coordinate of the second vertex in the light image. \param lx2 X-coordinate of the third vertex in the light image. \param ly2 Y-coordinate of the third vertex in the light image. \param opacity Drawing opacity. **/ template<typename tc, typename tl> CImg<T>& draw_triangle(const int x0, const int y0, const int x1, const int y1, const int x2, const int y2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const CImg<tl>& light, const int lx0, const int ly0, const int lx1, const int ly1, const int lx2, const int ly2, const float opacity=1) { if (is_empty()) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,x1,y1,x2,y2,texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, ntx0 = tx0, nty0 = ty0, ntx1 = tx1, nty1 = ty1, ntx2 = tx2, nty2 = ty2, nlx0 = lx0, nly0 = ly0, nlx1 = lx1, nly1 = ly1, nlx2 = lx2, nly2 = ly2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nlx0,nlx1,nly0,nly1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nlx0,nlx2,nly0,nly2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nlx1,nlx2,nly1,nly2); if (ny0>=height() || ny2<0) return *this; _cimg_for_triangle5(*this,xleft0,lxleft0,lyleft0,txleft0,tyleft0,xright0,lxright0,lyright0,txright0,tyright0,y, nx0,ny0,nlx0,nly0,ntx0,nty0,nx1,ny1,nlx1,nly1,ntx1,nty1,nx2,ny2,nlx2,nly2,ntx2,nty2) { int xleft = xleft0, xright = xright0, lxleft = lxleft0, lxright = lxright0, lyleft = lyleft0, lyright = lyright0, txleft = txleft0, txright = txright0, tyleft = tyleft0, tyright = tyright0; if (xright<xleft) cimg::swap(xleft,xright,lxleft,lxright,lyleft,lyright,txleft,txright,tyleft,tyright); const int dx = xright - xleft, dlx = lxright>lxleft?lxright - lxleft:lxleft - lxright, dly = lyright>lyleft?lyright - lyleft:lyleft - lyright, dtx = txright>txleft?txright - txleft:txleft - txright, dty = tyright>tyleft?tyright - tyleft:tyleft - tyright, rlx = dx?(lxright - lxleft)/dx:0, rly = dx?(lyright - lyleft)/dx:0, rtx = dx?(txright - txleft)/dx:0, rty = dx?(tyright - tyleft)/dx:0, slx = lxright>lxleft?1:-1, sly = lyright>lyleft?1:-1, stx = txright>txleft?1:-1, sty = tyright>tyleft?1:-1, ndlx = dlx - (dx?dx*(dlx/dx):0), ndly = dly - (dx?dx*(dly/dx):0), ndtx = dtx - (dx?dx*(dtx/dx):0), ndty = dty - (dx?dx*(dty/dx):0); int errlx = dx>>1, errly = errlx, errtx = errlx, errty = errlx; if (xleft<0 && dx) { lxleft-=xleft*(lxright - lxleft)/dx; lyleft-=xleft*(lyright - lyleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); *ptrd = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } else for (int x = xleft; x<=xright; ++x) { const tc *col = texture.data(txleft,tyleft); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const T val = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); txleft+=rtx+((errtx-=ndtx)<0?errtx+=dx,stx:0); tyleft+=rty+((errty-=ndty)<0?errty+=dx,sty:0); } } return *this; } //! Draw a textured Phong-shaded 2d triangle, with perspective correction. template<typename tc, typename tl> CImg<T>& draw_triangle(const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const CImg<tl>& light, const int lx0, const int ly0, const int lx1, const int ly1, const int lx2, const int ly2, const float opacity=1) { if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd-1; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nlx0 = lx0, nly0 = ly0, nlx1 = lx1, nly1 = ly1, nlx2 = lx2, nly2 = ly2; float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2, nz0 = 1/z0, nz1 = 1/z1, nz2 = 1/z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nlx0,nlx1,nly0,nly1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nlx0,nlx2,nly0,nly2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nlx1,nlx2,nly1,nly2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); _cimg_for_triangle3(*this,xleft0,lxleft0,lyleft0,xright0,lxright0,lyright0,y, nx0,ny0,nlx0,nly0,nx1,ny1,nlx1,nly1,nx2,ny2,nlx2,nly2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0, lxleft = lxleft0, lxright = lxright0, lyleft = lyleft0, lyright = lyright0; float zleft = zl, zright = zr, txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright,lxleft,lxright,lyleft,lyright); const int dx = xright - xleft, dlx = lxright>lxleft?lxright - lxleft:lxleft - lxright, dly = lyright>lyleft?lyright - lyleft:lyleft - lyright, rlx = dx?(lxright - lxleft)/dx:0, rly = dx?(lyright - lyleft)/dx:0, slx = lxright>lxleft?1:-1, sly = lyright>lyleft?1:-1, ndlx = dlx - (dx?dx*(dlx/dx):0), ndly = dly - (dx?dx*(dly/dx):0); const float pentez = (zright - zleft)/dx, pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; int errlx = dx>>1, errly = errlx; if (xleft<0 && dx) { zleft-=xleft*(zright - zleft)/dx; lxleft-=xleft*(lxright - lxleft)/dx; lyleft-=xleft*(lyright - lyleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y,0,0); if (opacity>=1) for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); *ptrd = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } else for (int x = xleft; x<=xright; ++x) { const float invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const T val = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; zleft+=pentez; txleft+=pentetx; tyleft+=pentety; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a textured Phong-shaded 2d triangle, with perspective correction and z-buffering. template<typename tz, typename tc, typename tl> CImg<T>& draw_triangle(CImg<tz>& zbuffer, const int x0, const int y0, const float z0, const int x1, const int y1, const float z1, const int x2, const int y2, const float z2, const CImg<tc>& texture, const int tx0, const int ty0, const int tx1, const int ty1, const int tx2, const int ty2, const CImg<tl>& light, const int lx0, const int ly0, const int lx1, const int ly1, const int lx2, const int ly2, const float opacity=1) { typedef typename cimg::superset<tz,float>::type tzfloat; if (is_empty() || z0<=0 || z1<=0 || z2<=0) return *this; if (!is_sameXY(zbuffer)) throw CImgArgumentException(_cimg_instance "draw_triangle(): Instance and specified Z-buffer (%u,%u,%u,%u,%p) have different dimensions.", cimg_instance, zbuffer._width,zbuffer._height,zbuffer._depth,zbuffer._spectrum,zbuffer._data); if (texture._depth>1 || texture._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).", cimg_instance, texture._width,texture._height,texture._depth,texture._spectrum,texture._data); if (light._depth>1 || light._spectrum<_spectrum) throw CImgArgumentException(_cimg_instance "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).", cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data); if (is_overlapped(texture)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, +texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); if (is_overlapped(light)) return draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2, texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity); static const T maxval = (T)cimg::min(cimg::type<T>::max(),cimg::type<tc>::max()); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const long whd = (long)_width*_height*_depth, twhd = (long)texture._width*texture._height*texture._depth, offx = _spectrum*whd; int nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1, nx2 = x2, ny2 = y2, nlx0 = lx0, nly0 = ly0, nlx1 = lx1, nly1 = ly1, nlx2 = lx2, nly2 = ly2; float ntx0 = tx0/z0, nty0 = ty0/z0, ntx1 = tx1/z1, nty1 = ty1/z1, ntx2 = tx2/z2, nty2 = ty2/z2; tzfloat nz0 = 1/(tzfloat)z0, nz1 = 1/(tzfloat)z1, nz2 = 1/(tzfloat)z2; if (ny0>ny1) cimg::swap(nx0,nx1,ny0,ny1,ntx0,ntx1,nty0,nty1,nlx0,nlx1,nly0,nly1,nz0,nz1); if (ny0>ny2) cimg::swap(nx0,nx2,ny0,ny2,ntx0,ntx2,nty0,nty2,nlx0,nlx2,nly0,nly2,nz0,nz2); if (ny1>ny2) cimg::swap(nx1,nx2,ny1,ny2,ntx1,ntx2,nty1,nty2,nlx1,nlx2,nly1,nly2,nz1,nz2); if (ny0>=height() || ny2<0) return *this; float ptxl = (ntx1 - ntx0)/(ny1 - ny0), ptxr = (ntx2 - ntx0)/(ny2 - ny0), ptxn = (ntx2 - ntx1)/(ny2 - ny1), ptyl = (nty1 - nty0)/(ny1 - ny0), ptyr = (nty2 - nty0)/(ny2 - ny0), ptyn = (nty2 - nty1)/(ny2 - ny1), txr = ny0>=0?ntx0:(ntx0 - ny0*(ntx2 - ntx0)/(ny2 - ny0)), tyr = ny0>=0?nty0:(nty0 - ny0*(nty2 - nty0)/(ny2 - ny0)), txl = ny1>=0?(ny0>=0?ntx0:(ntx0 - ny0*(ntx1 - ntx0)/(ny1 - ny0))):(ptxl=ptxn,(ntx1 - ny1*(ntx2 - ntx1)/(ny2 - ny1))), tyl = ny1>=0?(ny0>=0?nty0:(nty0 - ny0*(nty1 - nty0)/(ny1 - ny0))):(ptyl=ptyn,(nty1 - ny1*(nty2 - nty1)/(ny2 - ny1))); tzfloat pzl = (nz1 - nz0)/(ny1 - ny0), pzr = (nz2 - nz0)/(ny2 - ny0), pzn = (nz2 - nz1)/(ny2 - ny1), zr = ny0>=0?nz0:(nz0 - ny0*(nz2 - nz0)/(ny2 - ny0)), zl = ny1>=0?(ny0>=0?nz0:(nz0 - ny0*(nz1 - nz0)/(ny1 - ny0))):(pzl=pzn,(nz1 - ny1*(nz2 - nz1)/(ny2 - ny1))); _cimg_for_triangle3(*this,xleft0,lxleft0,lyleft0,xright0,lxright0,lyright0,y, nx0,ny0,nlx0,nly0,nx1,ny1,nlx1,nly1,nx2,ny2,nlx2,nly2) { if (y==ny1) { zl = nz1; txl = ntx1; tyl = nty1; pzl = pzn; ptxl = ptxn; ptyl = ptyn; } int xleft = xleft0, xright = xright0, lxleft = lxleft0, lxright = lxright0, lyleft = lyleft0, lyright = lyright0; float txleft = txl, txright = txr, tyleft = tyl, tyright = tyr; tzfloat zleft = zl, zright = zr; if (xright<xleft) cimg::swap(xleft,xright,zleft,zright,txleft,txright,tyleft,tyright,lxleft,lxright,lyleft,lyright); const int dx = xright - xleft, dlx = lxright>lxleft?lxright - lxleft:lxleft - lxright, dly = lyright>lyleft?lyright - lyleft:lyleft - lyright, rlx = dx?(lxright - lxleft)/dx:0, rly = dx?(lyright - lyleft)/dx:0, slx = lxright>lxleft?1:-1, sly = lyright>lyleft?1:-1, ndlx = dlx - (dx?dx*(dlx/dx):0), ndly = dly - (dx?dx*(dly/dx):0); float pentetx = (txright - txleft)/dx, pentety = (tyright - tyleft)/dx; const tzfloat pentez = (zright - zleft)/dx; int errlx = dx>>1, errly = errlx; if (xleft<0 && dx) { zleft-=xleft*(zright - zleft)/dx; lxleft-=xleft*(lxright - lxleft)/dx; lyleft-=xleft*(lyright - lyleft)/dx; txleft-=xleft*(txright - txleft)/dx; tyleft-=xleft*(tyright - tyleft)/dx; } if (xleft<0) xleft = 0; if (xright>=width()-1) xright = width()-1; T* ptrd = data(xleft,y); tz *ptrz = zbuffer.data(xleft,y); if (opacity>=1) for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); *ptrd = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } else for (int x = xleft; x<=xright; ++x, ++ptrz, ++ptrd) { if (zleft>=(tzfloat)*ptrz) { *ptrz = (tz)zleft; const tzfloat invz = 1/zleft; const tc *col = texture.data((int)(txleft*invz),(int)(tyleft*invz)); cimg_forC(*this,c) { const tl l = light(lxleft,lyleft,c); const T val = (T)(l<1?l**col:(2-l)**col+(l-1)*maxval); *ptrd = (T)(nopacity*val + *ptrd*copacity); ptrd+=whd; col+=twhd; } ptrd-=offx; } zleft+=pentez; txleft+=pentetx; tyleft+=pentety; lxleft+=rlx+((errlx-=ndlx)<0?errlx+=dx,slx:0); lyleft+=rly+((errly-=ndly)<0?errly+=dx,sly:0); } zr+=pzr; txr+=ptxr; tyr+=ptyr; zl+=pzl; txl+=ptxl; tyl+=ptyl; } return *this; } //! Draw a filled 4d rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param c0 C-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param c1 C-coordinate of the lower-right rectangle corner. \param val Scalar value used to fill the rectangle area. \param opacity Drawing opacity. **/ CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int c0, const int x1, const int y1, const int z1, const int c1, const T val, const float opacity=1) { if (is_empty()) return *this; const bool bx = (x0<x1), by = (y0<y1), bz = (z0<z1), bc = (c0<c1); const int nx0 = bx?x0:x1, nx1 = bx?x1:x0, ny0 = by?y0:y1, ny1 = by?y1:y0, nz0 = bz?z0:z1, nz1 = bz?z1:z0, nc0 = bc?c0:c1, nc1 = bc?c1:c0; const int lX = (1 + nx1 - nx0) + (nx1>=width()?width() - 1 - nx1:0) + (nx0<0?nx0:0), lY = (1 + ny1 - ny0) + (ny1>=height()?height() - 1 - ny1:0) + (ny0<0?ny0:0), lZ = (1 + nz1 - nz0) + (nz1>=depth()?depth() - 1 - nz1:0) + (nz0<0?nz0:0), lC = (1 + nc1 - nc0) + (nc1>=spectrum()?spectrum() - 1 - nc1:0) + (nc0<0?nc0:0); const unsigned long offX = (unsigned long)_width - lX, offY = (unsigned long)_width*(_height - lY), offZ = (unsigned long)_width*_height*(_depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); T *ptrd = data(nx0<0?0:nx0,ny0<0?0:ny0,nz0<0?0:nz0,nc0<0?0:nc0); if (lX>0 && lY>0 && lZ>0 && lC>0) for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) { if (sizeof(T)!=1) { for (int x = 0; x<lX; ++x) *(ptrd++) = val; ptrd+=offX; } else { std::memset(ptrd,(int)val,lX); ptrd+=_width; } } else { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*val + *ptrd*copacity); ++ptrd; } ptrd+=offX; } } ptrd+=offY; } ptrd+=offZ; } return *this; } //! Draw a filled 3d rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param z0 Z-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param z1 Z-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_rectangle(): Specified color is (null).", cimg_instance); cimg_forC(*this,c) draw_rectangle(x0,y0,z0,c,x1,y1,z1,c,(T)color[c],opacity); return *this; } //! Draw an outlined 3d rectangle \overloading. template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int z0, const int x1, const int y1, const int z1, const tc *const color, const float opacity, const unsigned int pattern) { return draw_line(x0,y0,z0,x1,y0,z0,color,opacity,pattern,true). draw_line(x1,y0,z0,x1,y1,z0,color,opacity,pattern,false). draw_line(x1,y1,z0,x0,y1,z0,color,opacity,pattern,false). draw_line(x0,y1,z0,x0,y0,z0,color,opacity,pattern,false). draw_line(x0,y0,z1,x1,y0,z1,color,opacity,pattern,true). draw_line(x1,y0,z1,x1,y1,z1,color,opacity,pattern,false). draw_line(x1,y1,z1,x0,y1,z1,color,opacity,pattern,false). draw_line(x0,y1,z1,x0,y0,z1,color,opacity,pattern,false). draw_line(x0,y0,z0,x0,y0,z1,color,opacity,pattern,true). draw_line(x1,y0,z0,x1,y0,z1,color,opacity,pattern,true). draw_line(x1,y1,z0,x1,y1,z1,color,opacity,pattern,true). draw_line(x0,y1,z0,x0,y1,z1,color,opacity,pattern,true); } //! Draw a filled 2d rectangle. /** \param x0 X-coordinate of the upper-left rectangle corner. \param y0 Y-coordinate of the upper-left rectangle corner. \param x1 X-coordinate of the lower-right rectangle corner. \param y1 Y-coordinate of the lower-right rectangle corner. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity=1) { return draw_rectangle(x0,y0,0,x1,y1,_depth-1,color,opacity); } //! Draw a outlined 2d rectangle \overloading. template<typename tc> CImg<T>& draw_rectangle(const int x0, const int y0, const int x1, const int y1, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (y0==y1) return draw_line(x0,y0,x1,y0,color,opacity,pattern,true); if (x0==x1) return draw_line(x0,y0,x0,y1,color,opacity,pattern,true); const bool bx = (x0<x1), by = (y0<y1); const int nx0 = bx?x0:x1, nx1 = bx?x1:x0, ny0 = by?y0:y1, ny1 = by?y1:y0; if (ny1==ny0+1) return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false); return draw_line(nx0,ny0,nx1,ny0,color,opacity,pattern,true). draw_line(nx1,ny0+1,nx1,ny1-1,color,opacity,pattern,false). draw_line(nx1,ny1,nx0,ny1,color,opacity,pattern,false). draw_line(nx0,ny1-1,nx0,ny0+1,color,opacity,pattern,false); } //! Draw a filled 2d polygon. /** \param points Set of polygon vertices. \param color Pointer to \c spectrum() consecutive values of type \c T, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_polygon(const CImg<t>& points, const tc *const color, const float opacity=1) { if (is_empty() || !points || points._width<3) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_polygon(): Specified color is (null).", cimg_instance); // Normalize 2d input coordinates. CImg<intT> npoints(points._width,2); int x = npoints(0,0) = (int)points(0,0), y = npoints(0,1) = (int)points(0,1); unsigned int nb_points = 1; for (unsigned int p = 1; p<points._width; ++p) { const int nx = (int)points(p,0), ny = (int)points(p,1); if (nx!=x || ny!=y) { npoints(nb_points,0) = nx; npoints(nb_points++,1) = ny; x = nx; y = ny; } } if (nb_points==3) return draw_triangle((int)npoints(0,0),(int)npoints(0,1), (int)npoints(1,0),(int)npoints(1,1), (int)npoints(2,0),(int)npoints(2,1),color,opacity); // Draw polygon segments. _draw_scanline(color,opacity); int xmax = 0, xmin = (int)npoints.get_shared_points(0,nb_points-1,0).min_max(xmax), ymax = 0, ymin = (int)npoints.get_shared_points(0,nb_points-1,1).min_max(ymax); if (xmax<0 || xmin>=width() || ymax<0 || ymin>=height()) return *this; if (ymin==ymax) return _draw_scanline(xmin,xmax,ymin,color,opacity); const unsigned int nymin = ymin<0?0:(unsigned int)ymin, nymax = ymax>=height()?_height-1:(unsigned int)ymax, dy = 1 + nymax - nymin; CImg<intT> X(1+2*nb_points,dy,1,1,0), tmp; int cx = (int)npoints(0,0), cy = (int)npoints(0,1); unsigned int cp = 0; for (unsigned int p = 0; p<nb_points; ++p) { const unsigned int np = (p!=nb_points-1)?p+1:0, ap = (np!=nb_points-1)?np+1:0; const int nx = (int)npoints(np,0), ny = (int)npoints(np,1), ay = (int)npoints(ap,1), y0 = cy - nymin, y1 = ny - nymin; if (y0!=y1) { const int countermin = ((ny<ay && cy<ny) || (ny>ay && cy>ny))?1:0; for (int x = cx, y = y0, _sx = 1, _sy = 1, _dx = nx>cx?nx-cx:((_sx=-1),cx-nx), _dy = y1>y0?y1-y0:((_sy=-1),y0-y1), _counter = ((_dx-=_dy?_dy*(_dx/_dy):0),_dy), _err = _dx>>1, _rx = _dy?(nx-cx)/_dy:0; _counter>=countermin; --_counter, y+=_sy, x+=_rx + ((_err-=_dx)<0?_err+=_dy,_sx:0)) if (y>=0 && y<(int)dy) X(++X(0,y),y) = x; cp = np; cx = nx; cy = ny; } else { const int pp = (cp?cp-1:nb_points-1), py = (int)npoints(pp,1); if (y0>=0 && y0<(int)dy && (!p || (cy>py && ay>cy) || (cy<py && ay<cy))) X(++X(0,y0),y0) = nx; if (cy!=ay) { cp = np; cx = nx; cy = ny; } } } // Draw polygon scanlines. for (int y = 0; y<(int)dy; ++y) { tmp.assign(X.data(1,y),X(0,y),1,1,1,true).sort(); for (int i = 1; i<=X(0,y); ) { const int xb = X(i++,y), xe = X(i++,y); _draw_scanline(xb,xe,nymin+y,color,opacity); } } return *this; } //! Draw a outlined 2d polygon \overloading. template<typename t, typename tc> CImg<T>& draw_polygon(const CImg<t>& points, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty() || !points || points._width<3) return *this; bool ninit_hatch = true; switch (points._height) { case 0 : case 1 : throw CImgArgumentException(_cimg_instance "draw_polygon(): Invalid specified point set.", cimg_instance); case 2 : { // 2d version. CImg<intT> npoints(points._width,2); int x = npoints(0,0) = (int)points(0,0), y = npoints(0,1) = (int)points(0,1); unsigned int nb_points = 1; for (unsigned int p = 1; p<points._width; ++p) { const int nx = (int)points(p,0), ny = (int)points(p,1); if (nx!=x || ny!=y) { npoints(nb_points,0) = nx; npoints(nb_points++,1) = ny; x = nx; y = ny; } } const int x0 = (int)npoints(0,0), y0 = (int)npoints(0,1); int ox = x0, oy = y0; for (unsigned int i = 1; i<nb_points; ++i) { const int x = (int)npoints(i,0), y = (int)npoints(i,1); draw_line(ox,oy,x,y,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; } draw_line(ox,oy,x0,y0,color,opacity,pattern,false); } break; default : { // 3d version. CImg<intT> npoints(points._width,3); int x = npoints(0,0) = (int)points(0,0), y = npoints(0,1) = (int)points(0,1), z = npoints(0,2) = (int)points(0,2); unsigned int nb_points = 1; for (unsigned int p = 1; p<points._width; ++p) { const int nx = (int)points(p,0), ny = (int)points(p,1), nz = (int)points(p,2); if (nx!=x || ny!=y || nz!=z) { npoints(nb_points,0) = nx; npoints(nb_points,1) = ny; npoints(nb_points++,2) = nz; x = nx; y = ny; z = nz; } } const int x0 = (int)npoints(0,0), y0 = (int)npoints(0,1), z0 = (int)npoints(0,2); int ox = x0, oy = y0, oz = z0; for (unsigned int i = 1; i<nb_points; ++i) { const int x = (int)npoints(i,0), y = (int)npoints(i,1), z = (int)npoints(i,2); draw_line(ox,oy,oz,x,y,z,color,opacity,pattern,ninit_hatch); ninit_hatch = false; ox = x; oy = y; oz = z; } draw_line(ox,oy,oz,x0,y0,z0,color,opacity,pattern,false); } } return *this; } //! Draw a filled 2d ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity=1) { return _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,0U); } //! Draw a filled 2d ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity=1) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity); } //! Draw an outlined 2d ellipse. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param r1 First radius of the ellipse. \param r2 Second radius of the ellipse. \param angle Angle of the first radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity, const unsigned int pattern) { if (pattern) _draw_ellipse(x0,y0,r1,r2,angle,color,opacity,pattern); return *this; } //! Draw an outlined 2d ellipse \overloading. /** \param x0 X-coordinate of the ellipse center. \param y0 Y-coordinate of the ellipse center. \param tensor Diffusion tensor describing the ellipse. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename t, typename tc> CImg<T>& draw_ellipse(const int x0, const int y0, const CImg<t> &tensor, const tc *const color, const float opacity, const unsigned int pattern) { CImgList<t> eig = tensor.get_symmetric_eigen(); const CImg<t> &val = eig[0], &vec = eig[1]; return draw_ellipse(x0,y0,std::sqrt(val(0)),std::sqrt(val(1)), std::atan2(vec(0,1),vec(0,0))*180/cimg::PI, color,opacity,pattern); } template<typename tc> CImg<T>& _draw_ellipse(const int x0, const int y0, const float r1, const float r2, const float angle, const tc *const color, const float opacity, const unsigned int pattern) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_ellipse(): Specified color is (null).", cimg_instance); if (r1<=0 || r2<=0) return draw_point(x0,y0,color,opacity); _draw_scanline(color,opacity); const float nr1 = cimg::abs(r1), nr2 = cimg::abs(r2), nangle = (float)(angle*cimg::PI/180), u = (float)std::cos(nangle), v = (float)std::sin(nangle), rmax = cimg::max(nr1,nr2), l1 = (float)std::pow(rmax/(nr1>0?nr1:1e-6),2), l2 = (float)std::pow(rmax/(nr2>0?nr2:1e-6),2), a = l1*u*u + l2*v*v, b = u*v*(l1-l2), c = l1*v*v + l2*u*u; const int yb = (int)std::sqrt(a*rmax*rmax/(a*c - b*b)), tymin = y0 - yb - 1, tymax = y0 + yb + 1, ymin = tymin<0?0:tymin, ymax = tymax>=height()?height()-1:tymax; int oxmin = 0, oxmax = 0; bool first_line = true; for (int y = ymin; y<=ymax; ++y) { const float Y = y - y0 + (y<y0?0.5f:-0.5f), delta = b*b*Y*Y - a*(c*Y*Y - rmax*rmax), sdelta = delta>0?(float)std::sqrt(delta)/a:0.0f, bY = b*Y/a, fxmin = x0 - 0.5f - bY - sdelta, fxmax = x0 + 0.5f - bY + sdelta; const int xmin = (int)fxmin, xmax = (int)fxmax; if (!pattern) _draw_scanline(xmin,xmax,y,color,opacity); else { if (first_line) { if (y0-yb>=0) _draw_scanline(xmin,xmax,y,color,opacity); else draw_point(xmin,y,color,opacity).draw_point(xmax,y,color,opacity); first_line = false; } else { if (xmin<oxmin) _draw_scanline(xmin,oxmin-1,y,color,opacity); else _draw_scanline(oxmin+(oxmin==xmin?0:1),xmin,y,color,opacity); if (xmax<oxmax) _draw_scanline(xmax,oxmax-1,y,color,opacity); else _draw_scanline(oxmax+(oxmax==xmax?0:1),xmax,y,color,opacity); if (y==tymax) _draw_scanline(xmin+1,xmax-1,y,color,opacity); } } oxmin = xmin; oxmax = xmax; } return *this; } //! Draw a filled 2d circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \note - Circle version of the Bresenham's algorithm is used. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); _draw_scanline(color,opacity); if (radius<0 || x0-radius>=width() || y0+radius<0 || y0-radius>=height()) return *this; if (y0>=0 && y0<height()) _draw_scanline(x0-radius,x0+radius,y0,color,opacity); for (int f = 1-radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { const int x1 = x0-x, x2 = x0+x, y1 = y0-y, y2 = y0+y; if (y1>=0 && y1<height()) _draw_scanline(x1,x2,y1,color,opacity); if (y2>=0 && y2<height()) _draw_scanline(x1,x2,y2,color,opacity); f+=(ddFy+=2); --y; } const bool no_diag = y!=(x++); ++(f+=(ddFx+=2)); const int x1 = x0-y, x2 = x0+y, y1 = y0-x, y2 = y0+x; if (no_diag) { if (y1>=0 && y1<height()) _draw_scanline(x1,x2,y1,color,opacity); if (y2>=0 && y2<height()) _draw_scanline(x1,x2,y2,color,opacity); } } return *this; } //! Draw an outlined 2d circle. /** \param x0 X-coordinate of the circle center. \param y0 Y-coordinate of the circle center. \param radius Circle radius. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern An integer whose bits describe the outline pattern. **/ template<typename tc> CImg<T>& draw_circle(const int x0, const int y0, int radius, const tc *const color, const float opacity, const unsigned int pattern) { cimg::unused(pattern); if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_circle(): Specified color is (null).", cimg_instance); if (radius<0 || x0-radius>=width() || y0+radius<0 || y0-radius>=height()) return *this; if (!radius) return draw_point(x0,y0,color,opacity); draw_point(x0-radius,y0,color,opacity).draw_point(x0+radius,y0,color,opacity). draw_point(x0,y0-radius,color,opacity).draw_point(x0,y0+radius,color,opacity); if (radius==1) return *this; for (int f = 1-radius, ddFx = 0, ddFy = -(radius<<1), x = 0, y = radius; x<y; ) { if (f>=0) { f+=(ddFy+=2); --y; } ++x; ++(f+=(ddFx+=2)); if (x!=y+1) { const int x1 = x0-y, x2 = x0+y, y1 = y0-x, y2 = y0+x, x3 = x0-x, x4 = x0+x, y3 = y0-y, y4 = y0+y; draw_point(x1,y1,color,opacity).draw_point(x1,y2,color,opacity). draw_point(x2,y1,color,opacity).draw_point(x2,y2,color,opacity); if (x!=y) draw_point(x3,y3,color,opacity).draw_point(x4,y4,color,opacity). draw_point(x4,y3,color,opacity).draw_point(x3,y4,color,opacity); } } return *this; } //! Draw an image. /** \param sprite Sprite image. \param x0 X-coordinate of the sprite position. \param y0 Y-coordinate of the sprite position. \param z0 Z-coordinate of the sprite position. \param c0 C-coordinate of the sprite position. \param opacity Drawing opacity. **/ template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<t>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const t *ptrs = sprite._data - (bx?x0:0) - (by?y0*sprite.width():0) - (bz?z0*sprite.width()*sprite.height():0) - (bc?c0*sprite.width()*sprite.height()*sprite.depth():0); const unsigned long offX = (unsigned long)_width - lX, soffX = (unsigned long)sprite._width - lX, offY = (unsigned long)_width*(_height - lY), soffY = (unsigned long)sprite._width*(sprite._height - lY), offZ = (unsigned long)_width*_height*(_depth - lZ), soffZ = (unsigned long)sprite._width*sprite._height*(sprite._depth - lZ); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { if (opacity>=1) for (int x = 0; x<lX; ++x) *(ptrd++) = (T)*(ptrs++); else for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \specialization. CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<T>& sprite, const float opacity=1) { if (is_empty() || !sprite) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity); if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1) return assign(sprite,false); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const T *ptrs = sprite._data - (bx?x0:0) - (by?y0*sprite.width():0) - (bz?z0*sprite.width()*sprite.height():0) - (bc?c0*sprite.width()*sprite.height()*sprite.depth():0); const unsigned long offX = (unsigned long)_width - lX, soffX = (unsigned long)sprite._width - lX, offY = (unsigned long)_width*(_height - lY), soffY = (unsigned long)sprite._width*(sprite._height - lY), offZ = (unsigned long)_width*_height*(_depth - lZ), soffZ = (unsigned long)sprite._width*sprite._height*(sprite._depth - lZ), slX = lX*sizeof(T); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int v = 0; v<lC; ++v) { for (int z = 0; z<lZ; ++z) { if (opacity>=1) for (int y = 0; y<lY; ++y) { std::memcpy(ptrd,ptrs,slX); ptrd+=_width; ptrs+=sprite._width; } else for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; } ptrd+=offX; ptrs+=soffX; } ptrd+=offY; ptrs+=soffY; } ptrd+=offZ; ptrs+=soffZ; } } return *this; } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,z0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const int y0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,y0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const int x0, const CImg<t>& sprite, const float opacity=1) { return draw_image(x0,0,sprite,opacity); } //! Draw an image \overloading. template<typename t> CImg<T>& draw_image(const CImg<t>& sprite, const float opacity=1) { return draw_image(0,sprite,opacity); } //! Draw a masked image. /** \param sprite Sprite image. \param mask Mask image. \param x0 X-coordinate of the sprite position in the image instance. \param y0 Y-coordinate of the sprite position in the image instance. \param z0 Z-coordinate of the sprite position in the image instance. \param c0 C-coordinate of the sprite position in the image instance. \param mask_max_value Maximum pixel value of the mask image \c mask. \param opacity Drawing opacity. \note - Pixel values of \c mask set the opacity of the corresponding pixels in \c sprite. - Dimensions along x,y and z of \p sprite and \p mask must be the same. **/ template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { if (is_empty() || !sprite || !mask) return *this; if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,mask,opacity,mask_max_value); if (is_overlapped(mask)) return draw_image(x0,y0,z0,c0,sprite,+mask,opacity,mask_max_value); if (mask._width!=sprite._width || mask._height!=sprite._height || mask._depth!=sprite._depth) throw CImgArgumentException(_cimg_instance "draw_image(): Sprite (%u,%u,%u,%u,%p) and mask (%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, sprite._width,sprite._height,sprite._depth,sprite._spectrum,sprite._data, mask._width,mask._height,mask._depth,mask._spectrum,mask._data); const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0); const int lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0), lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0), lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0), lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0); const int coff = -(bx?x0:0)-(by?y0*mask.width():0)-(bz?z0*mask.width()*mask.height():0)-(bc?c0*mask.width()*mask.height()*mask.depth():0), ssize = mask.width()*mask.height()*mask.depth(); const ti *ptrs = sprite._data + coff; const tm *ptrm = mask._data + coff; const unsigned long offX = (unsigned long)_width - lX, soffX = (unsigned long)sprite._width - lX, offY = (unsigned long)_width*(_height - lY), soffY = (unsigned long)sprite._width*(sprite._height - lY), offZ = (unsigned long)_width*_height*(_depth - lZ), soffZ = (unsigned long)sprite._width*sprite._height*(sprite._depth - lZ); if (lX>0 && lY>0 && lZ>0 && lC>0) { T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0); for (int c = 0; c<lC; ++c) { ptrm = mask._data + (ptrm - mask._data)%ssize; for (int z = 0; z<lZ; ++z) { for (int y = 0; y<lY; ++y) { for (int x = 0; x<lX; ++x) { const float mopacity = (float)(*(ptrm++)*opacity), nopacity = cimg::abs(mopacity), copacity = mask_max_value - cimg::max(mopacity,0); *ptrd = (T)((nopacity*(*(ptrs++)) + *ptrd*copacity)/mask_max_value); ++ptrd; } ptrd+=offX; ptrs+=soffX; ptrm+=soffX; } ptrd+=offY; ptrs+=soffY; ptrm+=soffY; } ptrd+=offZ; ptrs+=soffZ; ptrm+=soffZ; } } return *this; } //! Draw a masked image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const int z0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,z0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const int y0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,y0,0,sprite,mask,opacity,mask_max_value); } //! Draw a image \overloading. template<typename ti, typename tm> CImg<T>& draw_image(const int x0, const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(x0,0,sprite,mask,opacity,mask_max_value); } //! Draw an image. template<typename ti, typename tm> CImg<T>& draw_image(const CImg<ti>& sprite, const CImg<tm>& mask, const float opacity=1, const float mask_max_value=1) { return draw_image(0,sprite,mask,opacity,mask_max_value); } //! Draw a text string. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Pointer to \c spectrum() consecutive values, defining the foreground drawing color. \param background_color Pointer to \c spectrum() consecutive values, defining the background drawing color. \param opacity Drawing opacity. \param font Font used for drawing text. **/ template<typename tc1, typename tc2, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font); } //! Draw a text string \overloading. /** \note A transparent background is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); return _draw_text(x0,y0,tmp,foreground_color,(tc*)0,opacity,font); } //! Draw a text string \overloading. /** \note A transparent foreground is used for the text. **/ template<typename tc, typename t> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity, const CImgList<t>& font, ...) { if (!font) return *this; char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); return _draw_text(x0,y0,tmp,(tc*)0,background_color,opacity,font); } //! Draw a text string \overloading. /** \param x0 X-coordinate of the text in the image instance. \param y0 Y-coordinate of the text in the image instance. \param text Format of the text ('printf'-style format string). \param foreground_color Array of spectrum() values of type \c T, defining the foreground color (0 means 'transparent'). \param background_color Array of spectrum() values of type \c T, defining the background color (0 means 'transparent'). \param opacity Drawing opacity. \param font_height Height of the text font (exact match for 13,24,32,57, interpolated otherwise). **/ template<typename tc1, typename tc2> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); static CImgList<floatT> font; const unsigned int ref_height = font_height<=13?13:font_height<=28?24:font_height<=32?32:57, padding_x = font_height<=18?1:font_height<=32?2:3; if (!font || font[0]._height!=font_height) { font = CImgList<floatT>::font(ref_height,true); font[0].assign(1,font_height); if (ref_height==font_height) cimglist_for(font,l) font[l].resize(font[l]._width + padding_x,-100,-100,-100,0); } if (is_empty()) { if (font[0]._spectrum!=1) cimglist_for_in(font,0,255,l) font[l].channel(0); } else if (font[0]._spectrum<_spectrum) cimglist_for_in(font,0,255,l) font[l].resize(-100,-100,1,_spectrum); if (ref_height!=font_height) for (const char *ptrs = tmp; *ptrs; ++ptrs) { const unsigned int __c = (unsigned int)(unsigned char)*ptrs, _c = (__c=='\t')?' ':__c; if (_c<font._width) { CImg<floatT> &c = font[_c]; if (c._height!=font_height) { c.resize(cimg::max(1U,c._width*font_height/c._height),font_height,-100,-100,c._height>font_height?2:3); c.resize(c._width + padding_x,-100,-100,-100,0); } } if (_c+256U<font._width) { CImg<floatT> &c = font[_c+256]; if (c._height!=font_height) { c.resize(cimg::max(1U,c._width*font_height/c._height),font_height,-100,-100,c._height>font_height?2:3); c.resize(c._width + padding_x,-100,-100,-100,0); } } } return _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font); } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const tc *const foreground_color, const int background_color=0, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; cimg::unused(background_color); char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); return draw_text(x0,y0,"%s",foreground_color,(const tc*)0,opacity,font_height,tmp); } //! Draw a text string \overloading. template<typename tc> CImg<T>& draw_text(const int x0, const int y0, const char *const text, const int, const tc *const background_color, const float opacity=1, const unsigned int font_height=13, ...) { if (!font_height) return *this; char tmp[2048] = { 0 }; std::va_list ap; va_start(ap,font_height); cimg_vsnprintf(tmp,sizeof(tmp),text,ap); va_end(ap); return draw_text(x0,y0,"%s",(tc*)0,background_color,opacity,font_height,tmp); } template<typename tc1, typename tc2, typename t> CImg<T>& _draw_text(const int x0, const int y0, const char *const text, const tc1 *const foreground_color, const tc2 *const background_color, const float opacity, const CImgList<t>& font) { if (!text) return *this; if (!font) throw CImgArgumentException(_cimg_instance "draw_text(): Empty specified font.", cimg_instance); const unsigned int text_length = (unsigned int)std::strlen(text); if (is_empty()) { // If needed, pre-compute necessary size of the image int x = 0, y = 0, w = 0; unsigned char c = 0; for (unsigned int i = 0; i<text_length; ++i) { c = text[i]; switch (c) { case '\n' : y+=font[0]._height; if (x>w) w = x; x = 0; break; case '\t' : x+=4*font[' ']._width; break; default : if (c<font._width) x+=font[c]._width; } } if (x!=0 || c=='\n') { if (x>w) w=x; y+=font[0]._height; } assign(x0+w,y0+y,1,font[0]._spectrum,0); if (background_color) cimg_forC(*this,c) get_shared_channel(c).fill((T)background_color[c]); } int x = x0, y = y0; CImg<t> letter; for (unsigned int i = 0; i<text_length; ++i) { const unsigned char c = text[i]; switch (c) { case '\n' : y+=font[' ']._height; x = x0; break; case '\t' : x+=4*font[' ']._width; break; default : if (c<font._width) { letter = font[c]; const unsigned int cmin = cimg::min(_spectrum,letter._spectrum); const CImg<t>& mask = (c+256)<(int)font._width?font[c+256]:font[c]; if (foreground_color) for (unsigned long p = 0; p<(unsigned long)letter._width*letter._height; ++p) if (mask(p)) for (unsigned int c = 0; c<cmin; ++c) letter(p,0,0,c) = (t)(letter(p,0,0,c)*foreground_color[c]); if (background_color) for (unsigned long p = 0; p<(unsigned long)letter._width*letter._height; ++p) if (!mask(p)) for (unsigned int c = 0; c<cmin; ++c) letter(p,0,0,c) = (t)background_color[c]; if (!background_color && font._width>=512) draw_image(x,y,letter,mask,opacity,(T)1); else draw_image(x,y,letter,opacity); x+=letter._width; } } } return *this; } //! Draw a 2d vector field. /** \param flow Image of 2d vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Drawing opacity. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const t2 *const color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { return draw_quiver(flow,CImg<t2>(color,_spectrum,1,1,1,true),opacity,sampling,factor,is_arrow,pattern); } //! Draw a 2d vector field, using a field of colors. /** \param flow Image of 2d vectors used as input data. \param color Image of spectrum()-D vectors corresponding to the color of each arrow. \param opacity Opacity of the drawing. \param sampling Length (in pixels) between each arrow. \param factor Length factor of each arrow (if <0, computed as a percentage of the maximum length). \param is_arrow Tells if arrows must be drawn, instead of oriented segments. \param pattern Used pattern to draw lines. \note Clipping is supported. **/ template<typename t1, typename t2> CImg<T>& draw_quiver(const CImg<t1>& flow, const CImg<t2>& color, const float opacity=1, const unsigned int sampling=25, const float factor=-20, const bool is_arrow=true, const unsigned int pattern=~0U) { if (is_empty()) return *this; if (!flow || flow._spectrum!=2) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid dimensions of specified flow (%u,%u,%u,%u,%p).", cimg_instance, flow._width,flow._height,flow._depth,flow._spectrum,flow._data); if (sampling<=0) throw CImgArgumentException(_cimg_instance "draw_quiver(): Invalid sampling value %g " "(should be >0)", cimg_instance, sampling); const bool colorfield = (color._width==flow._width && color._height==flow._height && color._depth==1 && color._spectrum==_spectrum); if (is_overlapped(flow)) return draw_quiver(+flow,color,opacity,sampling,factor,is_arrow,pattern); float vmax,fact; if (factor<=0) { float m, M = (float)flow.get_norm(2).max_min(m); vmax = (float)cimg::max(cimg::abs(m),cimg::abs(M)); if (!vmax) vmax = 1; fact = -factor; } else { fact = factor; vmax = 1; } for (unsigned int y = sampling/2; y<_height; y+=sampling) for (unsigned int x = sampling/2; x<_width; x+=sampling) { const unsigned int X = x*flow._width/_width, Y = y*flow._height/_height; float u = (float)flow(X,Y,0,0)*fact/vmax, v = (float)flow(X,Y,0,1)*fact/vmax; if (is_arrow) { const int xx = x+(int)u, yy = y+(int)v; if (colorfield) draw_arrow(x,y,xx,yy,color.get_vector_at(X,Y)._data,opacity,45,sampling/5.0f,pattern); else draw_arrow(x,y,xx,yy,color._data,opacity,45,sampling/5.0f,pattern); } else { if (colorfield) draw_line((int)(x-0.5*u),(int)(y-0.5*v),(int)(x+0.5*u),(int)(y+0.5*v),color.get_vector_at(X,Y)._data,opacity,pattern); else draw_line((int)(x-0.5*u),(int)(y-0.5*v),(int)(x+0.5*u),(int)(y+0.5*v),color._data,opacity,pattern); } } return *this; } //! Draw a labeled horizontal axis. /** \param values_x Values along the horizontal axis. \param y Y-coordinate of the horizontal axis in the image instance. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,24,32,57, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const CImg<t>& values_x, const int y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true) { if (is_empty()) return *this; const int yt = (y+3+font_height)<_height?(y+3):(y-2-font_height); const int siz = (int)values_x.size()-1; char txt[32] = { 0 }; CImg<T> label; if (siz<=0) { // Degenerated case. draw_line(0,y,_width-1,y,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,sizeof(txt),"%g",(double)*values_x); label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _xt = (width() - label.width())/2, xt = _xt<3?3:_xt+label.width()>=width()-2?width()-3-label.width():_xt; draw_point(width()/2,y-1,color,opacity).draw_point(width()/2,y+1,color,opacity); if (allow_zero || txt[0]!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case. if (values_x[0]<values_x[siz]) draw_arrow(0,y,_width-1,y,color,opacity,30,5,pattern); else draw_arrow(_width-1,y,0,y,color,opacity,30,5,pattern); cimg_foroff(values_x,x) { cimg_snprintf(txt,sizeof(txt),"%g",(double)values_x(x)); label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int xi = (int)(x*(_width-1)/siz), _xt = xi - label.width()/2, xt = _xt<3?3:_xt+label.width()>=width()-2?width()-3-label.width():_xt; draw_point(xi,y-1,color,opacity).draw_point(xi,y+1,color,opacity); if (allow_zero || txt[0]!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw a labeled vertical axis. /** \param x X-coordinate of the vertical axis in the image instance. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern Drawing pattern. \param font_height Height of the labels (exact match for 13,24,32,57, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename t, typename tc> CImg<T>& draw_axis(const int x, const CImg<t>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern=~0U, const unsigned int font_height=13, const bool allow_zero=true) { if (is_empty()) return *this; int siz = (int)values_y.size()-1; char txt[32] = { 0 }; CImg<T> label; if (siz<=0) { // Degenerated case. draw_line(x,0,x,_height-1,color,opacity,pattern); if (!siz) { cimg_snprintf(txt,sizeof(txt),"%g",(double)*values_y); label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int _yt = (height() - label.height())/2, yt = _yt<0?0:_yt+label.height()>=height()?height()-1-label.height():_yt, _xt = x - 2 - label.width(), xt = _xt>=0?_xt:x+3; draw_point(x-1,height()/2,color,opacity).draw_point(x+1,height()/2,color,opacity); if (allow_zero || txt[0]!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } else { // Regular case. if (values_y[0]<values_y[siz]) draw_arrow(x,0,x,_height-1,color,opacity,30,5,pattern); else draw_arrow(x,_height-1,x,0,color,opacity,30,5,pattern); cimg_foroff(values_y,y) { cimg_snprintf(txt,sizeof(txt),"%g",(double)values_y(y)); label.assign().draw_text(0,0,txt,color,(tc*)0,opacity,font_height); const int yi = (int)(y*(_height-1)/siz), _yt = yi - label.height()/2, yt = _yt<0?0:_yt+label.height()>=height()?height()-1-label.height():_yt, _xt = x - 2 - label.width(), xt = _xt>=0?_xt:x+3; draw_point(x-1,yi,color,opacity).draw_point(x+1,yi,color,opacity); if (allow_zero || txt[0]!='0' || txt[1]!=0) draw_text(xt,yt,txt,color,(tc*)0,opacity,font_height); } } return *this; } //! Draw labeled horizontal and vertical axes. /** \param values_x Values along the X-axis. \param values_y Values along the Y-axis. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for the X-axis. \param pattern_y Drawing pattern for the Y-axis. \param font_height Height of the labels (exact match for 13,24,32,57, interpolated otherwise). \param allow_zero Enable/disable the drawing of label '0' if found. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_axes(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13, const bool allow_zero=true) { if (is_empty()) return *this; const CImg<tx> nvalues_x(values_x._data,values_x.size(),1,1,1,true); const int sizx = (int)values_x.size()-1, wm1 = width()-1; if (sizx>=0) { float ox = (float)*nvalues_x; for (unsigned int x = sizx?1:0; x<_width; ++x) { const float nx = (float)nvalues_x._linear_atX((float)x*sizx/wm1); if (nx*ox<=0) { draw_axis(nx==0?x:x-1,values_y,color,opacity,pattern_y,font_height,allow_zero); break; } ox = nx; } } const CImg<ty> nvalues_y(values_y._data,values_y.size(),1,1,1,true); const int sizy = (int)values_y.size()-1, hm1 = height()-1; if (sizy>0) { float oy = (float)nvalues_y[0]; for (unsigned int y = sizy?1:0; y<_height; ++y) { const float ny = (float)nvalues_y._linear_atX((float)y*sizy/hm1); if (ny*oy<=0) { draw_axis(values_x,ny==0?y:y-1,color,opacity,pattern_x,font_height,allow_zero); break; } oy = ny; } } return *this; } //! Draw labeled horizontal and vertical axes \overloading. template<typename tc> CImg<T>& draw_axes(const float x0, const float x1, const float y0, const float y1, const tc *const color, const float opacity=1, const int subdivisionx=-60, const int subdivisiony=-60, const float precisionx=0, const float precisiony=0, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U, const unsigned int font_height=13) { if (is_empty()) return *this; const bool allow_zero = (x0*x1>0) || (y0*y1>0); const float dx = cimg::abs(x1-x0), dy = cimg::abs(y1-y0), px = dx<=0?1:precisionx==0?(float)std::pow(10.0,(int)std::log10(dx)-2.0):precisionx, py = dy<=0?1:precisiony==0?(float)std::pow(10.0,(int)std::log10(dy)-2.0):precisiony; if (x0!=x1 && y0!=y1) draw_axes(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1).round(px), CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1).round(py), color,opacity,pattern_x,pattern_y,font_height,allow_zero); else if (x0==x1 && y0!=y1) draw_axis((int)x0,CImg<floatT>::sequence(subdivisiony>0?subdivisiony:1-height()/subdivisiony,y0,y1).round(py), color,opacity,pattern_y,font_height); else if (x0!=x1 && y0==y1) draw_axis(CImg<floatT>::sequence(subdivisionx>0?subdivisionx:1-width()/subdivisionx,x0,x1).round(px),(int)y0, color,opacity,pattern_x,font_height); return *this; } //! Draw 2d grid. /** \param values_x X-coordinates of the vertical lines. \param values_y Y-coordinates of the horizontal lines. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param pattern_x Drawing pattern for vertical lines. \param pattern_y Drawing pattern for horizontal lines. **/ template<typename tx, typename ty, typename tc> CImg<T>& draw_grid(const CImg<tx>& values_x, const CImg<ty>& values_y, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; if (values_x) cimg_foroff(values_x,x) { const int xi = (int)values_x[x]; if (xi>=0 && xi<width()) draw_line(xi,0,xi,_height-1,color,opacity,pattern_x); } if (values_y) cimg_foroff(values_y,y) { const int yi = (int)values_y[y]; if (yi>=0 && yi<height()) draw_line(0,yi,_width-1,yi,color,opacity,pattern_y); } return *this; } //! Draw 2d grid \simplification. template<typename tc> CImg<T>& draw_grid(const float delta_x, const float delta_y, const float offsetx, const float offsety, const bool invertx, const bool inverty, const tc *const color, const float opacity=1, const unsigned int pattern_x=~0U, const unsigned int pattern_y=~0U) { if (is_empty()) return *this; CImg<uintT> seqx, seqy; if (delta_x!=0) { const float dx = delta_x>0?delta_x:_width*-delta_x/100; const unsigned int nx = (unsigned int)(_width/dx); seqx = CImg<uintT>::sequence(1+nx,0,(unsigned int)(dx*nx)); if (offsetx) cimg_foroff(seqx,x) seqx(x) = (unsigned int)cimg::mod(seqx(x)+offsetx,(float)_width); if (invertx) cimg_foroff(seqx,x) seqx(x) = _width - 1 - seqx(x); } if (delta_y!=0) { const float dy = delta_y>0?delta_y:_height*-delta_y/100; const unsigned int ny = (unsigned int)(_height/dy); seqy = CImg<uintT>::sequence(1+ny,0,(unsigned int)(dy*ny)); if (offsety) cimg_foroff(seqy,y) seqy(y) = (unsigned int)cimg::mod(seqy(y)+offsety,(float)_height); if (inverty) cimg_foroff(seqy,y) seqy(y) = _height - 1 - seqy(y); } return draw_grid(seqx,seqy,color,opacity,pattern_x,pattern_y); } //! Draw 1d graph. /** \param data Image containing the graph values I = f(x). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. \param plot_type Define the type of the plot: - 0 = No plot. - 1 = Plot using segments. - 2 = Plot using cubic splines. - 3 = Plot with bars. \param vertex_type Define the type of points: - 0 = No points. - 1 = Point. - 2 = Straight cross. - 3 = Diagonal cross. - 4 = Filled circle. - 5 = Outlined circle. - 6 = Square. - 7 = Diamond. \param ymin Lower bound of the y-range. \param ymax Upper bound of the y-range. \param pattern Drawing pattern. \note - if \c ymin==ymax==0, the y-range is computed automatically from the input samples. **/ template<typename t, typename tc> CImg<T>& draw_graph(const CImg<t>& data, const tc *const color, const float opacity=1, const unsigned int plot_type=1, const int vertex_type=1, const double ymin=0, const double ymax=0, const unsigned int pattern=~0U) { if (is_empty() || _height<=1) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_graph(): Specified color is (null).", cimg_instance); // Create shaded colors for displaying bar plots. CImg<tc> color1, color2; if (plot_type==3) { color1.assign(_spectrum); color2.assign(_spectrum); cimg_forC(*this,c) { color1[c] = (tc)cimg::min((float)cimg::type<tc>::max(),color[c]*1.2f); color2[c] = (tc)(color[c]*0.4f); } } // Compute min/max and normalization factors. const unsigned long siz = data.size(), _siz1 = siz - (plot_type!=3?1:0), siz1 = _siz1?_siz1:1; const unsigned int _width1 = _width - (plot_type!=3?1:0), width1 = _width1?_width1:1; double m = ymin, M = ymax; if (ymin==ymax) m = (double)data.max_min(M); if (m==M) { --m; ++M; } const float ca = (float)(M-m)/(_height-1); bool init_hatch = true; // Draw graph edges switch (plot_type%4) { case 1 : { // Segments int oX = 0, oY = (int)((data[0]-m)/ca); if (siz==1) { const int Y = (int)((*data-m)/ca); draw_line(0,Y,width()-1,Y,color,opacity,pattern); } else for (unsigned long off = 1; off<siz; ++off) { const int X = off*_width1/siz1, Y = (int)((data[off]-m)/ca); draw_line(oX,oY,X,Y,color,opacity,pattern,init_hatch); oX = X; oY = Y; init_hatch = false; } } break; case 2 : { // Spline const CImg<t> ndata(data._data,siz,1,1,1,true); int oY = (int)((data[0]-m)/ca); cimg_forX(*this,x) { const int Y = (int)((ndata._cubic_atX((float)x*siz1/width1)-m)/ca); if (x>0) draw_line(x,oY,x+1,Y,color,opacity,pattern,init_hatch); init_hatch = false; oY = Y; } } break; case 3 : { // Bars const int Y0 = (int)(-m/ca); int oX = 0; cimg_foroff(data,off) { const int X = (off+1)*_width/siz-1, Y = (int)((data[off]-m)/ca); draw_rectangle(oX,Y0,X,Y,color,opacity). draw_line(oX,Y,oX,Y0,color2.data(),opacity). draw_line(oX,Y0,X,Y0,Y<=Y0?color2.data():color1.data(),opacity). draw_line(X,Y,X,Y0,color1.data(),opacity). draw_line(oX,Y,X,Y,Y<=Y0?color1.data():color2.data(),opacity); oX = X+1; } } break; default : break; // No edges } // Draw graph points const unsigned int wb2 = plot_type==3?_width1/(2*siz):0; switch (vertex_type%8) { case 1 : { // Point cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_point(X,Y,color,opacity); } } break; case 2 : { // Straight Cross cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_line(X-3,Y,X+3,Y,color,opacity).draw_line(X,Y-3,X,Y+3,color,opacity); } } break; case 3 : { // Diagonal Cross cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_line(X-3,Y-3,X+3,Y+3,color,opacity).draw_line(X-3,Y+3,X+3,Y-3,color,opacity); } } break; case 4 : { // Filled Circle cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity); } } break; case 5 : { // Outlined circle cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_circle(X,Y,3,color,opacity,0U); } } break; case 6 : { // Square cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_rectangle(X-3,Y-3,X+3,Y+3,color,opacity,~0U); } } break; case 7 : { // Diamond cimg_foroff(data,off) { const int X = off*_width1/siz1 + wb2, Y = (int)((data[off]-m)/ca); draw_line(X,Y-4,X+4,Y,color,opacity). draw_line(X+4,Y,X,Y+4,color,opacity). draw_line(X,Y+4,X-4,Y,color,opacity). draw_line(X-4,Y,X,Y-4,color,opacity); } } break; default : break; // No points } return *this; } //! Draw filled 3d region with the flood fill algorithm. /** \param x X-coordinate of the starting point of the region to fill. \param y Y-coordinate of the starting point of the region to fill. \param z Z-coordinate of the starting point of the region to fill. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param[out] region Image that will contain the mask of the filled region mask, as an output. \param sigma Tolerance concerning neighborhood values. \param opacity Opacity of the drawing. \param is_high_connexity Tells if 8-connexity must be used (only for 2d images). \return \c region is initialized with the binary mask of the filled region. **/ template<typename tc, typename t> CImg<T>& draw_fill(const int x, const int y, const int z, const tc *const color, const float opacity, CImg<t>& region, const float sigma=0, const bool is_high_connexity=false) { #define _cimg_draw_fill_test(x,y,z,res) if (region(x,y,z)) res = false; else { \ res = true; \ const T *reference_col = reference_color._data + _spectrum, *ptrs = data(x,y,z) + siz; \ for (unsigned int i = _spectrum; res && i; --i) { ptrs-=whd; res = (cimg::abs(*ptrs - *(--reference_col))<=sigma); } \ region(x,y,z) = (t)(res?1:noregion); \ } #define _cimg_draw_fill_set(x,y,z) { \ const tc *col = color; \ T *ptrd = data(x,y,z); \ if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)*(col++); ptrd+=whd; } \ else cimg_forC(*this,c) { *ptrd = (T)(*(col++)*nopacity + *ptrd*copacity); ptrd+=whd; } \ } #define _cimg_draw_fill_insert(x,y,z) { \ if (posr1>=remaining._height) remaining.resize(3,remaining._height<<1,1,1,0); \ unsigned int *ptrr = remaining.data(0,posr1); \ *(ptrr++) = x; *(ptrr++) = y; *(ptrr++) = z; ++posr1; \ } #define _cimg_draw_fill_test_neighbor(x,y,z,cond) if (cond) { \ const unsigned int tx = x, ty = y, tz = z; \ _cimg_draw_fill_test(tx,ty,tz,res); if (res) _cimg_draw_fill_insert(tx,ty,tz); \ } if (!color) throw CImgArgumentException(_cimg_instance "draw_fill(): Specified color is (null).", cimg_instance); region.assign(_width,_height,_depth,1,(t)0); if (x>=0 && x<width() && y>=0 && y<height() && z>=0 && z<depth()) { const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const unsigned long whd = (unsigned long)_width*_height*_depth, siz = (unsigned long)_spectrum*whd; const unsigned int W1 = _width-1, H1 = _height-1, D1 = _depth-1; const bool is_3d = (_depth>1); const CImg<T> reference_color = get_vector_at(x,y,z); CImg<uintT> remaining(3,512,1,1,0); remaining(0,0) = x; remaining(1,0) = y; remaining(2,0) = z; unsigned int posr0 = 0, posr1 = 1; region(x,y,z) = (t)1; const t noregion = ((t)1==(t)2)?(t)0:(t)(-1); if (is_3d) do { // 3d version of the filling algorithm const unsigned int *pcurr = remaining.data(0,posr0++), xc = *(pcurr++), yc = *(pcurr++), zc = *(pcurr++); if (posr0>=512) { remaining.shift(0,-(int)posr0); posr1-=posr0; posr0 = 0; } bool cont, res; unsigned int nxc = xc; do { // X-backward _cimg_draw_fill_set(nxc,yc,zc); _cimg_draw_fill_test_neighbor(nxc,yc-1,zc,yc!=0); _cimg_draw_fill_test_neighbor(nxc,yc+1,zc,yc<H1); _cimg_draw_fill_test_neighbor(nxc,yc,zc-1,zc!=0); _cimg_draw_fill_test_neighbor(nxc,yc,zc+1,zc<D1); if (nxc) { --nxc; _cimg_draw_fill_test(nxc,yc,zc,cont); } else cont = false; } while (cont); nxc = xc; do { // X-forward if ((++nxc)<=W1) { _cimg_draw_fill_test(nxc,yc,zc,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(nxc,yc,zc); _cimg_draw_fill_test_neighbor(nxc,yc-1,zc,yc!=0); _cimg_draw_fill_test_neighbor(nxc,yc+1,zc,yc<H1); _cimg_draw_fill_test_neighbor(nxc,yc,zc-1,zc!=0); _cimg_draw_fill_test_neighbor(nxc,yc,zc+1,zc<D1); } } while (cont); unsigned int nyc = yc; do { // Y-backward if (nyc) { --nyc; _cimg_draw_fill_test(xc,nyc,zc,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,nyc,zc); _cimg_draw_fill_test_neighbor(xc-1,nyc,zc,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,nyc,zc,xc<W1); _cimg_draw_fill_test_neighbor(xc,nyc,zc-1,zc!=0); _cimg_draw_fill_test_neighbor(xc,nyc,zc+1,zc<D1); } } while (cont); nyc = yc; do { // Y-forward if ((++nyc)<=H1) { _cimg_draw_fill_test(xc,nyc,zc,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,nyc,zc); _cimg_draw_fill_test_neighbor(xc-1,nyc,zc,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,nyc,zc,xc<W1); _cimg_draw_fill_test_neighbor(xc,nyc,zc-1,zc!=0); _cimg_draw_fill_test_neighbor(xc,nyc,zc+1,zc<D1); } } while (cont); unsigned int nzc = zc; do { // Z-backward if (nzc) { --nzc; _cimg_draw_fill_test(xc,yc,nzc,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,yc,nzc); _cimg_draw_fill_test_neighbor(xc-1,yc,nzc,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,yc,nzc,xc<W1); _cimg_draw_fill_test_neighbor(xc,yc-1,nzc,yc!=0); _cimg_draw_fill_test_neighbor(xc,yc+1,nzc,yc<H1); } } while (cont); nzc = zc; do { // Z-forward if ((++nzc)<=D1) { _cimg_draw_fill_test(xc,yc,nzc,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,nyc,zc); _cimg_draw_fill_test_neighbor(xc-1,yc,nzc,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,yc,nzc,xc<W1); _cimg_draw_fill_test_neighbor(xc,yc-1,nzc,yc!=0); _cimg_draw_fill_test_neighbor(xc,yc+1,nzc,yc<H1); } } while (cont); } while (posr1>posr0); else do { // 2d version of the filling algorithm const unsigned int *pcurr = remaining.data(0,posr0++), xc = *(pcurr++), yc = *(pcurr++); if (posr0>=512) { remaining.shift(0,-(int)posr0); posr1-=posr0; posr0 = 0; } bool cont, res; unsigned int nxc = xc; do { // X-backward _cimg_draw_fill_set(nxc,yc,0); _cimg_draw_fill_test_neighbor(nxc,yc-1,0,yc!=0); _cimg_draw_fill_test_neighbor(nxc,yc+1,0,yc<H1); if (is_high_connexity) { _cimg_draw_fill_test_neighbor(nxc-1,yc-1,0,(nxc!=0 && yc!=0)); _cimg_draw_fill_test_neighbor(nxc+1,yc-1,0,(nxc<W1 && yc!=0)); _cimg_draw_fill_test_neighbor(nxc-1,yc+1,0,(nxc!=0 && yc<H1)); _cimg_draw_fill_test_neighbor(nxc+1,yc+1,0,(nxc<W1 && yc<H1)); } if (nxc) { --nxc; _cimg_draw_fill_test(nxc,yc,0,cont); } else cont = false; } while (cont); nxc = xc; do { // X-forward if ((++nxc)<=W1) { _cimg_draw_fill_test(nxc,yc,0,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(nxc,yc,0); _cimg_draw_fill_test_neighbor(nxc,yc-1,0,yc!=0); _cimg_draw_fill_test_neighbor(nxc,yc+1,0,yc<H1); if (is_high_connexity) { _cimg_draw_fill_test_neighbor(nxc-1,yc-1,0,(nxc!=0 && yc!=0)); _cimg_draw_fill_test_neighbor(nxc+1,yc-1,0,(nxc<W1 && yc!=0)); _cimg_draw_fill_test_neighbor(nxc-1,yc+1,0,(nxc!=0 && yc<H1)); _cimg_draw_fill_test_neighbor(nxc+1,yc+1,0,(nxc<W1 && yc<H1)); } } } while (cont); unsigned int nyc = yc; do { // Y-backward if (nyc) { --nyc; _cimg_draw_fill_test(xc,nyc,0,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,nyc,0); _cimg_draw_fill_test_neighbor(xc-1,nyc,0,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,nyc,0,xc<W1); if (is_high_connexity) { _cimg_draw_fill_test_neighbor(xc-1,nyc-1,0,(xc!=0 && nyc!=0)); _cimg_draw_fill_test_neighbor(xc+1,nyc-1,0,(xc<W1 && nyc!=0)); _cimg_draw_fill_test_neighbor(xc-1,nyc+1,0,(xc!=0 && nyc<H1)); _cimg_draw_fill_test_neighbor(xc+1,nyc+1,0,(xc<W1 && nyc<H1)); } } } while (cont); nyc = yc; do { // Y-forward if ((++nyc)<=H1) { _cimg_draw_fill_test(xc,nyc,0,cont); } else cont = false; if (cont) { _cimg_draw_fill_set(xc,nyc,0); _cimg_draw_fill_test_neighbor(xc-1,nyc,0,xc!=0); _cimg_draw_fill_test_neighbor(xc+1,nyc,0,xc<W1); if (is_high_connexity) { _cimg_draw_fill_test_neighbor(xc-1,nyc-1,0,(xc!=0 && nyc!=0)); _cimg_draw_fill_test_neighbor(xc+1,nyc-1,0,(xc<W1 && nyc!=0)); _cimg_draw_fill_test_neighbor(xc-1,nyc+1,0,(xc!=0 && nyc<H1)); _cimg_draw_fill_test_neighbor(xc+1,nyc+1,0,(xc<W1 && nyc<H1)); } } } while (cont); } while (posr1>posr0); if (noregion) cimg_for(region,ptrd,t) if (*ptrd==noregion) *ptrd = (t)0; } return *this; } //! Draw filled 3d region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x, const int y, const int z, const tc *const color, const float opacity=1, const float sigma=0, const bool is_high_connexity=false) { CImg<boolT> tmp; return draw_fill(x,y,z,color,opacity,tmp,sigma,is_high_connexity); } //! Draw filled 2d region with the flood fill algorithm \simplification. template<typename tc> CImg<T>& draw_fill(const int x, const int y, const tc *const color, const float opacity=1, const float sigma=0, const bool is_high_connexity=false) { CImg<boolT> tmp; return draw_fill(x,y,0,color,opacity,tmp,sigma,is_high_connexity); } //! Draw a random plasma texture. /** \param alpha Alpha-parameter. \param beta Beta-parameter. \param scale Scale-parameter. \note Use the mid-point algorithm to render. **/ CImg<T>& draw_plasma(const float alpha=1, const float beta=0, const unsigned int scale=8) { if (is_empty()) return *this; const int w = width(), h = height(); const Tfloat m = (Tfloat)cimg::type<T>::min(), M = (Tfloat)cimg::type<T>::max(); cimg_forZC(*this,z,c) { CImg<T> ref = get_shared_slice(z,c); for (int d=1<<cimg::min(scale,31U); d>1; d>>=1) { const int d2 = d>>1; const float r = alpha*d + beta; for (int y0=0; y0<h; y0+=d) for (int x0=0; x0<w; x0+=d) { const int x1 = (x0 + d)%w, y1 = (y0 + d)%h, xc = (x0 + d2)%w, yc = (y0 + d2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(x0,y0) + ref(x0,y1) + ref(x0,y1) + ref(x1,y1)) + r*cimg::crand()); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y=-d2; y<h; y+=d) for (int x0=0; x0<w; x0+=d) { const int y0 = cimg::mod(y,h), x1 = (x0 + d)%w, y1 = (y + d)%h, xc = (x0 + d2)%w, yc = (y + d2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::crand()); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y0=0; y0<h; y0+=d) for (int x=-d2; x<w; x+=d) { const int x0 = cimg::mod(x,w), x1 = (x + d)%w, y1 = (y0 + d)%h, xc = (x + d2)%w, yc = (y0 + d2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::crand()); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } for (int y=-d2; y<h; y+=d) for (int x=-d2; x<w; x+=d) { const int x0 = cimg::mod(x,w), y0 = cimg::mod(y,h), x1 = (x + d)%w, y1 = (y + d)%h, xc = (x + d2)%w, yc = (y + d2)%h; const Tfloat val = (Tfloat)(0.25f*(ref(xc,y0) + ref(x0,yc) + ref(xc,y1) + ref(x1,yc)) + r*cimg::crand()); ref(xc,yc) = (T)(val<m?m:val>M?M:val); } } } return *this; } //! Draw a quadratic Mandelbrot or Julia 2d fractal. /** \param x0 X-coordinate of the upper-left pixel. \param y0 Y-coordinate of the upper-left pixel. \param x1 X-coordinate of the lower-right pixel. \param y1 Y-coordinate of the lower-right pixel. \param colormap Colormap. \param opacity Drawing opacity. \param z0r Real part of the upper-left fractal vertex. \param z0i Imaginary part of the upper-left fractal vertex. \param z1r Real part of the lower-right fractal vertex. \param z1i Imaginary part of the lower-right fractal vertex. \param iteration_max Maximum number of iterations for each estimated point. \param is_normalized_iteration Tells if iterations are normalized. \param is_julia_set Tells if the Mandelbrot or Julia set is rendered. \param param_r Real part of the Julia set parameter. \param param_i Imaginary part of the Julia set parameter. \note Fractal rendering is done by the Escape Time Algorithm. **/ template<typename tc> CImg<T>& draw_mandelbrot(const int x0, const int y0, const int x1, const int y1, const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { if (is_empty()) return *this; CImg<tc> palette; if (colormap) palette.assign(colormap._data,colormap.size()/colormap._spectrum,1,1,colormap._spectrum,true); if (palette && palette._spectrum!=_spectrum) throw CImgArgumentException(_cimg_instance "draw_mandelbrot(): Instance and specified colormap (%u,%u,%u,%u,%p) have incompatible dimensions.", cimg_instance, colormap._width,colormap._height,colormap._depth,colormap._spectrum,colormap._data); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0), ln2 = (float)std::log(2.0); unsigned int iteration = 0; cimg_for_inXY(*this,x0,y0,x1,y1,p,q) { const double x = z0r + p*(z1r-z0r)/_width, y = z0i + q*(z1i-z0i)/_height; double zr, zi, cr, ci; if (is_julia_set) { zr = x; zi = y; cr = param_r; ci = param_i; } else { zr = param_r; zi = param_i; cr = x; ci = y; } for (iteration=1; zr*zr + zi*zi<=4 && iteration<=iteration_max; ++iteration) { const double temp = zr*zr - zi*zi + cr; zi = 2*zr*zi + ci; zr = temp; } if (iteration>iteration_max) { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette(0,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(0,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)0; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)((*this)(p,q,0,c)*copacity); } } else if (is_normalized_iteration) { const float normz = (float)cimg::abs(zr*zr+zi*zi), niteration = (float)(iteration + 1 - std::log(std::log(normz))/ln2); if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._linear_atX(niteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette._linear_atX(niteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)niteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(niteration*nopacity + (*this)(p,q,0,c)*copacity); } } else { if (palette) { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)palette._atX(iteration,c); else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(palette(iteration,c)*nopacity + (*this)(p,q,0,c)*copacity); } else { if (opacity>=1) cimg_forC(*this,c) (*this)(p,q,0,c) = (T)iteration; else cimg_forC(*this,c) (*this)(p,q,0,c) = (T)(iteration*nopacity + (*this)(p,q,0,c)*copacity); } } } return *this; } //! Draw a quadratic Mandelbrot or Julia 2d fractal \overloading. template<typename tc> CImg<T>& draw_mandelbrot(const CImg<tc>& colormap, const float opacity=1, const double z0r=-2, const double z0i=-2, const double z1r=2, const double z1i=2, const unsigned int iteration_max=255, const bool is_normalized_iteration=false, const bool is_julia_set=false, const double param_r=0, const double param_i=0) { return draw_mandelbrot(0,0,_width-1,_height-1,colormap,opacity, z0r,z0i,z1r,z1i,iteration_max,is_normalized_iteration,is_julia_set,param_r,param_i); } //! Draw a 1d gaussian function. /** \param xc X-coordinate of the gaussian center. \param sigma Standard variation of the gaussian distribution. \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename tc> CImg<T>& draw_gaussian(const float xc, const float sigma, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); const float sigma2 = 2*sigma*sigma, nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const unsigned long whd = (unsigned long)_width*_height*_depth; const tc *col = color; cimg_forX(*this,x) { const float dx = (x - xc), val = (float)std::exp(-dx*dx/sigma2); T *ptrd = data(x,0,0,0); if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 2d gaussian function. /** \param xc X-coordinate of the gaussian center. \param yc Y-coordinate of the gaussian center. \param tensor Covariance matrix (must be 2x2). \param color Pointer to \c spectrum() consecutive values, defining the drawing color. \param opacity Drawing opacity. **/ template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; if (tensor._width!=2 || tensor._height!=2 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 2x2 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); if (!color) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified color is (null).", cimg_instance); typedef typename CImg<t>::Tfloat tfloat; const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/(-2.0); const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = invT2(1,1); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const unsigned long whd = (unsigned long)_width*_height*_depth; const tc *col = color; float dy = -yc; cimg_forY(*this,y) { float dx = -xc; cimg_forX(*this,x) { const float val = (float)std::exp(a*dx*dx + b*dx*dy + c*dy*dy); T *ptrd = data(x,y,0,0); if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; ++dx; } ++dy; } return *this; } //! Draw a 2d gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const int xc, const int yc, const float r1, const float r2, const float ru, const float rv, const tc *const color, const float opacity=1) { const double a = r1*ru*ru + r2*rv*rv, b = (r1-r2)*ru*rv, c = r1*rv*rv + r2*ru*ru; const CImg<Tfloat> tensor(2,2,1,1, a,b,b,c); return draw_gaussian(xc,yc,tensor,color,opacity); } //! Draw a 2d gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,CImg<floatT>::diagonal(sigma,sigma),color,opacity); } //! Draw a 3d gaussian function \overloading. template<typename t, typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const CImg<t>& tensor, const tc *const color, const float opacity=1) { if (is_empty()) return *this; typedef typename CImg<t>::Tfloat tfloat; if (tensor._width!=3 || tensor._height!=3 || tensor._depth!=1 || tensor._spectrum!=1) throw CImgArgumentException(_cimg_instance "draw_gaussian(): Specified tensor (%u,%u,%u,%u,%p) is not a 3x3 matrix.", cimg_instance, tensor._width,tensor._height,tensor._depth,tensor._spectrum,tensor._data); const CImg<tfloat> invT = tensor.get_invert(), invT2 = (invT*invT)/(-2.0); const tfloat a = invT2(0,0), b = 2*invT2(1,0), c = 2*invT2(2,0), d = invT2(1,1), e = 2*invT2(2,1), f = invT2(2,2); const float nopacity = cimg::abs(opacity), copacity = 1 - cimg::max(opacity,0); const unsigned long whd = (unsigned long)_width*_height*_depth; const tc *col = color; cimg_forXYZ(*this,x,y,z) { const float dx = (x - xc), dy = (y - yc), dz = (z - zc), val = (float)std::exp(a*dx*dx + b*dx*dy + c*dx*dz + d*dy*dy + e*dy*dz + f*dz*dz); T *ptrd = data(x,y,z,0); if (opacity>=1) cimg_forC(*this,c) { *ptrd = (T)(val*(*col++)); ptrd+=whd; } else cimg_forC(*this,c) { *ptrd = (T)(nopacity*val*(*col++) + *ptrd*copacity); ptrd+=whd; } col-=_spectrum; } return *this; } //! Draw a 3d gaussian function \overloading. template<typename tc> CImg<T>& draw_gaussian(const float xc, const float yc, const float zc, const float sigma, const tc *const color, const float opacity=1) { return draw_gaussian(xc,yc,zc,CImg<floatT>::diagonal(sigma,sigma,sigma),color,opacity); } //! Draw a 3d object. /** \param x0 X-coordinate of the 3d object position \param y0 Y-coordinate of the 3d object position \param z0 Z-coordinate of the 3d object position \param vertices Image Nx3 describing 3d point coordinates \param primitives List of P primitives \param colors List of P color (or textures) \param opacities Image or list of P opacities \param render_type d Render type (0=Points, 1=Lines, 2=Faces (no light), 3=Faces (flat), 4=Faces(Gouraud) \param is_double_sided Tells if object faces have two sides or are oriented. \param focale length of the focale (0 for parallel projection) \param lightx X-coordinate of the light \param lighty Y-coordinate of the light \param lightz Z-coordinate of the light \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object **/ template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,CImg<floatT>::empty()); } //! Draw a 3d object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImg<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,1); } #endif //! Draw a 3d object \simplification. template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,opacities,render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,CImg<floatT>::empty()); } //! Draw a 3d object \simplification. template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return _draw_object3d(0,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,1); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type,is_double_sided,focale,lightx,lighty,lightz, specular_lightness,specular_shininess,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const CImgList<to>& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities, render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,1); } #endif //! Draw a 3d object \simplification. template<typename tp, typename tf, typename tc> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::empty(), render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,CImg<floatT>::empty()); } //! Draw a 3d object \simplification. template<typename tp, typename tf, typename tc, typename tz> CImg<T>& draw_object3d(const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::empty(), render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,zbuffer); } #ifdef cimg_use_board template<typename tp, typename tf, typename tc, typename to> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type=4, const bool is_double_sided=false, const float focale=500, const float lightx=0, const float lighty=0, const float lightz=-5e8, const float specular_lightness=0.2f, const float specular_shininess=0.1f) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::empty(), render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,CImg<floatT>::empty()); } template<typename tp, typename tf, typename tc, typename to, typename tz> CImg<T>& draw_object3d(LibBoard::Board& board, const float x0, const float y0, const float z0, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, CImg<tz>& zbuffer) { return draw_object3d(x0,y0,z0,vertices,primitives,colors,CImg<floatT>::empty(), render_type,is_double_sided,focale,lightx,lighty,lightz,specular_lightness,specular_shininess,zbuffer); } #endif template<typename t> unsigned int ___draw_object3d(const CImgList<t>& opacities, const unsigned int n_primitive) const { return (n_primitive>=opacities._width || opacities[n_primitive].is_empty())?1:opacities[n_primitive].size(); } template<typename t> unsigned int ___draw_object3d(const CImg<t>&, const unsigned int) const { return 1; } template<typename tc, typename to> void __draw_object3d(const unsigned int n_primitive, const CImgList<to>& opacities, const CImg<tc>& color, const int nx0, const int ny0, const CImg<T>& sprite, const float opac, const float factor) { if (n_primitive<opacities._width && opacities[n_primitive]) { const CImg<to>& opacity = opacities[n_primitive]; if (opacity.size()==1) draw_image(nx0,ny0,sprite,opac); else if (opacity.is_sameXY(sprite)) draw_image(nx0,ny0,sprite,opacity); else if (opacity.is_sameXY(color)) draw_image(nx0,ny0,sprite,opacity.get_resize(sprite._width,sprite._height)); else { const unsigned int W = cimg::max(sprite._width,(unsigned int)(opacity._width*factor)), H = cimg::max(sprite._height,(unsigned int)(opacity._height*factor)); const CImg<T> __sprite = (sprite._width==W && sprite._height==H)?CImg<T>():sprite.get_resize(W,H), &_sprite = __sprite?__sprite:sprite; const CImg<to> __opacity = (opacity._width==W && opacity._height==H)?CImg<to>():opacity.get_resize(W,H), &_opacity = __opacity?__opacity:opacity; draw_image(nx0,ny0,_sprite,_opacity); } } else draw_image(nx0,ny0,sprite,opac); } template<typename tc, typename to> void __draw_object3d(const unsigned int, const CImg<to>&, const CImg<tc>&, const int nx0, const int ny0, const CImg<T>& sprite, const float opac, const float) { draw_image(nx0,ny0,sprite,opac); } template<typename tz, typename tp, typename tf, typename tc, typename to> CImg<T>& _draw_object3d(void *const pboard, CImg<tz>& zbuffer, const float X, const float Y, const float Z, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const unsigned int render_type, const bool is_double_sided, const float focale, const float lightx, const float lighty, const float lightz, const float specular_lightness, const float specular_shininess, const float sprite_scale) { typedef typename cimg::superset2<tp,tz,float>::type tpfloat; if (is_empty() || !vertices || !primitives) return *this; char error_message[1024] = { 0 }; if (!vertices.is_object3d(primitives,colors,opacities,false,error_message)) throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid specified 3d object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message); #ifndef cimg_use_board if (pboard) return *this; #endif const float nspec = 1 - (specular_lightness<0.0f?0.0f:(specular_lightness>1.0f?1.0f:specular_lightness)), nspec2 = 1 + (specular_shininess<0.0f?0.0f:specular_shininess), nsl1 = (nspec2 - 1)/cimg::sqr(nspec - 1), nsl2 = 1 - 2*nsl1*nspec, nsl3 = nspec2 - nsl1 - nsl2; // Create light texture for phong-like rendering. CImg<floatT> light_texture; if (render_type==5) { if (colors._width>primitives._width) { static CImg<floatT> default_light_texture; static const tc *lptr = 0; static tc ref_values[64] = { 0 }; const CImg<tc>& img = colors.back(); bool is_same_texture = (lptr==img._data); if (is_same_texture) for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) if (ref_values[r++]!=img(i*img._width/9,j*img._height/9,0,(i+j)%img._spectrum)) { is_same_texture = false; break; } if (!is_same_texture || default_light_texture._spectrum<_spectrum) { (default_light_texture.assign(img,false)/=255).resize(-100,-100,1,_spectrum); lptr = colors.back().data(); for (unsigned int r = 0, j = 0; j<8; ++j) for (unsigned int i = 0; i<8; ++i) ref_values[r++] = img(i*img._width/9,j*img._height/9,0,(i+j)%img._spectrum); } light_texture.assign(default_light_texture,true); } else { static CImg<floatT> default_light_texture; static float olightx = 0, olighty = 0, olightz = 0, ospecular_shininess = 0; if (!default_light_texture || lightx!=olightx || lighty!=olighty || lightz!=olightz || specular_shininess!=ospecular_shininess || default_light_texture._spectrum<_spectrum) { default_light_texture.assign(512,512); const float dlx = lightx - X, dly = lighty - Y, dlz = lightz - Z, nl = (float)std::sqrt(dlx*dlx + dly*dly + dlz*dlz), nlx = default_light_texture._width/2*(1 + dlx/nl), nly = default_light_texture._height/2*(1 + dly/nl), white[] = { 1 }; default_light_texture.draw_gaussian(nlx,nly,default_light_texture._width/3.0f,white); cimg_forXY(default_light_texture,x,y) { const float factor = default_light_texture(x,y); if (factor>nspec) default_light_texture(x,y) = cimg::min(2,nsl1*factor*factor + nsl2*factor + nsl3); } default_light_texture.resize(-100,-100,1,_spectrum); olightx = lightx; olighty = lighty; olightz = lightz; ospecular_shininess = specular_shininess; } light_texture.assign(default_light_texture,true); } } // Compute 3d to 2d projection. CImg<tpfloat> projections(vertices._width,2); tpfloat parallzmin = cimg::type<tpfloat>::max(); const float absfocale = focale?cimg::abs(focale):0, _focale = absfocale?absfocale:(1-parallzmin); if (absfocale) cimg_forX(projections,l) { // Perspective projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); const tpfloat projectedz = z + Z + absfocale; projections(l,1) = Y + absfocale*y/projectedz; projections(l,0) = X + absfocale*x/projectedz; } else cimg_forX(projections,l) { // Parallel projection const tpfloat x = (tpfloat)vertices(l,0), y = (tpfloat)vertices(l,1), z = (tpfloat)vertices(l,2); if (z<parallzmin) parallzmin = z; projections(l,1) = Y + y; projections(l,0) = X + x; } // Compute and sort visible primitives. CImg<uintT> visibles(primitives._width); CImg<tpfloat> zrange(primitives._width); unsigned int nb_visibles = 0; const tpfloat zmin = absfocale?(tpfloat)(1.5f - absfocale):cimg::type<tpfloat>::min(); cimglist_for(primitives,l) { const CImg<tf>& primitive = primitives[l]; switch (primitive.size()) { case 1 : { // Point const unsigned int i0 = (unsigned int)primitive(0); const tpfloat z0 = Z + vertices(i0,2); if (z0>zmin) { visibles(nb_visibles) = (unsigned int)l; zrange(nb_visibles++) = z0; } } break; case 5 : { // Sphere const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat Xc = 0.5f*((float)vertices(i0,0) + (float)vertices(i1,0)), Yc = 0.5f*((float)vertices(i0,1) + (float)vertices(i1,1)), Zc = 0.5f*((float)vertices(i0,2) + (float)vertices(i1,2)), _zc = Z + Zc, zc = _zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*std::sqrt(cimg::sqr(vertices(i1,0) - vertices(i0,0)) + cimg::sqr(vertices(i1,1) - vertices(i0,1)) + cimg::sqr(vertices(i1,2) - vertices(i0,2)))*(absfocale?absfocale/zc:1), xm = xc - radius, ym = yc - radius, xM = xc + radius, yM = yc + radius; if (xM>=0 && xm<_width && yM>=0 && ym<_height && _zc>zmin) { visibles(nb_visibles) = (unsigned int)l; zrange(nb_visibles++) = _zc; } } break; case 2 : // Segment case 6 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin) { visibles(nb_visibles) = (unsigned int)l; zrange(nb_visibles++) = (z0 + z1)/2; } } break; case 3 : // Triangle case 9 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const tpfloat d = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0); if (is_double_sided || d<0) { visibles(nb_visibles) = (unsigned int)l; zrange(nb_visibles++) = (z0 + z1 + z2)/3; } } } break; case 4 : // Rectangle case 12 : { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = (unsigned int)primitive(3); const tpfloat x0 = projections(i0,0), y0 = projections(i0,1), z0 = Z + vertices(i0,2), x1 = projections(i1,0), y1 = projections(i1,1), z1 = Z + vertices(i1,2), x2 = projections(i2,0), y2 = projections(i2,1), z2 = Z + vertices(i2,2), x3 = projections(i3,0), y3 = projections(i3,1), z3 = Z + vertices(i3,2); tpfloat xm, xM, ym, yM; if (x0<x1) { xm = x0; xM = x1; } else { xm = x1; xM = x0; } if (x2<xm) xm = x2; if (x2>xM) xM = x2; if (x3<xm) xm = x3; if (x3>xM) xM = x3; if (y0<y1) { ym = y0; yM = y1; } else { ym = y1; yM = y0; } if (y2<ym) ym = y2; if (y2>yM) yM = y2; if (y3<ym) ym = y3; if (y3>yM) yM = y3; if (xM>=0 && xm<_width && yM>=0 && ym<_height && z0>zmin && z1>zmin && z2>zmin) { const float d = (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0); if (is_double_sided || d<0) { visibles(nb_visibles) = (unsigned int)l; zrange(nb_visibles++) = (z0 + z1 + z2 + z3)/4; } } } break; default : throw CImgArgumentException(_cimg_instance "draw_object3d(): Invalid primitive[%u] with size %u " "(should have size 1,2,3,4,5,6,9 or 12).", cimg_instance, l,primitive.size()); } } if (nb_visibles<=0) return *this; CImg<uintT> permutations; CImg<tpfloat>(zrange._data,nb_visibles,1,1,1,true).sort(permutations,false); // Compute light properties CImg<floatT> lightprops; switch (render_type) { case 3 : { // Flat Shading lightprops.assign(nb_visibles); cimg_forX(lightprops,l) { const CImg<tf>& primitive = primitives(visibles(permutations(l))); const unsigned int psize = primitive.size(); if (psize==3 || psize==4 || psize==9 || psize==12) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2); const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nx = dy1*dz2 - dz1*dy2, ny = dz1*dx2 - dx1*dz2, nz = dx1*dy2 - dy1*dx2, norm = (tpfloat)std::sqrt(1e-5f + nx*nx + ny*ny + nz*nz), lx = X + (x0 + x1 + x2)/3 - lightx, ly = Y + (y0 + y1 + y2)/3 - lighty, lz = Z + (z0 + z1 + z2)/3 - lightz, nl = (tpfloat)std::sqrt(1e-5f + lx*lx + ly*ly + lz*lz), factor = cimg::max(cimg::abs(-lx*nx-ly*ny-lz*nz)/(norm*nl),0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } else lightprops[l] = 1; } } break; case 4 : // Gouraud Shading case 5 : { // Phong-Shading CImg<tpfloat> vertices_normals(vertices._width,3,1,1,0); for (unsigned int l = 0; l<nb_visibles; ++l) { const CImg<tf>& primitive = primitives[visibles(l)]; const unsigned int psize = primitive.size(); const bool triangle_flag = (psize==3) || (psize==9), rectangle_flag = (psize==4) || (psize==12); if (triangle_flag || rectangle_flag) { const unsigned int i0 = (unsigned int)primitive(0), i1 = (unsigned int)primitive(1), i2 = (unsigned int)primitive(2), i3 = rectangle_flag?(unsigned int)primitive(3):0; const tpfloat x0 = (tpfloat)vertices(i0,0), y0 = (tpfloat)vertices(i0,1), z0 = (tpfloat)vertices(i0,2), x1 = (tpfloat)vertices(i1,0), y1 = (tpfloat)vertices(i1,1), z1 = (tpfloat)vertices(i1,2), x2 = (tpfloat)vertices(i2,0), y2 = (tpfloat)vertices(i2,1), z2 = (tpfloat)vertices(i2,2), dx1 = x1 - x0, dy1 = y1 - y0, dz1 = z1 - z0, dx2 = x2 - x0, dy2 = y2 - y0, dz2 = z2 - z0, nnx = dy1*dz2 - dz1*dy2, nny = dz1*dx2 - dx1*dz2, nnz = dx1*dy2 - dy1*dx2, norm = (tpfloat)(1e-5f + std::sqrt(nnx*nnx + nny*nny + nnz*nnz)), nx = nnx/norm, ny = nny/norm, nz = nnz/norm; vertices_normals(i0,0)+=nx; vertices_normals(i0,1)+=ny; vertices_normals(i0,2)+=nz; vertices_normals(i1,0)+=nx; vertices_normals(i1,1)+=ny; vertices_normals(i1,2)+=nz; vertices_normals(i2,0)+=nx; vertices_normals(i2,1)+=ny; vertices_normals(i2,2)+=nz; if (rectangle_flag) { vertices_normals(i3,0)+=nx; vertices_normals(i3,1)+=ny; vertices_normals(i3,2)+=nz; } } } if (is_double_sided) cimg_forX(vertices_normals,p) if (vertices_normals(p,2)>0) { vertices_normals(p,0) = -vertices_normals(p,0); vertices_normals(p,1) = -vertices_normals(p,1); vertices_normals(p,2) = -vertices_normals(p,2); } if (render_type==4) { lightprops.assign(vertices._width); cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = (tpfloat)std::sqrt(1e-5f + nx*nx + ny*ny + nz*nz), lx = X + vertices(l,0) - lightx, ly = Y + vertices(l,1) - lighty, lz = Z + vertices(l,2) - lightz, nl = (tpfloat)std::sqrt(1e-5f + lx*lx + ly*ly + lz*lz), factor = cimg::max((-lx*nx-ly*ny-lz*nz)/(norm*nl),0); lightprops[l] = factor<=nspec?factor:(nsl1*factor*factor + nsl2*factor + nsl3); } } else { const unsigned int lw2 = light_texture._width/2 - 1, lh2 = light_texture._height/2 - 1; lightprops.assign(vertices._width,2); cimg_forX(lightprops,l) { const tpfloat nx = vertices_normals(l,0), ny = vertices_normals(l,1), nz = vertices_normals(l,2), norm = (tpfloat)std::sqrt(1e-5f + nx*nx + ny*ny + nz*nz), nnx = nx/norm, nny = ny/norm; lightprops(l,0) = lw2*(1 + nnx); lightprops(l,1) = lh2*(1 + nny); } } } break; } // Draw visible primitives const CImg<tc> default_color(1,_spectrum,1,1,(tc)200); for (unsigned int l = 0; l<nb_visibles; ++l) { const unsigned int n_primitive = visibles(permutations(l)); const CImg<tf>& primitive = primitives[n_primitive]; const CImg<tc> &__color = n_primitive<colors._width?colors[n_primitive]:CImg<tc>(), _color = (__color && __color.size()!=_spectrum && __color._spectrum<_spectrum)?colors[n_primitive].get_resize(-100,-100,-100,_spectrum,0):CImg<tc>(), &color = _color?_color:(__color?__color:default_color); const tc *const pcolor = color._data; const unsigned int siz_opac = ___draw_object3d(opacities,n_primitive); const float opac = (n_primitive>=opacities._width || !siz_opac)?1.0f:opacities(n_primitive,0); #ifdef cimg_use_board LibBoard::Board &board = *(LibBoard::Board*)pboard; #endif switch (primitive.size()) { case 1 : { // Colored point or sprite const unsigned int n0 = (unsigned int)primitive[0]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1); if (color.size()==_spectrum && siz_opac==1) { // Colored point. draw_point(x0,y0,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.fillCircle((float)x0,height()-(float)y0,0); } #endif } else { // Colored sprite. if (!__color) throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for sprite primitive [%u].", cimg_instance,n_primitive); const tpfloat z = Z + vertices(n0,2); const float factor = focale<0?1:sprite_scale*(absfocale?absfocale/(z + absfocale):1); const unsigned int _sw = (unsigned int)(color._width*factor), _sh = (unsigned int)(color._height*factor), sw = _sw?_sw:1, sh = _sh?_sh:1; const int nx0 = x0 - (int)sw/2, ny0 = y0 - (int)sh/2; if (sw<=3*_width/2 && sh<=3*_height/2 && (nx0+(int)sw/2>=0 || nx0-(int)sw/2<width() || ny0+(int)sh/2>=0 || ny0-(int)sh/2<height())) { const CImg<tc> _sprite = (sw!=color._width || sh!=color._height)?color.get_resize(sw,sh,1,-100,render_type<=3?1:3):CImg<tc>(), &sprite = _sprite?_sprite:color; __draw_object3d(n_primitive,opacities,color,nx0,ny0,sprite,opac,factor); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128); board.setFillColor(LibBoard::Color::None); board.drawRectangle((float)nx0,height()-(float)ny0,sw,sh); } #endif } } } break; case 2 : { // Colored line const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opac); else draw_line(x0,y0,x1,y1,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,x1,height()-(float)y1); } #endif } else { draw_point(x0,y0,pcolor,opac).draw_point(x1,y1,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); } #endif } } break; case 5 : { // Colored sphere const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1]; const float Xc = 0.5f*((float)vertices(n0,0) + (float)vertices(n1,0)), Yc = 0.5f*((float)vertices(n0,1) + (float)vertices(n1,1)), Zc = 0.5f*((float)vertices(n0,2) + (float)vertices(n1,2)), zc = Z + Zc + _focale, xc = X + Xc*(absfocale?absfocale/zc:1), yc = Y + Yc*(absfocale?absfocale/zc:1), radius = 0.5f*std::sqrt(cimg::sqr(vertices(n1,0) - vertices(n0,0)) + cimg::sqr(vertices(n1,1) - vertices(n0,1)) + cimg::sqr(vertices(n1,2) - vertices(n0,2)))*(absfocale?absfocale/zc:1); switch (render_type) { case 0 : draw_point((int)xc,(int)yc,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.fillCircle(xc,height()-yc,0); } #endif break; case 1 : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opac,~0U); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.setFillColor(LibBoard::Color::None); board.drawCircle(xc,height()-yc,radius); } #endif break; default : draw_circle((int)xc,(int)yc,(int)radius,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.fillCircle(xc,height()-yc,radius); } #endif break; } } break; case 6 : { // Textured line if (!__color) throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for line primitive [%u].", cimg_instance,n_primitive); const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], tx0 = (unsigned int)primitive[2], ty0 = (unsigned int)primitive[3], tx1 = (unsigned int)primitive[4], ty1 = (unsigned int)primitive[5]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale; if (render_type) { if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opac); else draw_line(x0,y0,x1,y1,color,tx0,ty0,tx1,ty1,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,(float)x1,height()-(float)y1); } #endif } else { draw_point(x0,y0,color.get_vector_at(tx0,ty0)._data,opac). draw_point(x1,y1,color.get_vector_at(tx1,ty1)._data,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); } #endif } } break; case 3 : { // Colored triangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opac).draw_point(x1,y1,pcolor,opac).draw_point(x2,y2,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); board.drawCircle((float)x2,height()-(float)y2,0); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opac).draw_line(zbuffer,x0,y0,z0,x2,y2,z2,pcolor,opac). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opac); else draw_line(x0,y0,x1,y1,pcolor,opac).draw_line(x0,y0,x2,y2,pcolor,opac). draw_line(x1,y1,x2,y2,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,(float)x1,height()-(float)y1); board.drawLine((float)x0,height()-(float)y0,(float)x2,height()-(float)y2); board.drawLine((float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opac,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opac,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = cimg::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp), (unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprops(n0),lightprops(n1),lightprops(n2),opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprops(n0), (float)x1,height()-(float)y1,lightprops(n1), (float)x2,height()-(float)y2,lightprops(n2)); } #endif break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1+lightprops(n0,0))), (int)(light_texture.height()/2*(1+lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1+lightprops(n1,0))), (int)(light_texture.height()/2*(1+lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1+lightprops(n2,0))), (int)(light_texture.height()/2*(1+lightprops(n2,1)))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0, (float)x1,height()-(float)y1,l1, (float)x2,height()-(float)y2,l2); } #endif } break; } } break; case 4 : { // Colored rectangle const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1), x3 = (int)projections(n3,0), y3 = (int)projections(n3,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,pcolor,opac).draw_point(x1,y1,pcolor,opac). draw_point(x2,y2,pcolor,opac).draw_point(x3,y3,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); board.drawCircle((float)x2,height()-(float)y2,0); board.drawCircle((float)x3,height()-(float)y3,0); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,pcolor,opac).draw_line(zbuffer,x1,y1,z1,x2,y2,z2,pcolor,opac). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,pcolor,opac).draw_line(zbuffer,x3,y3,z3,x0,y0,z0,pcolor,opac); else draw_line(x0,y0,x1,y1,pcolor,opac).draw_line(x1,y1,x2,y2,pcolor,opac). draw_line(x2,y2,x3,y3,pcolor,opac).draw_line(x3,y3,x0,y0,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,(float)x1,height()-(float)y1); board.drawLine((float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.drawLine((float)x2,height()-(float)y2,(float)x3,height()-(float)y3); board.drawLine((float)x3,height()-(float)y3,(float)x0,height()-(float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opac).draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opac).draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(color[0],color[1],color[2],(unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.fillTriangle((float)x0,height()-(float)y0,(float)x2,height()-(float)y2,(float)x3,height()-(float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,opac,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,opac,lightprops(l)); else _draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,opac,lightprops(l)). _draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,opac,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = cimg::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(color[0]*lp), (unsigned char)(color[1]*lp), (unsigned char)(color[2]*lp),(unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.fillTriangle((float)x0,height()-(float)y0,(float)x2,height()-(float)y2,(float)x3,height()-(float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,lightprop0,lightprop1,lightprop2,opac). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,lightprop0,lightprop2,lightprop3,opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,lightprop0,lightprop1,lightprop2,opac). draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,lightprop0,lightprop2,lightprop3,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprop0, (float)x1,height()-(float)y1,lightprop1, (float)x2,height()-(float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprop0, (float)x2,height()-(float)y2,lightprop2, (float)x3,height()-(float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1), lx3 = (unsigned int)lightprops(n3,0), ly3 = (unsigned int)lightprops(n3,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,pcolor,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opac); else draw_triangle(x0,y0,x1,y1,x2,y2,pcolor,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac). draw_triangle(x0,y0,x2,y2,x3,y3,pcolor,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opac); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1+lx0)), (int)(light_texture.height()/2*(1+ly0))), l1 = light_texture((int)(light_texture.width()/2*(1+lx1)), (int)(light_texture.height()/2*(1+ly1))), l2 = light_texture((int)(light_texture.width()/2*(1+lx2)), (int)(light_texture.height()/2*(1+ly2))), l3 = light_texture((int)(light_texture.width()/2*(1+lx3)), (int)(light_texture.height()/2*(1+ly3))); board.setPenColorRGBi((unsigned char)(color[0]), (unsigned char)(color[1]), (unsigned char)(color[2]), (unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0, (float)x1,height()-(float)y1,l1, (float)x2,height()-(float)y2,l2); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0, (float)x2,height()-(float)y2,l2, (float)x3,height()-(float)y3,l3); } #endif } break; } } break; case 9 : { // Textured triangle if (!__color) throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for triangle primitive [%u].", cimg_instance,n_primitive); const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], tx0 = (unsigned int)primitive[3], ty0 = (unsigned int)primitive[4], tx1 = (unsigned int)primitive[5], ty1 = (unsigned int)primitive[6], tx2 = (unsigned int)primitive[7], ty2 = (unsigned int)primitive[8]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0,ty0)._data,opac). draw_point(x1,y1,color.get_vector_at(tx1,ty1)._data,opac). draw_point(x2,y2,color.get_vector_at(tx2,ty2)._data,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); board.drawCircle((float)x2,height()-(float)y2,0); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opac). draw_line(zbuffer,x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opac). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opac); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opac). draw_line(x0,y0,z0,x2,y2,z2,color,tx0,ty0,tx2,ty2,opac). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,(float)x1,height()-(float)y1); board.drawLine((float)x0,height()-(float)y0,(float)x2,height()-(float)y2); board.drawLine((float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = cimg::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); } #endif break; case 4 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,lightprops(n0),lightprops(n1),lightprops(n2),opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,lightprops(n0),lightprops(n1),lightprops(n2),opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprops(n0), (float)x1,height()-(float)y1,lightprops(n1), (float)x2,height()-(float)y2,lightprops(n2)); } #endif break; case 5 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture, (unsigned int)lightprops(n0,0),(unsigned int)lightprops(n0,1), (unsigned int)lightprops(n1,0),(unsigned int)lightprops(n1,1), (unsigned int)lightprops(n2,0),(unsigned int)lightprops(n2,1), opac); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1+lightprops(n0,0))), (int)(light_texture.height()/2*(1+lightprops(n0,1)))), l1 = light_texture((int)(light_texture.width()/2*(1+lightprops(n1,0))), (int)(light_texture.height()/2*(1+lightprops(n1,1)))), l2 = light_texture((int)(light_texture.width()/2*(1+lightprops(n2,0))), (int)(light_texture.height()/2*(1+lightprops(n2,1)))); board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0,(float)x1,height()-(float)y1,l1,(float)x2,height()-(float)y2,l2); } #endif break; } } break; case 12 : { // Textured quadrangle if (!__color) throw CImgArgumentException(_cimg_instance "draw_object3d(): Undefined texture for quadrangle primitive [%u].", cimg_instance,n_primitive); const unsigned int n0 = (unsigned int)primitive[0], n1 = (unsigned int)primitive[1], n2 = (unsigned int)primitive[2], n3 = (unsigned int)primitive[3], tx0 = (unsigned int)primitive[4], ty0 = (unsigned int)primitive[5], tx1 = (unsigned int)primitive[6], ty1 = (unsigned int)primitive[7], tx2 = (unsigned int)primitive[8], ty2 = (unsigned int)primitive[9], tx3 = (unsigned int)primitive[10], ty3 = (unsigned int)primitive[11]; const int x0 = (int)projections(n0,0), y0 = (int)projections(n0,1), x1 = (int)projections(n1,0), y1 = (int)projections(n1,1), x2 = (int)projections(n2,0), y2 = (int)projections(n2,1), x3 = (int)projections(n3,0), y3 = (int)projections(n3,1); const float z0 = vertices(n0,2) + Z + _focale, z1 = vertices(n1,2) + Z + _focale, z2 = vertices(n2,2) + Z + _focale, z3 = vertices(n3,2) + Z + _focale; switch (render_type) { case 0 : draw_point(x0,y0,color.get_vector_at(tx0,ty0)._data,opac). draw_point(x1,y1,color.get_vector_at(tx1,ty1)._data,opac). draw_point(x2,y2,color.get_vector_at(tx2,ty2)._data,opac). draw_point(x3,y3,color.get_vector_at(tx3,ty3)._data,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawCircle((float)x0,height()-(float)y0,0); board.drawCircle((float)x1,height()-(float)y1,0); board.drawCircle((float)x2,height()-(float)y2,0); board.drawCircle((float)x3,height()-(float)y3,0); } #endif break; case 1 : if (zbuffer) draw_line(zbuffer,x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opac). draw_line(zbuffer,x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opac). draw_line(zbuffer,x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opac). draw_line(zbuffer,x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opac); else draw_line(x0,y0,z0,x1,y1,z1,color,tx0,ty0,tx1,ty1,opac). draw_line(x1,y1,z1,x2,y2,z2,color,tx1,ty1,tx2,ty2,opac). draw_line(x2,y2,z2,x3,y3,z3,color,tx2,ty2,tx3,ty3,opac). draw_line(x3,y3,z3,x0,y0,z0,color,tx3,ty3,tx0,ty0,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.drawLine((float)x0,height()-(float)y0,(float)x1,height()-(float)y1); board.drawLine((float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.drawLine((float)x2,height()-(float)y2,(float)x3,height()-(float)y3); board.drawLine((float)x3,height()-(float)y3,(float)x0,height()-(float)y0); } #endif break; case 2 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.fillTriangle((float)x0,height()-(float)y0,(float)x2,height()-(float)y2,(float)x3,height()-(float)y3); } #endif break; case 3 : if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac,lightprops(l)). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opac,lightprops(l)); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,opac,lightprops(l)). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,opac,lightprops(l)); #ifdef cimg_use_board if (pboard) { const float lp = cimg::min(lightprops(l),1); board.setPenColorRGBi((unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(128*lp), (unsigned char)(opac*255)); board.fillTriangle((float)x0,height()-(float)y0,(float)x1,height()-(float)y1,(float)x2,height()-(float)y2); board.fillTriangle((float)x0,height()-(float)y0,(float)x2,height()-(float)y2,(float)x3,height()-(float)y3); } #endif break; case 4 : { const float lightprop0 = lightprops(n0), lightprop1 = lightprops(n1), lightprop2 = lightprops(n2), lightprop3 = lightprops(n3); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,lightprop0,lightprop1,lightprop2,opac). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,lightprop0,lightprop2,lightprop3,opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,lightprop0,lightprop1,lightprop2,opac). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,lightprop0,lightprop2,lightprop3,opac); #ifdef cimg_use_board if (pboard) { board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprop0, (float)x1,height()-(float)y1,lightprop1, (float)x2,height()-(float)y2,lightprop2); board.fillGouraudTriangle((float)x0,height()-(float)y0,lightprop0, (float)x2,height()-(float)y2,lightprop2, (float)x3,height()-(float)y3,lightprop3); } #endif } break; case 5 : { const unsigned int lx0 = (unsigned int)lightprops(n0,0), ly0 = (unsigned int)lightprops(n0,1), lx1 = (unsigned int)lightprops(n1,0), ly1 = (unsigned int)lightprops(n1,1), lx2 = (unsigned int)lightprops(n2,0), ly2 = (unsigned int)lightprops(n2,1), lx3 = (unsigned int)lightprops(n3,0), ly3 = (unsigned int)lightprops(n3,1); if (zbuffer) draw_triangle(zbuffer,x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac). draw_triangle(zbuffer,x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opac); else draw_triangle(x0,y0,z0,x1,y1,z1,x2,y2,z2,color,tx0,ty0,tx1,ty1,tx2,ty2,light_texture,lx0,ly0,lx1,ly1,lx2,ly2,opac). draw_triangle(x0,y0,z0,x2,y2,z2,x3,y3,z3,color,tx0,ty0,tx2,ty2,tx3,ty3,light_texture,lx0,ly0,lx2,ly2,lx3,ly3,opac); #ifdef cimg_use_board if (pboard) { const float l0 = light_texture((int)(light_texture.width()/2*(1+lx0)), (int)(light_texture.height()/2*(1+ly0))), l1 = light_texture((int)(light_texture.width()/2*(1+lx1)), (int)(light_texture.height()/2*(1+ly1))), l2 = light_texture((int)(light_texture.width()/2*(1+lx2)), (int)(light_texture.height()/2*(1+ly2))), l3 = light_texture((int)(light_texture.width()/2*(1+lx3)), (int)(light_texture.height()/2*(1+ly3))); board.setPenColorRGBi(128,128,128,(unsigned char)(opac*255)); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0, (float)x1,height()-(float)y1,l1, (float)x2,height()-(float)y2,l2); board.fillGouraudTriangle((float)x0,height()-(float)y0,l0, (float)x2,height()-(float)y2,l2, (float)x3,height()-(float)y3,l3); } #endif } break; } } break; } } return *this; } //@} //--------------------------- // //! \name Data Input //@{ //--------------------------- //! Launch simple interface to select a shape from an image. /** \param disp Display window to use. \param feature_type Type of feature to select. Can be <tt>{ 0=point | 1=line | 2=rectangle | 3=ellipse }</tt>. \param XYZ Pointer to 3 values X,Y,Z which tells about the projection point coordinates, for volumetric images. **/ CImg<T>& select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0) { return get_select(disp,feature_type,XYZ).move_to(*this); } //! Simple interface to select a shape from an image \overloading. CImg<T>& select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0) { return get_select(title,feature_type,XYZ).move_to(*this); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(CImgDisplay &disp, const unsigned int feature_type=2, unsigned int *const XYZ=0) const { return _get_select(disp,0,feature_type,XYZ,0,0,0,true); } //! Simple interface to select a shape from an image \newinstance. CImg<intT> get_select(const char *const title, const unsigned int feature_type=2, unsigned int *const XYZ=0) const { CImgDisplay disp; return _get_select(disp,title,feature_type,XYZ,0,0,0,true); } CImg<intT> _get_select(CImgDisplay &disp, const char *const title, const unsigned int feature_type, unsigned int *const XYZ, const int origX, const int origY, const int origZ, const bool reset_view3d=true) const { if (is_empty()) return CImg<intT>(1,feature_type==0?3:6,1,1,-1); if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); } else if (title) disp.set_title("%s",title); const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0).set_wheel(); unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; int area = 0, starting_area = 0, clicked_area = 0, phase = 0, X0 = (int)((XYZ?XYZ[0]:_width/2)%_width), Y0 = (int)((XYZ?XYZ[1]:_height/2)%_height), Z0 = (int)((XYZ?XYZ[2]:_depth/2)%_depth), X1 =-1, Y1 = -1, Z1 = -1, X = -1, Y = -1, Z = -1, X3d = -1, Y3d = -1, oX = X, oY = Y, oZ = Z, oX3d = X3d, oY3d = -1; unsigned int old_button = 0, key = 0; bool shape_selected = false, text_down = false; static CImg<floatT> pose3d; static bool is_view3d = false; if (reset_view3d) { pose3d.assign(); is_view3d = false; } CImg<floatT> points3d, opacities3d, sel_opacities3d; CImgList<uintT> primitives3d, sel_primitives3d; CImgList<ucharT> colors3d, sel_colors3d; CImg<ucharT> visu, visu0, view3d; char text[1024] = { 0 }; while (!key && !disp.is_closed() && !shape_selected) { // Handle mouse motion and selection oX = X; oY = Y; oZ = Z; int mx = disp.mouse_x(), my = disp.mouse_y(); const int mX = mx<0?-1:mx*(width()+(depth()>1?depth():0))/disp.width(), mY = my<0?-1:my*(height()+(depth()>1?depth():0))/disp.height(); area = 0; if (mX>=0 && mY>=0 && mX<width() && mY<height()) { area = 1; X = mX; Y = mY; Z = phase?Z1:Z0; } if (mX>=0 && mX<width() && mY>=height()) { area = 2; X = mX; Z = mY - _height; Y = phase?Y1:Y0; } if (mY>=0 && mX>=width() && mY<height()) { area = 3; Y = mY; Z = mX - _width; X = phase?X1:X0; } if (mX>=width() && mY>=height()) area = 4; if (disp.button()) { if (!clicked_area) clicked_area = area; } else clicked_area = 0; switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(1); key = 0; } break; case cimg::keyPAGEDOWN : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_wheel(-1); key = 0; } break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyV : is_view3d = !is_view3d; disp.set_key(key,false); key = 0; visu0.assign(); break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.bmp",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { visu.draw_text(0,0," Saving snapshot... ",foreground_color,background_color,1,13).display(disp); visu0.save(filename); visu.draw_text(0,0," Snapshot '%s' saved. ",foreground_color,background_color,1,13,filename).display(disp); } disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving instance... ",foreground_color,background_color,1,13).display(disp); save(filename); visu.draw_text(0,0," Instance '%s' saved. ",foreground_color,background_color,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; } switch (area) { case 0 : // When mouse is out of image range. mx = my = X = Y = Z = -1; break; case 1 : case 2 : case 3 : // When mouse is over the XY,XZ or YZ projections. if (disp.button()&1 && phase<2 && clicked_area==area) { // When selection has been started (1st step). if (_depth>1 && (X1!=X || Y1!=Y || Z1!=Z)) visu0.assign(); X1 = X; Y1 = Y; Z1 = Z; } if (!(disp.button()&1) && phase>=2 && clicked_area!=area) { // When selection is at 2nd step (for volumes). switch (starting_area) { case 1 : if (Z1!=Z) visu0.assign(); Z1 = Z; break; case 2 : if (Y1!=Y) visu0.assign(); Y1 = Y; break; case 3 : if (X1!=X) visu0.assign(); X1 = X; break; } } if (disp.button()&2 && clicked_area==area) { // When moving through the image/volume. if (phase) { if (_depth>1 && (X1!=X || Y1!=Y || Z1!=Z)) visu0.assign(); X1 = X; Y1 = Y; Z1 = Z; } else { if (_depth>1 && (X0!=X || Y0!=Y || Z0!=Z)) visu0.assign(); X0 = X; Y0 = Y; Z0 = Z; } } if (disp.button()&4) { // Reset positions. oX = X = X0; oY = Y = Y0; oZ = Z = Z0; phase = area = clicked_area = starting_area = 0; visu0.assign(); } if (disp.wheel()) { // When moving through the slices of the volume (with mouse wheel). if (_depth>1 && !disp.is_keyCTRLLEFT() && !disp.is_keyCTRLRIGHT() && !disp.is_keySHIFTLEFT() && !disp.is_keySHIFTRIGHT() && !disp.is_keyALT() && !disp.is_keyALTGR()) { switch (area) { case 1 : if (phase) Z = (Z1+=disp.wheel()); else Z = (Z0+=disp.wheel()); visu0.assign(); break; case 2 : if (phase) Y = (Y1+=disp.wheel()); else Y = (Y0+=disp.wheel()); visu0.assign(); break; case 3 : if (phase) X = (X1+=disp.wheel()); else X = (X0+=disp.wheel()); visu0.assign(); break; } disp.set_wheel(); } else key = ~0U; } if ((disp.button()&1)!=old_button) { // When left button has just been pressed or released. switch (phase) { case 0 : if (area==clicked_area) { X0 = X1 = X; Y0 = Y1 = Y; Z0 = Z1 = Z; starting_area = area; ++phase; } break; case 1 : if (area==starting_area) { X1 = X; Y1 = Y; Z1 = Z; ++phase; } else if (!(disp.button()&1)) { oX = X = X0; oY = Y = Y0; oZ = Z = Z0; phase = 0; visu0.assign(); } break; case 2 : ++phase; break; } old_button = disp.button()&1; } break; case 4 : // When mouse is over the 3d view. if (is_view3d && points3d) { X3d = mx - _width*disp.width()/(_width+(_depth>1?_depth:0)); Y3d = my - _height*disp.height()/(_height+(_depth>1?_depth:0)); if (oX3d<0) { oX3d = X3d; oY3d = Y3d; } if ((disp.button()&3)==3) { pose3d.assign(); view3d.assign(); oX3d = oY3d = X3d = Y3d = -1; } // Left + right buttons: reset. else if (disp.button()&1 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Left button: rotate. const float R = 0.45f*cimg::min(view3d._width,view3d._height), R2 = R*R, u0 = (float)(oX3d-view3d.width()/2), v0 = (float)(oY3d-view3d.height()/2), u1 = (float)(X3d-view3d.width()/2), v1 = (float)(Y3d-view3d.height()/2), n0 = (float)std::sqrt(u0*u0+v0*v0), n1 = (float)std::sqrt(u1*u1+v1*v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(cimg::max(0,R2-nu0*nu0-nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(cimg::max(0,R2-nu1*nu1-nv1*nv1)), u = nv0*nw1 - nw0*nv1, v = nw0*nu1 - nu0*nw1, w = nv0*nu1 - nu0*nv1, n = (float)std::sqrt(u*u+v*v+w*w), alpha = (float)std::asin(n/R2); pose3d.draw_image(CImg<floatT>::rotation_matrix(u,v,w,alpha)*pose3d.get_crop(0,0,2,2)); view3d.assign(); } else if (disp.button()&2 && pose3d && oY3d!=Y3d) { // Right button: zoom. pose3d(3,2)-=(oY3d - Y3d)*1.5f; view3d.assign(); } if (disp.wheel()) { // Wheel: zoom pose3d(3,2)-=disp.wheel()*15; view3d.assign(); disp.set_wheel(); } if (disp.button()&4 && pose3d && (oX3d!=X3d || oY3d!=Y3d)) { // Middle button: shift. pose3d(3,0)-=oX3d - X3d; pose3d(3,1)-=oY3d - Y3d; view3d.assign(); } oX3d = X3d; oY3d = Y3d; } mx = my = X = Y = Z = -1; break; } if (phase) { if (!feature_type) shape_selected = phase?true:false; else { if (_depth>1) shape_selected = (phase==3)?true:false; else shape_selected = (phase==2)?true:false; } } if (X0<0) X0 = 0; if (X0>=width()) X0 = width() - 1; if (Y0<0) Y0 = 0; if (Y0>=height()) Y0 = height() - 1; if (Z0<0) Z0 = 0; if (Z0>=depth()) Z0 = depth() - 1; if (X1<1) X1 = 0; if (X1>=width()) X1 = width() - 1; if (Y1<0) Y1 = 0; if (Y1>=height()) Y1 = height() - 1; if (Z1<0) Z1 = 0; if (Z1>=depth()) Z1 = depth() - 1; // Draw visualization image on the display if (oX!=X || oY!=Y || oZ!=Z || !visu0 || (_depth>1 && !view3d)) { if (!visu0) { // Create image of projected planes. CImg<Tuchar> tmp, tmp0; if (_depth!=1) { tmp0 = get_projections2d(phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0); tmp = tmp0.get_channels(0,cimg::min(2,spectrum() - 1)); } else tmp = get_channels(0,cimg::min(2,spectrum() - 1)); switch (old_normalization) { case 0 : tmp.move_to(visu0); break; case 1 : tmp.normalize(0,255).move_to(visu0); break; case 2 : { const float m = disp._min, M = disp._max; ((tmp-=m)*=255.0f/(M-m>0?M-m:1)).move_to(visu0); } case 3 : if (cimg::type<T>::is_float()) (tmp.normalize(0,255)).move_to(visu0); else { const float m = (float)cimg::type<T>::min(), M = (float)cimg::type<T>::max(); ((tmp-=m)*=255.0f/(M-m)).move_to(visu0); } break; } visu0.resize(disp); view3d.assign(); points3d.assign(); } if (is_view3d && _depth>1 && !view3d) { // Create 3d view for volumetric images. const unsigned int _x3d = (unsigned int)cimg::round((float)_width*visu0._width/(_width+_depth),1,1), _y3d = (unsigned int)cimg::round((float)_height*visu0._height/(_height+_depth),1,1), x3d = _x3d>=visu0._width?visu0._width-1:_x3d, y3d = _y3d>=visu0._height?visu0._height-1:_y3d; CImg<ucharT>(1,2,1,1,64,128).resize(visu0._width-x3d,visu0._height-y3d,1,visu0._spectrum,3).move_to(view3d); if (!points3d) { get_projections3d(primitives3d,colors3d,phase?X1:X0,phase?Y1:Y0,phase?Z1:Z0,true).move_to(points3d); points3d.append(CImg<floatT>(8,3,1,1, 0,_width-1,_width-1,0,0,_width-1,_width-1,0, 0,0,_height-1,_height-1,0,0,_height-1,_height-1, 0,0,0,0,_depth-1,_depth-1,_depth-1,_depth-1),'x'); CImg<uintT>::vector(12,13).move_to(primitives3d); CImg<uintT>::vector(13,14).move_to(primitives3d); CImg<uintT>::vector(14,15).move_to(primitives3d); CImg<uintT>::vector(15,12).move_to(primitives3d); CImg<uintT>::vector(16,17).move_to(primitives3d); CImg<uintT>::vector(17,18).move_to(primitives3d); CImg<uintT>::vector(18,19).move_to(primitives3d); CImg<uintT>::vector(19,16).move_to(primitives3d); CImg<uintT>::vector(12,16).move_to(primitives3d); CImg<uintT>::vector(13,17).move_to(primitives3d); CImg<uintT>::vector(14,18).move_to(primitives3d); CImg<uintT>::vector(15,19).move_to(primitives3d); colors3d.insert(12,CImg<ucharT>::vector(255,255,255)); opacities3d.assign(primitives3d.width(),1,1,1,0.5f); if (!phase) { opacities3d[0] = opacities3d[1] = opacities3d[2] = 0.8f; sel_primitives3d.assign(); sel_colors3d.assign(); sel_opacities3d.assign(); } else { if (feature_type==2) { points3d.append(CImg<floatT>(8,3,1,1, X0,X1,X1,X0,X0,X1,X1,X0, Y0,Y0,Y1,Y1,Y0,Y0,Y1,Y1, Z0,Z0,Z0,Z0,Z1,Z1,Z1,Z1),'x'); sel_primitives3d.assign(); CImg<uintT>::vector(20,21).move_to(sel_primitives3d); CImg<uintT>::vector(21,22).move_to(sel_primitives3d); CImg<uintT>::vector(22,23).move_to(sel_primitives3d); CImg<uintT>::vector(23,20).move_to(sel_primitives3d); CImg<uintT>::vector(24,25).move_to(sel_primitives3d); CImg<uintT>::vector(25,26).move_to(sel_primitives3d); CImg<uintT>::vector(26,27).move_to(sel_primitives3d); CImg<uintT>::vector(27,24).move_to(sel_primitives3d); CImg<uintT>::vector(20,24).move_to(sel_primitives3d); CImg<uintT>::vector(21,25).move_to(sel_primitives3d); CImg<uintT>::vector(22,26).move_to(sel_primitives3d); CImg<uintT>::vector(23,27).move_to(sel_primitives3d); } else { points3d.append(CImg<floatT>(2,3,1,1, X0,X1, Y0,Y1, Z0,Z1),'x'); sel_primitives3d.assign(CImg<uintT>::vector(20,21)); } sel_colors3d.assign(sel_primitives3d._width,CImg<ucharT>::vector(255,255,255)); sel_opacities3d.assign(sel_primitives3d._width,1,1,1,0.8f); } points3d.shift_object3d(-0.5f*_width,-0.5f*_height,-0.5f*_depth).resize_object3d(); points3d*=0.75f*cimg::min(view3d._width,view3d._height); } if (!pose3d) CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose3d); CImg<floatT> zbuffer3d(view3d._width,view3d._height,1,1,0); const CImg<floatT> rotated_points3d = pose3d.get_crop(0,0,2,2)*points3d; if (sel_primitives3d) view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,sel_primitives3d,sel_colors3d,sel_opacities3d, 2,true,500,0,0,0,0,0,zbuffer3d); view3d.draw_object3d(pose3d(3,0) + 0.5f*view3d._width, pose3d(3,1) + 0.5f*view3d._height, pose3d(3,2), rotated_points3d,primitives3d,colors3d,opacities3d, 2,true,500,0,0,0,0,0,zbuffer3d); visu0.draw_image(x3d,y3d,view3d); } visu = visu0; const int d = (_depth>1)?_depth:0; if (phase) switch (feature_type) { case 1 : { const int x0 = (int)((X0+0.5f)*disp.width()/(_width+d)), y0 = (int)((Y0+0.5f)*disp.height()/(_height+d)), x1 = (int)((X1+0.5f)*disp.width()/(_width+d)), y1 = (int)((Y1+0.5f)*disp.height()/(_height+d)); visu.draw_arrow(x0,y0,x1,y1,background_color,0.9f,30,5,0x55555555). draw_arrow(x0,y0,x1,y1,foreground_color,0.9f,30,5,0xAAAAAAAA); if (d) { const int zx0 = (int)((_width+Z0+0.5f)*disp.width()/(_width+d)), zx1 = (int)((_width+Z1+0.5f)*disp.width()/(_width+d)), zy0 = (int)((_height+Z0+0.5f)*disp.height()/(_height+d)), zy1 = (int)((_height+Z1+0.5f)*disp.height()/(_height+d)); visu.draw_arrow(zx0,y0,zx1,y1,foreground_color,0.9f,30,5,0x55555555). draw_arrow(x0,zy0,x1,zy1,foreground_color,0.9f,30,5,0x55555555). draw_arrow(zx0,y0,zx1,y1,foreground_color,0.9f,30,5,0xAAAAAAAA). draw_arrow(x0,zy0,x1,zy1,foreground_color,0.9f,30,5,0xAAAAAAAA); } } break; case 2 : { const int x0 = (X0<X1?X0:X1)*disp.width()/(_width+d), y0 = (Y0<Y1?Y0:Y1)*disp.height()/(_height+d), x1 = ((X0<X1?X1:X0)+1)*disp.width()/(_width+d)-1, y1 = ((Y0<Y1?Y1:Y0)+1)*disp.height()/(_height+d)-1; visu.draw_rectangle(x0,y0,x1,y1,background_color,0.2f).draw_rectangle(x0,y0,x1,y1,foreground_color,0.6f,0x55555555); if (d) { const int zx0 = (int)((_width+(Z0<Z1?Z0:Z1))*disp.width()/(_width+d)), zy0 = (int)((_height+(Z0<Z1?Z0:Z1))*disp.height()/(_height+d)), zx1 = (int)((_width+(Z0<Z1?Z1:Z0)+1)*disp.width()/(_width+d))-1, zy1 = (int)((_height+(Z0<Z1?Z1:Z0)+1)*disp.height()/(_height+d))-1; visu.draw_rectangle(zx0,y0,zx1,y1,background_color,0.2f).draw_rectangle(zx0,y0,zx1,y1,foreground_color,0.6f,0x55555555). draw_rectangle(x0,zy0,x1,zy1,background_color,0.2f).draw_rectangle(x0,zy0,x1,zy1,foreground_color,0.6f,0x55555555); } } break; case 3 : { const int x0 = X0*disp.width()/(_width+d), y0 = Y0*disp.height()/(_height+d), x1 = X1*disp.width()/(_width+d)-1, y1 = Y1*disp.height()/(_height+d)-1; visu.draw_ellipse(x0,y0,(float)cimg::abs(x1-x0),(float)cimg::abs(y1-y0),0,background_color,0.2f). draw_ellipse(x0,y0,(float)cimg::abs(x1-x0),(float)cimg::abs(y1-y0),0,foreground_color,0.6f,0x55555555). draw_point(x0,y0,foreground_color,0.6f); if (d) { const int zx0 = (int)((_width+Z0)*disp.width()/(_width+d)), zy0 = (int)((_height+Z0)*disp.height()/(_height+d)), zx1 = (int)((_width+Z1+1)*disp.width()/(_width+d))-1, zy1 = (int)((_height+Z1+1)*disp.height()/(_height+d))-1; visu.draw_ellipse(zx0,y0,(float)cimg::abs(zx1-zx0),(float)cimg::abs(y1-y0),0,background_color,0.2f). draw_ellipse(zx0,y0,(float)cimg::abs(zx1-zx0),(float)cimg::abs(y1-y0),0,foreground_color,0.6f,0x55555555). draw_point(zx0,y0,foreground_color,0.6f). draw_ellipse(x0,zy0,(float)cimg::abs(x1-x0),(float)cimg::abs(zy1-zy0),0,background_color,0.2f). draw_ellipse(x0,zy0,(float)cimg::abs(x1-x0),(float)cimg::abs(zy1-zy0),0,foreground_color,0.6f,0x55555555). draw_point(x0,zy0,foreground_color,0.6f); } } break; } else { const int x0 = X*disp.width()/(_width+d), y0 = Y*disp.height()/(_height+d), x1 = (X+1)*disp.width()/(_width+d)-1, y1 = (Y+1)*disp.height()/(_height+d)-1, zx0 = (Z+_width)*disp.width()/(_width+d), zx1 = (Z+_width+1)*disp.width()/(_width+d), zy0 = (Z+_height)*disp.height()/(_height+d), zy1 = (Z+_height+1)*disp.height()/(_height+d); if (x1-x0>=4 && y1-y0>=4) visu.draw_rectangle(x0,y0,x1,y1,background_color,0.2f). draw_rectangle(x0,y0,x1,y1,foreground_color,0.6f,~0U); if (_depth>1) { if (y1-y0>=4 && zx1-zx0>=4) visu.draw_rectangle(zx0,y0,zx1,y1,background_color,0.2f). draw_rectangle(zx0,y0,zx1,y1,foreground_color,0.6f,~0U); if (x1-x0>=4 && zy1-zy0>=4) visu.draw_rectangle(x0,zy0,x1,zy1,background_color,0.2f). draw_rectangle(x0,zy0,x1,zy1,foreground_color,0.6f,~0U); } } if (my>=0 && my<13) text_down = true; else if (my>=visu.height()-13) text_down = false; if (!feature_type || !phase) { if (X>=0 && Y>=0 && Z>=0 && X<width() && Y<height() && Z<depth()) { if (_depth>1) cimg_snprintf(text,sizeof(text)," Point (%d,%d,%d) = [ ",origX+X,origY+Y,origZ+Z); else cimg_snprintf(text,sizeof(text)," Point (%d,%d) = [ ",origX+X,origY+Y); char *ctext = text + std::strlen(text), *const ltext = text + 512; for (unsigned int c = 0; c<_spectrum && ctext<ltext; ++c) { cimg_snprintf(ctext,sizeof(text)/2,cimg::type<T>::format(),cimg::type<T>::format((*this)(X,Y,Z,c))); ctext = text + std::strlen(text); *(ctext++) = ' '; *ctext = 0; } std::strcpy(text + std::strlen(text),"] "); } } else switch (feature_type) { case 1 : { const double dX = (double)(X0 - X1), dY = (double)(Y0 - Y1), dZ = (double)(Z0 - Z1), norm = std::sqrt(dX*dX+dY*dY+dZ*dZ); if (_depth>1) cimg_snprintf(text,sizeof(text)," Vect (%d,%d,%d)-(%d,%d,%d), Norm = %g ", origX+X0,origY+Y0,origZ+Z0,origX+X1,origY+Y1,origZ+Z1,norm); else cimg_snprintf(text,sizeof(text)," Vect (%d,%d)-(%d,%d), Norm = %g ", origX+X0,origY+Y0,origX+X1,origY+Y1,norm); } break; case 2 : if (_depth>1) cimg_snprintf(text,sizeof(text)," Box (%d,%d,%d)-(%d,%d,%d), Size = (%d,%d,%d) ", origX+(X0<X1?X0:X1),origY+(Y0<Y1?Y0:Y1),origZ+(Z0<Z1?Z0:Z1), origX+(X0<X1?X1:X0),origY+(Y0<Y1?Y1:Y0),origZ+(Z0<Z1?Z1:Z0), 1+cimg::abs(X0-X1),1+cimg::abs(Y0-Y1),1+cimg::abs(Z0-Z1)); else cimg_snprintf(text,sizeof(text)," Box (%d,%d)-(%d,%d), Size = (%d,%d) ", origX+(X0<X1?X0:X1),origY+(Y0<Y1?Y0:Y1),origX+(X0<X1?X1:X0),origY+(Y0<Y1?Y1:Y0), 1+cimg::abs(X0-X1),1+cimg::abs(Y0-Y1)); break; default : if (_depth>1) cimg_snprintf(text,sizeof(text)," Ellipse (%d,%d,%d)-(%d,%d,%d), Radii = (%d,%d,%d) ", origX+X0,origY+Y0,origZ+Z0,origX+X1,origY+Y1,origZ+Z1, 1+cimg::abs(X0-X1),1+cimg::abs(Y0-Y1),1+cimg::abs(Z0-Z1)); else cimg_snprintf(text,sizeof(text)," Ellipse (%d,%d)-(%d,%d), Radii = (%d,%d) ", origX+X0,origY+Y0,origX+X1,origY+Y1,1+cimg::abs(X0-X1),1+cimg::abs(Y0-Y1)); } if (phase || (mx>=0 && my>=0)) visu.draw_text(0,text_down?visu.height()-13:0,text,foreground_color,background_color,0.7f,13); disp.display(visu).wait(); } else if (!shape_selected) disp.wait(); if (disp.is_resized()) { disp.resize(false)._is_resized = false; old_is_resized = true; visu0.assign(); } } // Return result CImg<intT> res(1,feature_type==0?3:6,1,1,-1); if (XYZ) { XYZ[0] = (unsigned int)X0; XYZ[1] = (unsigned int)Y0; XYZ[2] = (unsigned int)Z0; } if (shape_selected) { if (feature_type==2) { if (X0>X1) cimg::swap(X0,X1); if (Y0>Y1) cimg::swap(Y0,Y1); if (Z0>Z1) cimg::swap(Z0,Z1); } if (X1<0 || Y1<0 || Z1<0) X0 = Y0 = Z0 = X1 = Y1 = Z1 = -1; switch (feature_type) { case 1 : case 2 : res[0] = X0; res[1] = Y0; res[2] = Z0; res[3] = X1; res[4] = Y1; res[5] = Z1; break; case 3 : res[3] = cimg::abs(X1-X0); res[4] = cimg::abs(Y1-Y0); res[5] = cimg::abs(Z1-Z0); // keep no break here! default : res[0] = X0; res[1] = Y0; res[2] = Z0; } } disp.set_button(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; if (key!=~0U) disp.set_key(key); return res; } //! Select sub-graph in a graph. CImg<intT> get_select_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "select_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(640,480,1),0,0).set_title("CImg<%s>",pixel_type()); const unsigned long siz = (unsigned long)_width*_height*_depth; const unsigned int old_normalization = disp.normalization(); disp.show().set_button().set_wheel()._normalization = 0; double nymin = ymin, nymax = ymax, nxmin = xmin, nxmax = xmax; if (nymin==nymax) { nymin = (Tfloat)min_max(nymax); const double dy = nymax - nymin; nymin-=dy/20; nymax+=dy/20; } if (nymin==nymax) { --nymin; ++nymax; } if (nxmin==nxmax && nxmin==0) { nxmin = 0; nxmax = siz - 1.0; } const unsigned char black[] = { 0, 0, 0 }, white[] = { 255, 255, 255 }, gray[] = { 220, 220, 220 }; const unsigned char gray2[] = { 110, 110, 110 }, ngray[] = { 35, 35, 35 }; static unsigned int odimv = 0; static CImg<ucharT> colormap; if (odimv!=_spectrum) { odimv = _spectrum; colormap = CImg<ucharT>(3,_spectrum,1,1,120).noise(70,1); if (_spectrum==1) { colormap[0] = colormap[1] = 120; colormap[2] = 200; } else { colormap(0,0) = 220; colormap(1,0) = 10; colormap(2,0) = 10; if (_spectrum>1) { colormap(0,1) = 10; colormap(1,1) = 220; colormap(2,1) = 10; } if (_spectrum>2) { colormap(0,2) = 10; colormap(1,2) = 10; colormap(2,2) = 220; } } } CImg<ucharT> visu0, visu, graph, text, axes; int x0 = -1, x1 = -1, y0 = -1, y1 = -1, omouse_x = -2, omouse_y = -2; const unsigned int one = plot_type==3?0:1; unsigned int okey = 0, obutton = 0; char message[1024] = { 0 }; CImg_3x3(I,unsigned char); for (bool selected = false; !selected && !disp.is_closed() && !okey && !disp.wheel(); ) { const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); const unsigned int key = disp.key(), button = disp.button(); // Generate graph representation. if (!visu0) { visu0.assign(disp.width(),disp.height(),1,3,220); const int gdimx = disp.width() - 32, gdimy = disp.height() - 32; if (gdimx>0 && gdimy>0) { graph.assign(gdimx,gdimy,1,3,255); if (siz<32) { if (siz>1) graph.draw_grid(gdimx/(float)(siz - one),gdimy/(float)(siz - one),0,0,false,true,black,0.2f,0x33333333,0x33333333); } else graph.draw_grid(-10,-10,0,0,false,true,black,0.2f,0x33333333,0x33333333); cimg_forC(*this,c) graph.draw_graph(get_shared_channel(c),&colormap(0,c),(plot_type!=3 || _spectrum==1)?1:0.6f, plot_type,vertex_type,nymax,nymin); axes.assign(gdimx,gdimy,1,1,0); const float dx = (float)cimg::abs(nxmax-nxmin), dy = (float)cimg::abs(nymax-nymin), px = (float)std::pow(10.0,(int)std::log10(dx?dx:1)-2.0), py = (float)std::pow(10.0,(int)std::log10(dy?dy:1)-2.0); const CImg<Tdouble> seqx = dx<=0?CImg<Tdouble>::vector(nxmin):CImg<Tdouble>::sequence(1 + gdimx/60,nxmin,one?nxmax:nxmin+(nxmax-nxmin)*(siz+1)/siz).round(px), seqy = CImg<Tdouble>::sequence(1 + gdimy/60,nymax,nymin).round(py); const bool allow_zero = (nxmin*nxmax>0) || (nymin*nymax>0); axes.draw_axes(seqx,seqy,white,1,~0U,~0U,13,allow_zero); if (nymin>0) axes.draw_axis(seqx,gdimy-1,gray,1,~0U,13,allow_zero); if (nymax<0) axes.draw_axis(seqx,0,gray,1,~0U,13,allow_zero); if (nxmin>0) axes.draw_axis(0,seqy,gray,1,~0U,13,allow_zero); if (nxmax<0) axes.draw_axis(gdimx-1,seqy,gray,1,~0U,13,allow_zero); cimg_for3x3(axes,x,y,0,0,I,unsigned char) if (Icc) { if (Icc==255) cimg_forC(graph,c) graph(x,y,c) = 0; else cimg_forC(graph,c) graph(x,y,c) = (unsigned char)(2*graph(x,y,c)/3); } else if (Ipc || Inc || Icp || Icn || Ipp || Inn || Ipn || Inp) cimg_forC(graph,c) graph(x,y,c) = (graph(x,y,c)+511)/3; visu0.draw_image(16,16,graph); visu0.draw_line(15,15,16+gdimx,15,gray2).draw_line(16+gdimx,15,16+gdimx,16+gdimy,gray2). draw_line(16+gdimx,16+gdimy,15,16+gdimy,white).draw_line(15,16+gdimy,15,15,white); } else graph.assign(); text.assign().draw_text(0,0,labelx?labelx:"X-axis",white,ngray,1,13).resize(-100,-100,1,3); visu0.draw_image((visu0.width()-text.width())/2,visu0.height()-14,~text); text.assign().draw_text(0,0,labely?labely:"Y-axis",white,ngray,1,13).rotate(-90).resize(-100,-100,1,3); visu0.draw_image(1,(visu0.height()-text.height())/2,~text); visu.assign(); } // Generate and display current view. if (!visu) { visu.assign(visu0); if (graph && x0>=0 && x1>=0) { const int nx0 = x0<=x1?x0:x1, nx1 = x0<=x1?x1:x0, ny0 = y0<=y1?y0:y1, ny1 = y0<=y1?y1:y0, sx0 = 16 + nx0*(visu.width()-32)/cimg::max(1U,siz-one), sx1 = 15 + (nx1+1)*(visu.width()-32)/cimg::max(1U,siz-one), sy0 = 16 + ny0, sy1 = 16 + ny1; if (y0>=0 && y1>=0) visu.draw_rectangle(sx0,sy0,sx1,sy1,gray,0.5f).draw_rectangle(sx0,sy0,sx1,sy1,black,0.5f,0xCCCCCCCCU); else visu.draw_rectangle(sx0,0,sx1,visu.height()-17,gray,0.5f). draw_line(sx0,16,sx0,visu.height()-17,black,0.5f,0xCCCCCCCCU). draw_line(sx1,16,sx1,visu.height()-17,black,0.5f,0xCCCCCCCCU); } if (mouse_x>=16 && mouse_y>=16 && mouse_x<visu.width()-16 && mouse_y<visu.height()-16) { if (graph) visu.draw_line(mouse_x,16,mouse_x,visu.height()-17,black,0.5f,0x55555555U); const unsigned int x = (unsigned int)cimg::round((mouse_x-16.0f)*(siz-one)/(disp.width()-32),1,one?0:-1); const double cx = nxmin + x*(nxmax-nxmin)/cimg::max(1U,siz-1); if (_spectrum>=7) cimg_snprintf(message,sizeof(message),"Value[%u:%g] = ( %g %g %g ... %g %g %g )",x,cx, (double)(*this)(x,0,0,0),(double)(*this)(x,0,0,1),(double)(*this)(x,0,0,2), (double)(*this)(x,0,0,_spectrum-4),(double)(*this)(x,0,0,_spectrum-3),(double)(*this)(x,0,0,_spectrum-1)); else { cimg_snprintf(message,sizeof(message),"Value[%u:%g] = ( ",x,cx); cimg_forC(*this,c) std::sprintf(message + std::strlen(message),"%g ",(double)(*this)(x,0,0,c)); std::sprintf(message + std::strlen(message),")"); } if (x0>=0 && x1>=0) { const unsigned int nx0 = x0<=x1?x0:x1, nx1 = x0<=x1?x1:x0, ny0 = y0<=y1?y0:y1, ny1 = y0<=y1?y1:y0; const double cx0 = nxmin + nx0*(nxmax-nxmin)/cimg::max(1U,siz-1), cx1 = nxmin + (nx1+one)*(nxmax-nxmin)/cimg::max(1U,siz-1), cy0 = nymax - ny0*(nymax-nymin)/(visu._height-32), cy1 = nymax - ny1*(nymax-nymin)/(visu._height-32); if (y0>=0 && y1>=0) std::sprintf(message + std::strlen(message)," - Range ( %u:%g, %g ) - ( %u:%g, %g )",x0,cx0,cy0,x1+one,cx1,cy1); else std::sprintf(message + std::strlen(message)," - Range [ %u:%g - %u:%g ]",x0,cx0,x1+one,cx1); } text.assign().draw_text(0,0,message,white,ngray,1,13).resize(-100,-100,1,3); visu.draw_image((visu.width()-text.width())/2,1,~text); } visu.display(disp); } // Test keys. switch (okey = key) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case cimg::keyCTRLLEFT : case cimg::keySHIFTLEFT : okey = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(640,480,1),false)._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); okey = 0; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.bmp",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).draw_text(0,0," Saving snapshot... ",black,gray,1,13).display(disp); screen.save(filename); screen.draw_text(0,0," Snapshot '%s' saved. ",black,gray,1,13,filename).display(disp); } disp.set_key(key,false); okey = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; if (visu || visu0) { CImg<ucharT> &screen = visu?visu:visu0; char filename[32] = { 0 }; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+screen).draw_text(0,0," Saving instance... ",black,gray,1,13).display(disp); save(filename); screen.draw_text(0,0," Instance '%s' saved. ",black,gray,1,13,filename).display(disp); } disp.set_key(key,false); okey = 0; } break; } // Handle mouse motion and mouse buttons if (obutton!=button || omouse_x!=mouse_x || omouse_y!=mouse_y) { visu.assign(); if (disp.mouse_x()>=0 && disp.mouse_y()>=0) { const int mx = (mouse_x -16)*(int)(siz-one)/(disp.width()-32), cx = mx<0?0:(mx>=(int)(siz-one)?(int)(siz-1-one):mx), my = mouse_y - 16, cy = my<=0?0:(my>=(disp.height()-32)?(disp.height()-32):my); if (button&1) { if (!obutton) { x0 = cx; y0 = -1; } else { x1 = cx; y1 = -1; } } else if (button&2) { if (!obutton) { x0 = cx; y0 = cy; } else { x1 = cx; y1 = cy; } } else if (obutton) { x1 = x1>=0?cx:-1; y1 = y1>=0?cy:-1; selected = true; } } else if (!button && obutton) selected = true; obutton = button; omouse_x = mouse_x; omouse_y = mouse_y; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (visu && visu0) disp.wait(); } disp._normalization = old_normalization; if (x1>=0 && x1<x0) cimg::swap(x0,x1); if (y1<y0) cimg::swap(y0,y1); disp.set_key(okey); return CImg<intT>(4,1,1,1,x0,y0,x1>=0?x1+(int)one:-1,y1); } //! Load image from a file. /** \param filename Filename, as a C-string. \note The extension of \c filename defines the file format. If no filename extension is provided, CImg<T>::get_load() will try to load the file as a .cimg or .cimgz file. **/ CImg<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load(): Specified filename is (null).", cimg_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { char filename_local[1024] = { 0 }; load(cimg::load_network_external(filename,filename_local)); std::remove(filename_local); return *this; } const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { #ifdef cimg_load_plugin cimg_load_plugin(filename); #endif #ifdef cimg_load_plugin1 cimg_load_plugin1(filename); #endif #ifdef cimg_load_plugin2 cimg_load_plugin2(filename); #endif #ifdef cimg_load_plugin3 cimg_load_plugin3(filename); #endif #ifdef cimg_load_plugin4 cimg_load_plugin4(filename); #endif #ifdef cimg_load_plugin5 cimg_load_plugin5(filename); #endif #ifdef cimg_load_plugin6 cimg_load_plugin6(filename); #endif #ifdef cimg_load_plugin7 cimg_load_plugin7(filename); #endif #ifdef cimg_load_plugin8 cimg_load_plugin8(filename); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) load_ascii(filename); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) load_dlm(filename); // 2d binary formats else if (!cimg::strcasecmp(ext,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) load_jpeg(filename); else if (!cimg::strcasecmp(ext,"png")) load_png(filename); else if (!cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"pnm") || !cimg::strcasecmp(ext,"pbm") || !cimg::strcasecmp(ext,"pnk")) load_pnm(filename); else if (!cimg::strcasecmp(ext,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"exr")) load_exr(filename); else if (!cimg::strcasecmp(ext,"cr2") || !cimg::strcasecmp(ext,"crw") || !cimg::strcasecmp(ext,"dcr") || !cimg::strcasecmp(ext,"mrw") || !cimg::strcasecmp(ext,"nef") || !cimg::strcasecmp(ext,"orf") || !cimg::strcasecmp(ext,"pix") || !cimg::strcasecmp(ext,"ptx") || !cimg::strcasecmp(ext,"raf") || !cimg::strcasecmp(ext,"srf")) load_dcraw_external(filename); // 3d binary formats else if (!cimg::strcasecmp(ext,"dcm") || !cimg::strcasecmp(ext,"dicom")) load_medcon_external(filename); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) load_analyze(filename); else if (!cimg::strcasecmp(ext,"par") || !cimg::strcasecmp(ext,"rec")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"mnc")) load_minc2(filename); else if (!cimg::strcasecmp(ext,"inr")) load_inr(filename); else if (!cimg::strcasecmp(ext,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) return load_cimg(filename); // Archive files else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); // Image sequences else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_ffmpeg(filename); else throw CImgIOException("CImg<%s>::load()", pixel_type()); } catch (CImgIOException&) { std::FILE *file = 0; try { file = cimg::fopen(filename,"rb"); } catch (CImgIOException&) { cimg::exception_mode() = omode; throw CImgIOException(_cimg_instance "load(): Failed to open file '%s'.", cimg_instance, filename); } try { const char *const f_type = cimg::file_type(file,filename); std::fclose(file); if (!cimg::strcasecmp(f_type,"pnm")) load_pnm(filename); else if (!cimg::strcasecmp(f_type,"pfm")) load_pfm(filename); else if (!cimg::strcasecmp(f_type,"bmp")) load_bmp(filename); else if (!cimg::strcasecmp(f_type,"jpg")) load_jpeg(filename); else if (!cimg::strcasecmp(f_type,"pan")) load_pandore(filename); else if (!cimg::strcasecmp(f_type,"png")) load_png(filename); else if (!cimg::strcasecmp(f_type,"tif")) load_tiff(filename); else if (!cimg::strcasecmp(f_type,"inr")) load_inr(filename); else if (!cimg::strcasecmp(f_type,"dcm")) load_medcon_external(filename); else throw CImgIOException("CImg<%s>::load()", pixel_type()); } catch (CImgIOException&) { try { load_other(filename); } catch (CImgIOException&) { cimg::exception_mode() = omode; throw CImgIOException(_cimg_instance "load(): Failed to recognize format of file '%s'.", cimg_instance, filename); } } } cimg::exception_mode() = omode; return *this; } //! Load image from a file \newinstance. static CImg<T> get_load(const char *const filename) { return CImg<T>().load(filename); } //! Load image from an ascii file. /** \param filename Filename, as a C -string. **/ CImg<T>& load_ascii(const char *const filename) { return _load_ascii(0,filename); } //! Load image from an ascii file \inplace. static CImg<T> get_load_ascii(const char *const filename) { return CImg<T>().load_ascii(filename); } //! Load image from an ascii file \overloading. CImg<T>& load_ascii(std::FILE *const file) { return _load_ascii(file,0); } //! Loadimage from an ascii file \newinstance. static CImg<T> get_load_ascii(std::FILE *const file) { return CImg<T>().load_ascii(file); } CImg<T>& _load_ascii(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_ascii(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); char line[256] = { 0 }; int err = std::fscanf(nfile,"%255[^\n]",line); unsigned int dx = 0, dy = 1, dz = 1, dc = 1; std::sscanf(line,"%u%*c%u%*c%u%*c%u",&dx,&dy,&dz,&dc); err = std::fscanf(nfile,"%*[^0-9.eE+-]"); if (!dx || !dy || !dz || !dc) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_ascii(): Invalid ascii header in file '%s', image dimensions are set to (%u,%u,%u,%u).", cimg_instance, filename?filename:"(FILE*)",dx,dy,dz,dc); } assign(dx,dy,dz,dc); const unsigned long siz = size(); unsigned long off = 0; double val; T *ptr = _data; for (err = 1, off = 0; off<siz && err==1; ++off) { err = std::fscanf(nfile,"%lf%*[^0-9.eE+-]",&val); *(ptr++) = (T)val; } if (err!=1) cimg::warn(_cimg_instance "load_ascii(): Only %lu/%lu values read from file '%s'.", cimg_instance, off-1,siz,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a DLM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dlm(const char *const filename) { return _load_dlm(0,filename); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(const char *const filename) { return CImg<T>().load_dlm(filename); } //! Load image from a DLM file \overloading. CImg<T>& load_dlm(std::FILE *const file) { return _load_dlm(file,0); } //! Load image from a DLM file \newinstance. static CImg<T> get_load_dlm(std::FILE *const file) { return CImg<T>().load_dlm(file); } CImg<T>& _load_dlm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_dlm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); char delimiter[256] = { 0 }, tmp[256] = { 0 }; unsigned int cdx = 0, dx = 0, dy = 0; int err = 0; double val; assign(256,256); while ((err = std::fscanf(nfile,"%lf%255[^0-9.+-]",&val,delimiter))>0) { if (err>0) (*this)(cdx++,dy) = (T)val; if (cdx>=_width) resize(3*_width/2,_height,1,1,0); char c = 0; if (!std::sscanf(delimiter,"%255[^\n]%c",tmp,&c) || c=='\n') { dx = cimg::max(cdx,dx); if (++dy>=_height) resize(_width,3*_height/2,1,1,0); cdx = 0; } } if (cdx && err==1) { dx = cdx; ++dy; } if (!dx || !dy) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_dlm(): Invalid DLM file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } resize(dx,dy,1,1,0); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a BMP file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_bmp(const char *const filename) { return _load_bmp(0,filename); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(const char *const filename) { return CImg<T>().load_bmp(filename); } //! Load image from a BMP file \overloading. CImg<T>& load_bmp(std::FILE *const file) { return _load_bmp(file,0); } //! Load image from a BMP file \newinstance. static CImg<T> get_load_bmp(std::FILE *const file) { return CImg<T>().load_bmp(file); } CImg<T>& _load_bmp(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_bmp(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); unsigned char header[64] = { 0 }; cimg::fread(header,54,nfile); if (*header!='B' || header[1]!='M') { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_bmp(): Invalid BMP file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read header and pixel buffer int file_size = header[0x02] + (header[0x03]<<8) + (header[0x04]<<16) + (header[0x05]<<24), offset = header[0x0A] + (header[0x0B]<<8) + (header[0x0C]<<16) + (header[0x0D]<<24), dx = header[0x12] + (header[0x13]<<8) + (header[0x14]<<16) + (header[0x15]<<24), dy = header[0x16] + (header[0x17]<<8) + (header[0x18]<<16) + (header[0x19]<<24), compression = header[0x1E] + (header[0x1F]<<8) + (header[0x20]<<16) + (header[0x21]<<24), nb_colors = header[0x2E] + (header[0x2F]<<8) + (header[0x30]<<16) + (header[0x31]<<24), bpp = header[0x1C] + (header[0x1D]<<8); if (!file_size || file_size==offset) { std::fseek(nfile,0,SEEK_END); file_size = (int)std::ftell(nfile); std::fseek(nfile,54,SEEK_SET); } const int cimg_iobuffer = 12*1024*1024, dx_bytes = (bpp==1)?(dx/8+(dx%8?1:0)):((bpp==4)?(dx/2+(dx%2?1:0)):(dx*bpp/8)), align_bytes = (4-dx_bytes%4)%4, buf_size = cimg::min(cimg::abs(dy)*(dx_bytes + align_bytes),file_size - offset); CImg<intT> colormap; if (bpp<16) { if (!nb_colors) nb_colors = 1<<bpp; } else nb_colors = 0; if (nb_colors) { colormap.assign(nb_colors); cimg::fread(colormap._data,nb_colors,nfile); } const int xoffset = offset - 54 - 4*nb_colors; if (xoffset>0) std::fseek(nfile,xoffset,SEEK_CUR); CImg<ucharT> buffer; if (buf_size<cimg_iobuffer) { buffer.assign(buf_size); cimg::fread(buffer._data,buf_size,nfile); } else buffer.assign(dx_bytes + align_bytes); unsigned char *ptrs = buffer; // Decompress buffer (if necessary) if (compression) { if (file) throw CImgIOException(_cimg_instance "load_bmp(): Unable to load compressed data from '(*FILE)' inputs.", cimg_instance); else { if (!file) cimg::fclose(nfile); return load_other(filename); } } // Read pixel data assign(dx,cimg::abs(dy),1,3); switch (bpp) { case 1 : { // Monochrome for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0x80, val = 0; cimg_forX(*this,x) { if (mask==0x80) val = *(ptrs++); const unsigned char *col = (unsigned char*)(colormap._data + (val&mask?1:0)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask); } ptrs+=align_bytes; } } break; case 4 : { // 16 colors for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } unsigned char mask = 0xF0, val = 0; cimg_forX(*this,x) { if (mask==0xF0) val = *(ptrs++); const unsigned char color = (unsigned char)((mask<16)?(val&mask):((val&mask)>>4)); const unsigned char *col = (unsigned char*)(colormap._data + color); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); mask = cimg::ror(mask,4); } ptrs+=align_bytes; } } break; case 8 : { // 256 colors for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char *col = (unsigned char*)(colormap._data + *(ptrs++)); (*this)(x,y,2) = (T)*(col++); (*this)(x,y,1) = (T)*(col++); (*this)(x,y,0) = (T)*(col++); } ptrs+=align_bytes; } } break; case 16 : { // 16 bits colors for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { const unsigned char c1 = *(ptrs++), c2 = *(ptrs++); const unsigned short col = (unsigned short)(c1|(c2<<8)); (*this)(x,y,2) = (T)(col&0x1F); (*this)(x,y,1) = (T)((col>>5)&0x1F); (*this)(x,y,0) = (T)((col>>10)&0x1F); } ptrs+=align_bytes; } } break; case 24 : { // 24 bits colors for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); } ptrs+=align_bytes; } } break; case 32 : { // 32 bits colors for (int y = height()-1; y>=0; --y) { if (buf_size>=cimg_iobuffer) { cimg::fread(ptrs=buffer._data,dx_bytes,nfile); std::fseek(nfile,align_bytes,SEEK_CUR); } cimg_forX(*this,x) { (*this)(x,y,2) = (T)*(ptrs++); (*this)(x,y,1) = (T)*(ptrs++); (*this)(x,y,0) = (T)*(ptrs++); ++ptrs; } ptrs+=align_bytes; } } break; } if (dy<0) mirror('y'); if (!file) cimg::fclose(nfile); return *this; } //! Load image from a JPEG file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_jpeg(const char *const filename) { return _load_jpeg(0,filename); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(const char *const filename) { return CImg<T>().load_jpeg(filename); } //! Load image from a JPEG file \overloading. CImg<T>& load_jpeg(std::FILE *const file) { return _load_jpeg(file,0); } //! Load image from a JPEG file \newinstance. static CImg<T> get_load_jpeg(std::FILE *const file) { return CImg<T>().load_jpeg(file); } // Custom error handler for libjpeg. #ifdef cimg_use_jpeg struct _cimg_error_mgr { struct jpeg_error_mgr original; jmp_buf setjmp_buffer; char message[JMSG_LENGTH_MAX]; }; typedef struct _cimg_error_mgr *_cimg_error_ptr; METHODDEF(void) _cimg_jpeg_error_exit(j_common_ptr cinfo) { _cimg_error_ptr c_err = (_cimg_error_ptr) cinfo->err; // Return control to the setjmp point (*cinfo->err->format_message)(cinfo,c_err->message); jpeg_destroy(cinfo); // Clean memory and temp files. longjmp(c_err->setjmp_buffer,1); } #endif CImg<T>& _load_jpeg(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_jpeg(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_jpeg if (file) throw CImgIOException(_cimg_instance "load_jpeg(): Unable to load data from '(FILE*)' unless libjpeg is enabled.", cimg_instance); else return load_other(filename); #else struct jpeg_decompress_struct cinfo; struct _cimg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr.original); jerr.original.error_exit = _cimg_jpeg_error_exit; if (setjmp(jerr.setjmp_buffer)) { // JPEG error throw CImgIOException(_cimg_instance "load_jpeg(): Error message returned by libjpeg: %s.", cimg_instance,jerr.message); } std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo,nfile); jpeg_read_header(&cinfo,TRUE); jpeg_start_decompress(&cinfo); if (cinfo.output_components!=1 && cinfo.output_components!=3 && cinfo.output_components!=4) { if (!file) return load_other(filename); else throw CImgIOException(_cimg_instance "load_jpeg(): Failed to load JPEG data from file '%s'.", cimg_instance,filename?filename:"(FILE*)"); } CImg<ucharT> buffer(cinfo.output_width*cinfo.output_components); JSAMPROW row_pointer[1]; assign(cinfo.output_width,cinfo.output_height,1,cinfo.output_components); T *ptr_r = _data, *ptr_g = _data + 1UL*_width*_height, *ptr_b = _data + 2UL*_width*_height, *ptr_a = _data + 3UL*_width*_height; while (cinfo.output_scanline<cinfo.output_height) { *row_pointer = buffer._data; if (jpeg_read_scanlines(&cinfo,row_pointer,1)!=1) { cimg::warn(_cimg_instance "load_jpeg(): Incomplete data in file '%s'.", cimg_instance,filename?filename:"(FILE*)"); break; } const unsigned char *ptrs = buffer._data; switch (_spectrum) { case 1 : { cimg_forX(*this,x) *(ptr_r++) = (T)*(ptrs++); } break; case 3 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } break; case 4 : { cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } break; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a file, using Magick++ library. /** \param filename Filename, as a C-string. **/ // Added April/may 2006 by Christoph Hormann <[email protected]> // This is experimental code, not much tested, use with care. CImg<T>& load_magick(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_magick(): Specified filename is (null).", cimg_instance); #ifdef cimg_use_magick Magick::Image image(filename); const unsigned int W = image.size().width(), H = image.size().height(); switch (image.type()) { case Magick::PaletteMatteType : case Magick::TrueColorMatteType : case Magick::ColorSeparationType : { assign(W,H,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (unsigned long off = (unsigned long)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; case Magick::PaletteType : case Magick::TrueColorType : { assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (unsigned long off = (unsigned long)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_g++) = (T)(pixels->green); *(ptr_b++) = (T)(pixels->blue); ++pixels; } } break; case Magick::GrayscaleMatteType : { assign(W,H,1,2); T *ptr_r = data(0,0,0,0), *ptr_a = data(0,0,0,1); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (unsigned long off = (unsigned long)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); *(ptr_a++) = (T)(pixels->opacity); ++pixels; } } break; default : { assign(W,H,1,1); T *ptr_r = data(0,0,0,0); Magick::PixelPacket *pixels = image.getPixels(0,0,W,H); for (unsigned long off = (unsigned long)W*H; off; --off) { *(ptr_r++) = (T)(pixels->red); ++pixels; } } } #else throw CImgIOException(_cimg_instance "load_magick(): Unable to load file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif return *this; } //! Load image from a file, using Magick++ library \newinstance. static CImg<T> get_load_magick(const char *const filename) { return CImg<T>().load_magick(filename); } //! Load image from a PNG file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_png(const char *const filename) { return _load_png(0,filename); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(const char *const filename) { return CImg<T>().load_png(filename); } //! Load image from a PNG file \overloading. CImg<T>& load_png(std::FILE *const file) { return _load_png(file,0); } //! Load image from a PNG file \newinstance. static CImg<T> get_load_png(std::FILE *const file) { return CImg<T>().load_png(file); } // (Note: Most of this function has been written by Eric Fausett) CImg<T>& _load_png(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_png(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_png if (file) throw CImgIOException(_cimg_instance "load_png(): Unable to load data from '(FILE*)' unless libpng is enabled.", cimg_instance); else return load_other(filename); #else // Open file and check for PNG validity const char *volatile nfilename = filename; // two 'volatile' here to remove a g++ warning due to 'setjmp'. std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"rb"); unsigned char pngCheck[8] = { 0 }; cimg::fread(pngCheck,8,(std::FILE*)nfile); if (png_sig_cmp(pngCheck,0,8)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Invalid PNG file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Setup PNG structures for read png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,user_error_ptr,user_error_fn,user_warning_fn); if (!png_ptr) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'png_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,(png_infopp)0,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'info_ptr' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Failed to initialize 'end_info' structure for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } // Error handling callback for png file reading if (setjmp(png_jmpbuf(png_ptr))) { if (!file) cimg::fclose((std::FILE*)nfile); png_destroy_read_struct(&png_ptr, &end_info, (png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Encountered unknown fatal error in libpng for file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); png_set_sig_bytes(png_ptr, 8); // Get PNG Header Info up to data block png_read_info(png_ptr,info_ptr); png_uint_32 W, H; int bit_depth, color_type, interlace_type; bool is_gray = false; png_get_IHDR(png_ptr,info_ptr,&W,&H,&bit_depth,&color_type,&interlace_type,(int*)0,(int*)0); // Transforms to unify image data if (color_type==PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); color_type = PNG_COLOR_TYPE_RGB; bit_depth = 8; } if (color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8) { png_set_expand_gray_1_2_4_to_8(png_ptr); is_gray = true; bit_depth = 8; } if (png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)) { png_set_tRNS_to_alpha(png_ptr); color_type |= PNG_COLOR_MASK_ALPHA; } if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); color_type |= PNG_COLOR_MASK_COLOR; is_gray = true; } if (color_type==PNG_COLOR_TYPE_RGB) png_set_filler(png_ptr,0xffffU,PNG_FILLER_AFTER); png_read_update_info(png_ptr,info_ptr); if (bit_depth!=8 && bit_depth!=16) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid bit depth %u in file '%s'.", cimg_instance, bit_depth,nfilename?nfilename:"(FILE*)"); } const int byte_depth = bit_depth>>3; // Allocate Memory for Image Read png_bytep *const imgData = new png_bytep[H]; for (unsigned int row = 0; row<H; ++row) imgData[row] = new png_byte[byte_depth*4*W]; png_read_image(png_ptr,imgData); png_read_end(png_ptr,end_info); // Read pixel data if (color_type!=PNG_COLOR_TYPE_RGB && color_type!=PNG_COLOR_TYPE_RGB_ALPHA) { if (!file) cimg::fclose(nfile); png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0); throw CImgIOException(_cimg_instance "load_png(): Invalid color coding type %u in file '%s'.", cimg_instance, color_type,nfilename?nfilename:"(FILE*)"); } const bool is_alpha = (color_type==PNG_COLOR_TYPE_RGBA); assign(W,H,1,(is_gray?1:3) + (is_alpha?1:0)); T *ptr_r = data(0,0,0,0), *ptr_g = is_gray?0:data(0,0,0,1), *ptr_b = is_gray?0:data(0,0,0,2), *ptr_a = !is_alpha?0:data(0,0,0,is_gray?1:3); switch (bit_depth) { case 8 : { cimg_forY(*this,y) { const unsigned char *ptrs = (unsigned char*)imgData[y]; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; case 16 : { cimg_forY(*this,y) { const unsigned short *ptrs = (unsigned short*)(imgData[y]); if (!cimg::endianness()) cimg::invert_endianness(ptrs,4*_width); cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs; if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs; if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs; } } } break; } png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); // Deallocate Image Read Memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Load image from a PNM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pnm(const char *const filename) { return _load_pnm(0,filename); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(const char *const filename) { return CImg<T>().load_pnm(filename); } //! Load image from a PNM file \overloading. CImg<T>& load_pnm(std::FILE *const file) { return _load_pnm(file,0); } //! Load image from a PNM file \newinstance. static CImg<T> get_load_pnm(std::FILE *const file) { return CImg<T>().load_pnm(file); } CImg<T>& _load_pnm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pnm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); unsigned int ppm_type, W, H, D = 1, colormax = 255; char item[1024] = { 0 }; int err, rval, gval, bval; const long cimg_iobuffer = 12*1024*1024; while ((err=std::fscanf(nfile,"%1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (std::sscanf(item," P%u",&ppm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=std::sscanf(item," %u %u %u %u",&W,&H,&D,&colormax))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): WIDTH and HEIGHT fields undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (ppm_type!=1 && ppm_type!=4) { if (err==2 || (err==3 && (ppm_type==5 || ppm_type==7 || ppm_type==8 || ppm_type==9))) { while ((err=std::fscanf(nfile," %1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (std::sscanf(item,"%u",&colormax)!=1) cimg::warn(_cimg_instance "load_pnm(): COLORMAX field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } else { colormax = D; D = 1; } } std::fgetc(nfile); switch (ppm_type) { case 1 : { // 2d b&w ascii. assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)(rval?0:255); else break; } } break; case 2 : { // 2d grey ascii. assign(W,H,1,1); T* ptrd = _data; cimg_foroff(*this,off) { if (std::fscanf(nfile,"%d",&rval)>0) *(ptrd++) = (T)rval; else break; } } break; case 3 : { // 2d color ascii. assign(W,H,1,3); T *ptrd = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forXY(*this,x,y) { if (std::fscanf(nfile,"%d %d %d",&rval,&gval,&bval)==3) { *(ptrd++) = (T)rval; *(ptr_g++) = (T)gval; *(ptr_b++) = (T)bval; } else break; } } break; case 4 : { // 2d b&w binary (support 3D PINK extension). CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); unsigned int w = 0, h = 0, d = 0; for (long to_read = (long)((W/8 + (W%8?1:0))*H*D); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; unsigned char mask = 0, val = 0; for (unsigned long off = (unsigned long)raw._width; off || mask; mask>>=1) { if (!mask) { if (off--) val = *(ptrs++); mask = 128; } *(ptrd++) = (T)((val&mask)?0:255); if (++w==W) { w = 0; mask = 0; if (++h==H) { h = 0; if (++d==D) break; }} } } } break; case 5 : case 7 : { // 2d/3d grey binary (support 3D PINK extension). if (colormax<256) { // 8 bits. CImg<ucharT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } else { // 16 bits. CImg<ushortT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } } break; case 6 : { // 2d color binary. if (colormax<256) { // 8 bits. CImg<ucharT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { // 16 bits. CImg<ushortT> raw; assign(W,H,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (long to_read = (int)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer/2)); cimg::fread(raw._data,raw._width,nfile); if (!cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); to_read-=raw._width; const unsigned short *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width/3; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } } break; case 8 : { // 2d/3d grey binary with int32 integers (PINK extension). CImg<intT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const int *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; case 9 : { // 2d/3d grey binary with float values (PINK extension). CImg<floatT> raw; assign(W,H,D,1); T *ptrd = data(0,0,0,0); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const float *ptrs = raw._data; for (unsigned long off = (unsigned long)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); } } break; default : assign(); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pnm(): PNM type 'P%d' found, but type is not supported.", cimg_instance, filename?filename:"(FILE*)",ppm_type); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PFM file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pfm(const char *const filename) { return _load_pfm(0,filename); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(const char *const filename) { return CImg<T>().load_pfm(filename); } //! Load image from a PFM file \overloading. CImg<T>& load_pfm(std::FILE *const file) { return _load_pfm(file,0); } //! Load image from a PFM file \newinstance. static CImg<T> get_load_pfm(std::FILE *const file) { return CImg<T>().load_pfm(file); } CImg<T>& _load_pfm(std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pfm(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); char pfm_type, item[1024] = { 0 }; int W = 0, H = 0, err = 0; double scale = 0; while ((err=std::fscanf(nfile,"%1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (std::sscanf(item," P%c",&pfm_type)!=1) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): PFM header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } while ((err=std::fscanf(nfile," %1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if ((err=std::sscanf(item," %d %d",&W,&H))<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pfm(): WIDTH and HEIGHT fields are undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (err==2) { while ((err=std::fscanf(nfile," %1023[^\n]",item))!=EOF && (*item=='#' || !err)) std::fgetc(nfile); if (std::sscanf(item,"%lf",&scale)!=1) cimg::warn(_cimg_instance "load_pfm(): SCALE field is undefined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } std::fgetc(nfile); const bool is_color = (pfm_type=='F'), is_inverted = (scale>0)!=cimg::endianness(); if (is_color) { assign(W,H,1,3,0); CImg<floatT> buf(3*W); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); cimg_forY(*this,y) { cimg::fread(buf._data,3*W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,3*W); const float *ptrs = buf._data; cimg_forX(*this,x) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } } else { assign(W,H,1,1,0); CImg<floatT> buf(W); T *ptrd = data(0,0,0,0); cimg_forY(*this,y) { cimg::fread(buf._data,W,nfile); if (is_inverted) cimg::invert_endianness(buf._data,W); const float *ptrs = buf._data; cimg_forX(*this,x) *(ptrd++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return mirror('y'); // Most of the .pfm files are flipped along the y-axis. } //! Load image from a RGB file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(0,filename,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(filename,dimw,dimh); } //! Load image from a RGB file \overloading. CImg<T>& load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgb(file,0,dimw,dimh); } //! Load image from a RGB file \newinstance. static CImg<T> get_load_rgb(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgb(file,dimw,dimh); } CImg<T>& _load_rgb(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgb(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const long cimg_iobuffer = 12*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,3); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (unsigned long off = raw._width/3UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a RGBA file. /** \param filename Filename, as a C-string. \param dimw Width of the image buffer. \param dimh Height of the image buffer. **/ CImg<T>& load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(0,filename,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(filename,dimw,dimh); } //! Load image from a RGBA file \overloading. CImg<T>& load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return _load_rgba(file,0,dimw,dimh); } //! Load image from a RGBA file \newinstance. static CImg<T> get_load_rgba(std::FILE *const file, const unsigned int dimw, const unsigned int dimh=1) { return CImg<T>().load_rgba(file,dimw,dimh); } CImg<T>& _load_rgba(std::FILE *const file, const char *const filename, const unsigned int dimw, const unsigned int dimh) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_rgba(): Specified filename is (null).", cimg_instance); if (!dimw || !dimh) return assign(); const long cimg_iobuffer = 12*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); CImg<ucharT> raw; assign(dimw,dimh,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); for (long to_read = (long)size(); to_read>0; ) { raw.assign(cimg::min(to_read,cimg_iobuffer)); cimg::fread(raw._data,raw._width,nfile); to_read-=raw._width; const unsigned char *ptrs = raw._data; for (unsigned long off = raw._width/4UL; off; --off) { *(ptr_r++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_b++) = (T)*(ptrs++); *(ptr_a++) = (T)*(ptrs++); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a TIFF file. /** \param filename Filename, as a C-string. \param first_frame First frame to read (for multi-pages tiff). \param last_frame Last frame to read (for multi-pages tiff). \param step_frame Step value of frame reading. \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compilation time the function uses CImg<T>& load_other(const char*). **/ CImg<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { if (!filename) throw CImgArgumentException(_cimg_instance "load_tiff(): Specified filename is (null).", cimg_instance); const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff if (nfirst_frame || nlast_frame!=~0U || nstep_frame>1) throw CImgArgumentException(_cimg_instance "load_tiff(): Unable to read sub-images from file '%s' unless libtiff is enabled.", cimg_instance, filename); return load_other(filename); #else TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimg_instance "load_tiff(): File '%s' contains %u image(s) while specified frame range is [%u,%u] (step %u).", cimg_instance, filename,nb_images,nfirst_frame,nlast_frame,nstep_frame); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images-1; TIFFSetDirectory(tif,0); CImg<T> frame; for (unsigned int l = nfirst_frame; l<=nlast_frame; l+=nstep_frame) { frame._load_tiff(tif,l); if (l==nfirst_frame) assign(frame._width,frame._height,1+(nlast_frame-nfirst_frame)/nstep_frame,frame._spectrum); if (frame._width>_width || frame._height>_height || frame._spectrum>_spectrum) resize(cimg::max(frame._width,_width),cimg::max(frame._height,_height),-100,cimg::max(frame._spectrum,_spectrum),0); draw_image(0,0,(l-nfirst_frame)/nstep_frame,frame); } TIFFClose(tif); } else throw CImgIOException(_cimg_instance "load_tiff(): Failed to open file '%s'.", cimg_instance, filename); return *this; #endif } //! Load image from a TIFF file \newinstance. static CImg<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { return CImg<T>().load_tiff(filename,first_frame,last_frame,step_frame); } // (Original contribution by Jerome Boulanger). #ifdef cimg_use_tiff template<typename t> void _load_tiff_tiled_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,0)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<cimg::min((unsigned int)(row+th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<cimg::min((unsigned int)(col+tw),(unsigned int)nx); ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,rr,vv) = (T)(ptr[(rr-row)*th*samplesperpixel + (cc-col)*samplesperpixel + vv]); } _TIFFfree(buf); } } template<typename t> void _load_tiff_tiled_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny, const uint32 tw, const uint32 th) { t *const buf = (t*)_TIFFmalloc(TIFFTileSize(tif)); if (buf) { for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (unsigned int row = 0; row<ny; row+=th) for (unsigned int col = 0; col<nx; col+=tw) { if (TIFFReadTile(tif,buf,col,row,0,vv)<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid tile in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = row; rr<cimg::min((unsigned int)(row+th),(unsigned int)ny); ++rr) for (unsigned int cc = col; cc<cimg::min((unsigned int)(col+tw),(unsigned int)nx); ++cc) (*this)(cc,rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_contig(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row+rowsperstrip>ny?ny-row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, 0); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) for (unsigned int vv = 0; vv<samplesperpixel; ++vv) (*this)(cc,row+rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } template<typename t> void _load_tiff_separate(TIFF *const tif, const uint16 samplesperpixel, const uint32 nx, const uint32 ny) { t *buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { uint32 row, rowsperstrip = (uint32)-1; TIFFGetField(tif,TIFFTAG_ROWSPERSTRIP,&rowsperstrip); for (unsigned int vv = 0; vv<samplesperpixel; ++vv) for (row = 0; row<ny; row+= rowsperstrip) { uint32 nrow = (row+rowsperstrip>ny?ny-row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif, row, vv); if ((TIFFReadEncodedStrip(tif,strip,buf,-1))<0) { _TIFFfree(buf); TIFFClose(tif); throw CImgIOException(_cimg_instance "load_tiff(): Invalid strip in file '%s'.", cimg_instance, TIFFFileName(tif)); } const t *ptr = buf; for (unsigned int rr = 0;rr<nrow; ++rr) for (unsigned int cc = 0; cc<nx; ++cc) (*this)(cc,row+rr,vv) = (T)*(ptr++); } _TIFFfree(buf); } } CImg<T>& _load_tiff(TIFF *const tif, const unsigned int directory) { if (!TIFFSetDirectory(tif,directory)) return assign(); uint16 samplesperpixel, bitspersample, photo; uint16 sampleformat = SAMPLEFORMAT_UINT; uint32 nx,ny; const char *const filename = TIFFFileName(tif); TIFFGetField(tif,TIFFTAG_IMAGEWIDTH,&nx); TIFFGetField(tif,TIFFTAG_IMAGELENGTH,&ny); TIFFGetField(tif,TIFFTAG_SAMPLESPERPIXEL,&samplesperpixel); TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sampleformat); TIFFGetFieldDefaulted(tif,TIFFTAG_BITSPERSAMPLE,&bitspersample); TIFFGetField(tif,TIFFTAG_PHOTOMETRIC,&photo); int spectrum = samplesperpixel; if (photo == 3) spectrum = 3; assign(nx,ny,1,spectrum); if ((photo < 3) && ( bitspersample!=8 || !(samplesperpixel==3 || samplesperpixel==4))) { uint16 config; TIFFGetField(tif,TIFFTAG_PLANARCONFIG,&config); if (TIFFIsTiled(tif)) { uint32 tw, th; TIFFGetField(tif,TIFFTAG_TILEWIDTH,&tw); TIFFGetField(tif,TIFFTAG_TILELENGTH,&th); if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : { if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<signed char>(tif,samplesperpixel,nx,ny,tw,th); } break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_contig<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_contig<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_contig<float>(tif,samplesperpixel,nx,ny,tw,th); break; } else switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned char>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<signed char>(tif,samplesperpixel,nx,ny,tw,th); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned short>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<short>(tif,samplesperpixel,nx,ny,tw,th); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_tiled_separate<unsigned int>(tif,samplesperpixel,nx,ny,tw,th); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_tiled_separate<int>(tif,samplesperpixel,nx,ny,tw,th); else _load_tiff_tiled_separate<float>(tif,samplesperpixel,nx,ny,tw,th); break; } } else { if (config==PLANARCONFIG_CONTIG) switch (bitspersample) { case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_contig<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_contig<int>(tif,samplesperpixel,nx,ny); else _load_tiff_contig<float>(tif,samplesperpixel,nx,ny); break; } else switch (bitspersample){ case 8 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned char>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<signed char>(tif,samplesperpixel,nx,ny); break; case 16 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned short>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<short>(tif,samplesperpixel,nx,ny); break; case 32 : if (sampleformat==SAMPLEFORMAT_UINT) _load_tiff_separate<unsigned int>(tif,samplesperpixel,nx,ny); else if (sampleformat==SAMPLEFORMAT_INT) _load_tiff_separate<int>(tif,samplesperpixel,nx,ny); else _load_tiff_separate<float>(tif,samplesperpixel,nx,ny); break; } } } else { uint32 *const raster = (uint32*)_TIFFmalloc(nx*ny*sizeof(uint32)); if (!raster) { _TIFFfree(raster); TIFFClose(tif); throw CImgException(_cimg_instance "load_tiff(): Failed to allocate memory (%s) for file '%s'.", cimg_instance, cimg::strbuffersize(nx*ny*sizeof(uint32)),filename); } TIFFReadRGBAImage(tif,nx,ny,raster,0); switch (spectrum) { case 1 : { cimg_forXY(*this,x,y) (*this)(x,y) = (T)(float)((raster[nx*(ny-1-y)+x] + 128)/257); } break; case 3 : { cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny-1-y)+x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny-1-y)+x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny-1-y)+x]); } } break; case 4 : { cimg_forXY(*this,x,y) { (*this)(x,y,0) = (T)(float)TIFFGetR(raster[nx*(ny-1-y)+x]); (*this)(x,y,1) = (T)(float)TIFFGetG(raster[nx*(ny-1-y)+x]); (*this)(x,y,2) = (T)(float)TIFFGetB(raster[nx*(ny-1-y)+x]); (*this)(x,y,3) = (T)(float)TIFFGetA(raster[nx*(ny-1-y)+x]); } } break; } _TIFFfree(raster); } return *this; } #endif //! Load image from a MINC2 file. /** \param filename Filename, as a C-string. **/ // (Original code by Haz-Edine Assemlal). CImg<T>& load_minc2(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_minc2(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_minc2 return load_other(filename); #else minc::minc_1_reader rdr; rdr.open(filename); assign(rdr.ndim(1)?rdr.ndim(1):1, rdr.ndim(2)?rdr.ndim(2):1, rdr.ndim(3)?rdr.ndim(3):1, rdr.ndim(4)?rdr.ndim(4):1); if(typeid(T)==typeid(unsigned char)) rdr.setup_read_byte(); else if(typeid(T)==typeid(int)) rdr.setup_read_int(); else if(typeid(T)==typeid(double)) rdr.setup_read_double(); else rdr.setup_read_float(); minc::load_standard_volume(rdr, this->_data); return *this; #endif } //! Load image from a MINC2 file \newinstance. static CImg<T> get_load_minc2(const char *const filename) { return CImg<T>().load_analyze(filename); } //! Load image from an ANALYZE7.5/NIFTI file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_analyze(const char *const filename, float *const voxel_size=0) { return _load_analyze(0,filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_analyze(filename,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \overloading. CImg<T>& load_analyze(std::FILE *const file, float *const voxel_size=0) { return _load_analyze(file,0,voxel_size); } //! Load image from an ANALYZE7.5/NIFTI file \newinstance. static CImg<T> get_load_analyze(std::FILE *const file, float *const voxel_size=0) { return CImg<T>().load_analyze(file,voxel_size); } CImg<T>& _load_analyze(std::FILE *const file, const char *const filename, float *const voxel_size=0) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_analyze(): Specified filename is (null).", cimg_instance); std::FILE *nfile_header = 0, *nfile = 0; if (!file) { char body[1024] = { 0 }; const char *const ext = cimg::split_filename(filename,body); if (!cimg::strcasecmp(ext,"hdr")) { // File is an Analyze header file. nfile_header = cimg::fopen(filename,"rb"); std::sprintf(body + std::strlen(body),".img"); nfile = cimg::fopen(body,"rb"); } else if (!cimg::strcasecmp(ext,"img")) { // File is an Analyze data file. nfile = cimg::fopen(filename,"rb"); std::sprintf(body + std::strlen(body),".hdr"); nfile_header = cimg::fopen(body,"rb"); } else nfile_header = nfile = cimg::fopen(filename,"rb"); // File is a Niftii file. } else nfile_header = nfile = file; // File is a Niftii file. if (!nfile || !nfile_header) throw CImgIOException(_cimg_instance "load_analyze(): Invalid Analyze7.5 or NIFTI header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); // Read header. bool endian = false; unsigned int header_size; cimg::fread(&header_size,1,nfile_header); if (!header_size) throw CImgIOException(_cimg_instance "load_analyze(): Invalid zero-sized header in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (header_size>=4096) { endian = true; cimg::invert_endianness(header_size); } unsigned char *const header = new unsigned char[header_size]; cimg::fread(header+4,header_size-4,nfile_header); if (!file && nfile_header!=nfile) cimg::fclose(nfile_header); if (endian) { cimg::invert_endianness((short*)(header+40),5); cimg::invert_endianness((short*)(header+70),1); cimg::invert_endianness((short*)(header+72),1); cimg::invert_endianness((float*)(header+76),4); cimg::invert_endianness((float*)(header+112),1); } unsigned short *dim = (unsigned short*)(header+40), dimx = 1, dimy = 1, dimz = 1, dimv = 1; if (!dim[0]) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with zero dimensions.", cimg_instance, filename?filename:"(FILE*)"); if (dim[0]>4) cimg::warn(_cimg_instance "load_analyze(): File '%s' defines an image with %u dimensions, reading only the 4 first.", cimg_instance, filename?filename:"(FILE*)",dim[0]); if (dim[0]>=1) dimx = dim[1]; if (dim[0]>=2) dimy = dim[2]; if (dim[0]>=3) dimz = dim[3]; if (dim[0]>=4) dimv = dim[4]; float scalefactor = *(float*)(header+112); if (scalefactor==0) scalefactor=1; const unsigned short datatype = *(short*)(header+70); if (voxel_size) { const float *vsize = (float*)(header+76); voxel_size[0] = vsize[1]; voxel_size[1] = vsize[2]; voxel_size[2] = vsize[3]; } delete[] header; // Read pixel data. assign(dimx,dimy,dimz,dimv); switch (datatype) { case 2 : { unsigned char *const buffer = new unsigned char[dimx*dimy*dimz*dimv]; cimg::fread(buffer,dimx*dimy*dimz*dimv,nfile); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 4 : { short *const buffer = new short[dimx*dimy*dimz*dimv]; cimg::fread(buffer,dimx*dimy*dimz*dimv,nfile); if (endian) cimg::invert_endianness(buffer,dimx*dimy*dimz*dimv); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 8 : { int *const buffer = new int[dimx*dimy*dimz*dimv]; cimg::fread(buffer,dimx*dimy*dimz*dimv,nfile); if (endian) cimg::invert_endianness(buffer,dimx*dimy*dimz*dimv); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 16 : { float *const buffer = new float[dimx*dimy*dimz*dimv]; cimg::fread(buffer,dimx*dimy*dimz*dimv,nfile); if (endian) cimg::invert_endianness(buffer,dimx*dimy*dimz*dimv); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; case 64 : { double *const buffer = new double[dimx*dimy*dimz*dimv]; cimg::fread(buffer,dimx*dimy*dimz*dimv,nfile); if (endian) cimg::invert_endianness(buffer,dimx*dimy*dimz*dimv); cimg_foroff(*this,off) _data[off] = (T)(buffer[off]*scalefactor); delete[] buffer; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_analyze(): Unable to load datatype %d in file '%s'", cimg_instance, datatype,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a .cimg[z] file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(const char *const filename, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,axis,align); } //! Load image from a .cimg[z] file \overloading. CImg<T>& load_cimg(std::FILE *const file, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a .cimg[z] file \newinstance static CImg<T> get_load_cimg(std::FILE *const file, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,axis,align); } //! Load sub-images of a .cimg file. /** \param filename Filename, as a C-string. \param n0 Starting frame. \param n1 Ending frame. \param x0 X-coordinate of the starting sub-image vertex. \param y0 Y-coordinate of the starting sub-image vertex. \param z0 Z-coordinate of the starting sub-image vertex. \param c0 C-coordinate of the starting sub-image vertex. \param x1 X-coordinate of the ending sub-image vertex. \param y1 Y-coordinate of the ending sub-image vertex. \param z1 Z-coordinate of the ending sub-image vertex. \param c1 C-coordinate of the ending sub-image vertex. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load sub-images of a .cimg file \overloading. CImg<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { CImgList<T> list; list.load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load sub-images of a .cimg file \newinstance. static CImg<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1, const char axis='z', const float align=0) { return CImg<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1,axis,align); } //! Load image from an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param[out] voxel_size Pointer to the three voxel sizes read from the file. **/ CImg<T>& load_inr(const char *const filename, float *const voxel_size=0) { return _load_inr(0,filename,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(const char *const filename, float *const voxel_size=0) { return CImg<T>().load_inr(filename,voxel_size); } //! Load image from an INRIMAGE-4 file \overloading. CImg<T>& load_inr(std::FILE *const file, float *const voxel_size=0) { return _load_inr(file,0,voxel_size); } //! Load image from an INRIMAGE-4 file \newinstance. static CImg<T> get_load_inr(std::FILE *const file, float *voxel_size=0) { return CImg<T>().load_inr(file,voxel_size); } static void _load_inr_header(std::FILE *file, int out[8], float *const voxel_size) { char item[1024] = { 0 }, tmp1[64] = { 0 }, tmp2[64] = { 0 }; out[0] = std::fscanf(file,"%63s",item); out[0] = out[1] = out[2] = out[3] = out[5] = 1; out[4] = out[6] = out[7] = -1; if(cimg::strncasecmp(item,"#INRIMAGE-4#{",13)!=0) throw CImgIOException("CImg<%s>::load_inr(): INRIMAGE-4 header not found.", pixel_type()); while (std::fscanf(file," %63[^\n]%*c",item)!=EOF && std::strncmp(item,"##}",3)) { std::sscanf(item," XDIM%*[^0-9]%d",out); std::sscanf(item," YDIM%*[^0-9]%d",out+1); std::sscanf(item," ZDIM%*[^0-9]%d",out+2); std::sscanf(item," VDIM%*[^0-9]%d",out+3); std::sscanf(item," PIXSIZE%*[^0-9]%d",out+6); if (voxel_size) { std::sscanf(item," VX%*[^0-9.+-]%f",voxel_size); std::sscanf(item," VY%*[^0-9.+-]%f",voxel_size+1); std::sscanf(item," VZ%*[^0-9.+-]%f",voxel_size+2); } if (std::sscanf(item," CPU%*[ =]%s",tmp1)) out[7]=cimg::strncasecmp(tmp1,"sun",3)?0:1; switch (std::sscanf(item," TYPE%*[ =]%s %s",tmp1,tmp2)) { case 0 : break; case 2 : out[5] = cimg::strncasecmp(tmp1,"unsigned",8)?1:0; std::strncpy(tmp1,tmp2,sizeof(tmp1)-1); case 1 : if (!cimg::strncasecmp(tmp1,"int",3) || !cimg::strncasecmp(tmp1,"fixed",5)) out[4] = 0; if (!cimg::strncasecmp(tmp1,"float",5) || !cimg::strncasecmp(tmp1,"double",6)) out[4] = 1; if (!cimg::strncasecmp(tmp1,"packed",6)) out[4] = 2; if (out[4]>=0) break; default : throw CImgIOException("CImg<%s>::load_inr(): Invalid pixel type '%s' defined in header.", pixel_type(), tmp2); } } if(out[0]<0 || out[1]<0 || out[2]<0 || out[3]<0) throw CImgIOException("CImg<%s>::load_inr(): Invalid dimensions (%d,%d,%d,%d) defined in header.", pixel_type(), out[0],out[1],out[2],out[3]); if(out[4]<0 || out[5]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete pixel type defined in header.", pixel_type()); if(out[6]<0) throw CImgIOException("CImg<%s>::load_inr(): Incomplete PIXSIZE field defined in header.", pixel_type()); if(out[7]<0) throw CImgIOException("CImg<%s>::load_inr(): Big/Little Endian coding type undefined in header.", pixel_type()); } CImg<T>& _load_inr(std::FILE *const file, const char *const filename, float *const voxel_size) { #define _cimg_load_inr_case(Tf,sign,pixsize,Ts) \ if (!loaded && fopt[6]==pixsize && fopt[4]==Tf && fopt[5]==sign) { \ Ts *xval, *const val = new Ts[fopt[0]*fopt[3]]; \ cimg_forYZ(*this,y,z) { \ cimg::fread(val,fopt[0]*fopt[3],nfile); \ if (fopt[7]!=endian) cimg::invert_endianness(val,fopt[0]*fopt[3]); \ xval = val; cimg_forX(*this,x) cimg_forC(*this,c) (*this)(x,y,z,c) = (T)*(xval++); \ } \ delete[] val; \ loaded = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_inr(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); int fopt[8], endian=cimg::endianness()?1:0; bool loaded = false; if (voxel_size) voxel_size[0] = voxel_size[1] = voxel_size[2] = 1; _load_inr_header(nfile,fopt,voxel_size); assign(fopt[0],fopt[1],fopt[2],fopt[3]); _cimg_load_inr_case(0,0,8,unsigned char); _cimg_load_inr_case(0,1,8,char); _cimg_load_inr_case(0,0,16,unsigned short); _cimg_load_inr_case(0,1,16,short); _cimg_load_inr_case(0,0,32,unsigned int); _cimg_load_inr_case(0,1,32,int); _cimg_load_inr_case(1,0,32,float); _cimg_load_inr_case(1,1,32,float); _cimg_load_inr_case(1,0,64,double); _cimg_load_inr_case(1,1,64,double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_inr(): Unknown pixel type defined in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a EXR file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_exr(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_exr(): Specified filename is (null).", cimg_instance); #ifndef cimg_use_openexr return load_other(filename); #else Imf::RgbaInputFile file(filename); Imath::Box2i dw = file.dataWindow(); const int inwidth = dw.max.x - dw.min.x + 1, inheight = dw.max.y - dw.min.y + 1; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase(inheight,inwidth); file.setFrameBuffer(&pixels[0][0] - dw.min.x - dw.min.y*inwidth, 1, inwidth); file.readPixels(dw.min.y, dw.max.y); assign(inwidth,inheight,1,4); T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3); cimg_forXY(*this,x,y) { *(ptr_r++) = (T)pixels[y][x].r; *(ptr_g++) = (T)pixels[y][x].g; *(ptr_b++) = (T)pixels[y][x].b; *(ptr_a++) = (T)pixels[y][x].a; } return *this; #endif } //! Load image from a EXR file \newinstance. static CImg<T> get_load_exr(const char *const filename) { return CImg<T>().load_exr(filename); } //! Load image from a PANDORE-5 file. /** \param filename Filename, as a C-string. **/ CImg<T>& load_pandore(const char *const filename) { return _load_pandore(0,filename); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(const char *const filename) { return CImg<T>().load_pandore(filename); } //! Load image from a PANDORE-5 file \overloading. CImg<T>& load_pandore(std::FILE *const file) { return _load_pandore(file,0); } //! Load image from a PANDORE-5 file \newinstance. static CImg<T> get_load_pandore(std::FILE *const file) { return CImg<T>().load_pandore(file); } CImg<T>& _load_pandore(std::FILE *const file, const char *const filename) { #define __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,ndim,stype) \ cimg::fread(dims,nbdim,nfile); \ if (endian) cimg::invert_endianness(dims,nbdim); \ assign(nwidth,nheight,ndepth,ndim); \ const unsigned int siz = size(); \ stype *buffer = new stype[siz]; \ cimg::fread(buffer,siz,nfile); \ if (endian) cimg::invert_endianness(buffer,siz); \ T *ptrd = _data; \ cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); \ buffer-=siz; \ delete[] buffer #define _cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1,stype2,stype3,ltype) { \ if (sizeof(stype1)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype1); } \ else if (sizeof(stype2)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype2); } \ else if (sizeof(stype3)==ltype) { __cimg_load_pandore_case(nbdim,nwidth,nheight,ndepth,dim,stype3); } \ else throw CImgIOException(_cimg_instance \ "load_pandore(): Unknown pixel datatype in file '%s'.", \ cimg_instance, \ filename?filename:"(FILE*)"); } if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_pandore(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); char header[32] = { 0 }; cimg::fread(header,12,nfile); if (cimg::strncasecmp("PANDORE",header,7)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): PANDORE header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } unsigned int imageid, dims[8] = { 0 }; cimg::fread(&imageid,1,nfile); const bool endian = (imageid>255); if (endian) cimg::invert_endianness(imageid); cimg::fread(header,20,nfile); switch (imageid) { case 2: _cimg_load_pandore_case(2,dims[1],1,1,1,unsigned char,unsigned char,unsigned char,1); break; case 3: _cimg_load_pandore_case(2,dims[1],1,1,1,long,int,short,4); break; case 4: _cimg_load_pandore_case(2,dims[1],1,1,1,double,float,float,4); break; case 5: _cimg_load_pandore_case(3,dims[2],dims[1],1,1,unsigned char,unsigned char,unsigned char,1); break; case 6: _cimg_load_pandore_case(3,dims[2],dims[1],1,1,long,int,short,4); break; case 7: _cimg_load_pandore_case(3,dims[2],dims[1],1,1,double,float,float,4); break; case 8: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,unsigned char,unsigned char,unsigned char,1); break; case 9: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,long,int,short,4); break; case 10: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],1,double,float,float,4); break; case 11 : { // Region 1d cimg::fread(dims,3,nfile); if (endian) cimg::invert_endianness(dims,3); assign(dims[1],1,1,1); const unsigned siz = size(); if (dims[2]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[2]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 12 : { // Region 2d cimg::fread(dims,4,nfile); if (endian) cimg::invert_endianness(dims,4); assign(dims[2],dims[1],1,1); const unsigned int siz = size(); if (dims[3]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[3]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned long *buffer = new unsigned long[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 13 : { // Region 3d cimg::fread(dims,5,nfile); if (endian) cimg::invert_endianness(dims,5); assign(dims[3],dims[2],dims[1],1); const unsigned int siz = size(); if (dims[4]<256) { unsigned char *buffer = new unsigned char[siz]; cimg::fread(buffer,siz,nfile); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { if (dims[4]<65536) { unsigned short *buffer = new unsigned short[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } else { unsigned int *buffer = new unsigned int[siz]; cimg::fread(buffer,siz,nfile); if (endian) cimg::invert_endianness(buffer,siz); T *ptrd = _data; cimg_foroff(*this,off) *(ptrd++) = (T)*(buffer++); buffer-=siz; delete[] buffer; } } } break; case 16: _cimg_load_pandore_case(4,dims[2],dims[1],1,3,unsigned char,unsigned char,unsigned char,1); break; case 17: _cimg_load_pandore_case(4,dims[2],dims[1],1,3,long,int,short,4); break; case 18: _cimg_load_pandore_case(4,dims[2],dims[1],1,3,double,float,float,4); break; case 19: _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,unsigned char,unsigned char,unsigned char,1); break; case 20: _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,long,int,short,4); break; case 21: _cimg_load_pandore_case(5,dims[3],dims[2],dims[1],3,double,float,float,4); break; case 22: _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 23: _cimg_load_pandore_case(2,dims[1],1,1,dims[0],long,int,short,4); case 24: _cimg_load_pandore_case(2,dims[1],1,1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 25: _cimg_load_pandore_case(2,dims[1],1,1,dims[0],double,float,float,4); break; case 26: _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned char,unsigned char,unsigned char,1); break; case 27: _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],long,int,short,4); break; case 28: _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],unsigned long,unsigned int,unsigned short,4); break; case 29: _cimg_load_pandore_case(3,dims[2],dims[1],1,dims[0],double,float,float,4); break; case 30: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned char,unsigned char,unsigned char,1); break; case 31: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],long,int,short,4); break; case 32: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],unsigned long,unsigned int,unsigned short,4); break; case 33: _cimg_load_pandore_case(4,dims[3],dims[2],dims[1],dims[0],double,float,float,4); break; case 34 : { // Points 1d int ptbuf[4] = { 0 }; cimg::fread(ptbuf,1,nfile); if (endian) cimg::invert_endianness(ptbuf,1); assign(1); (*this)(0) = (T)ptbuf[0]; } break; case 35 : { // Points 2d int ptbuf[4] = { 0 }; cimg::fread(ptbuf,2,nfile); if (endian) cimg::invert_endianness(ptbuf,2); assign(2); (*this)(0) = (T)ptbuf[1]; (*this)(1) = (T)ptbuf[0]; } break; case 36 : { // Points 3d int ptbuf[4] = { 0 }; cimg::fread(ptbuf,3,nfile); if (endian) cimg::invert_endianness(ptbuf,3); assign(3); (*this)(0) = (T)ptbuf[2]; (*this)(1) = (T)ptbuf[1]; (*this)(2) = (T)ptbuf[0]; } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_pandore(): Unable to load data with ID_type %u in file '%s'.", cimg_instance, imageid,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load image from a PAR-REC (Philips) file. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_parrec(const char *const filename, const char axis='c', const float align=0) { CImgList<T> list; list.load_parrec(filename); if (list._width==1) return list[0].move_to(*this); return assign(list.get_append(axis,align)); } //! Load image from a PAR-REC (Philips) file \newinstance. static CImg<T> get_load_parrec(const char *const filename, const char axis='c', const float align=0) { return CImg<T>().load_parrec(filename,axis,align); } //! Load image from a raw binary file. /** \param filename Filename, as a C-string. \param size_x Width of the image buffer. \param size_y Height of the image buffer. \param size_z Depth of the image buffer. \param size_c Spectrum of the image buffer. \param is_multiplexed Tells if the image values are multiplexed along the C-axis. \param invert_endianness Tells if the endianness of the image buffer must be inverted. **/ CImg<T>& load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false) { return _load_raw(0,filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(const char *const filename, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false) { return CImg<T>().load_raw(filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness); } //! Load image from a raw binary file \overloading. CImg<T>& load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false) { return _load_raw(file,0,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness); } //! Load image from a raw binary file \newinstance. static CImg<T> get_load_raw(std::FILE *const file, const unsigned int size_x=0, const unsigned int size_y=1, const unsigned int size_z=1, const unsigned int size_c=1, const bool is_multiplexed=false, const bool invert_endianness=false) { return CImg<T>().load_raw(file,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness); } CImg<T>& _load_raw(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c, const bool is_multiplexed, const bool invert_endianness) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_raw(): Specified filename is (null).", cimg_instance); unsigned int siz = size_x*size_y*size_z*size_c, _size_x = size_x, _size_y = size_y, _size_z = size_z, _size_c = size_c; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); if (!siz) { // Retrieve file size. const long fpos = std::ftell(nfile); if (fpos<0) throw CImgArgumentException(_cimg_instance "load_raw(): Cannot determine size of input file '%s'.", cimg_instance,filename?filename:"(FILE*)"); std::fseek(nfile,0,SEEK_END); siz = _size_y = (unsigned int)std::ftell(nfile)/sizeof(T); _size_x = _size_z = _size_c = 1; std::fseek(nfile,fpos,SEEK_SET); } assign(_size_x,_size_y,_size_z,_size_c,0); if (!is_multiplexed || size_c==1) { cimg::fread(_data,siz,nfile); if (invert_endianness) cimg::invert_endianness(_data,siz); } else { CImg<T> buf(1,1,1,_size_c); cimg_forXYZ(*this,x,y,z) { cimg::fread(buf._data,_size_c,nfile); if (invert_endianness) cimg::invert_endianness(buf._data,_size_c); set_vector_at(buf,x,y,z); } } if (!file) cimg::fclose(nfile); return *this; } //! Load image sequence using FFMPEG av's libraries. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param pixel_format To be documented. \param resume To be documented. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_ffmpeg(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool pixel_format=true, const bool resume=false, const char axis='z', const float align=0) { return get_load_ffmpeg(filename,first_frame,last_frame,step_frame,pixel_format,resume,axis,align).move_to(*this); } //! Load image sequence using FFMPEG av's libraries \newinstance. static CImg<T> get_load_ffmpeg(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool pixel_format=true, const bool resume=false, const char axis='z', const float align=0) { return CImgList<T>().load_ffmpeg(filename,first_frame,last_frame,step_frame,pixel_format,resume).get_append(axis,align); } //! Load image sequence from a YUV file. /** \param filename Filename, as a C-string. \param size_x Width of the frames. \param size_y Height of the frames. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param yuv2rgb Tells if the YUV to RGB transform must be applied. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. **/ CImg<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(filename,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(filename,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load image sequence from a YUV file \overloading. CImg<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return get_load_yuv(file,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this); } //! Load image sequence from a YUV file \newinstance. static CImg<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') { return CImgList<T>().load_yuv(file,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb).get_append(axis); } //! Load 3d object from a .OFF file. /** \param[out] primitives Primitives data of the 3d object. \param[out] colors Colors data of the 3d object. \param filename Filename, as a C-string. **/ template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return _load_off(primitives,colors,0,filename); } //! Load 3d object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, const char *const filename) { return CImg<T>().load_off(primitives,colors,filename); } //! Load 3d object from a .OFF file \overloading. template<typename tf, typename tc> CImg<T>& load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return _load_off(primitives,colors,file,0); } //! Load 3d object from a .OFF file \newinstance. template<typename tf, typename tc> static CImg<T> get_load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file) { return CImg<T>().load_off(primitives,colors,file); } template<typename tf, typename tc> CImg<T>& _load_off(CImgList<tf>& primitives, CImgList<tc>& colors, std::FILE *const file, const char *const filename) { if (!file && !filename) throw CImgArgumentException(_cimg_instance "load_off(): Specified filename is (null).", cimg_instance); std::FILE *const nfile = file?file:cimg::fopen(filename,"r"); unsigned int nb_points = 0, nb_primitives = 0, nb_read = 0; char line[256] = { 0 }; int err; // Skip comments, and read magic string OFF do { err = std::fscanf(nfile,"%255[^\n] ",line); } while (!err || (err==1 && *line=='#')); if (cimg::strncasecmp(line,"OFF",3) && cimg::strncasecmp(line,"COFF",4)) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): OFF header not found in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } do { err = std::fscanf(nfile,"%255[^\n] ",line); } while (!err || (err==1 && *line=='#')); if ((err = std::sscanf(line,"%u%u%*[^\n] ",&nb_points,&nb_primitives))!=2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Invalid number of vertices or primitives specified in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } // Read points data assign(nb_points,3); float X = 0, Y = 0, Z = 0; cimg_forX(*this,l) { do { err = std::fscanf(nfile,"%255[^\n] ",line); } while (!err || (err==1 && *line=='#')); if ((err = std::sscanf(line,"%f%f%f%*[^\n] ",&X,&Y,&Z))!=3) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "load_off(): Failed to read vertex %u/%u in file '%s'.", cimg_instance, l+1,nb_points,filename?filename:"(FILE*)"); } (*this)(l,0) = (T)X; (*this)(l,1) = (T)Y; (*this)(l,2) = (T)Z; } // Read primitive data primitives.assign(); colors.assign(); bool stopflag = false; while (!stopflag) { float c0 = 0.7f, c1 = 0.7f, c2 = 0.7f; unsigned int prim = 0, i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0; *line = 0; if ((err = std::fscanf(nfile,"%u",&prim))!=1) stopflag=true; else { ++nb_read; switch (prim) { case 1 : { if ((err = std::fscanf(nfile,"%u%255[^\n] ",&i0,line))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 2 : { if ((err = std::fscanf(nfile,"%u%u%255[^\n] ",&i0,&i1,line))<2) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 3 : { if ((err = std::fscanf(nfile,"%u%u%u%255[^\n] ",&i0,&i1,&i2,line))<3) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 4 : { if ((err = std::fscanf(nfile,"%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,line))<4) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255)).move_to(colors); } } break; case 5 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,line))<5) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 6 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,line))<6) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); colors.insert(2,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++nb_primitives; } } break; case 7 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,line))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i4,i3,i1).move_to(primitives); CImg<tf>::vector(i0,i6,i5,i4).move_to(primitives); CImg<tf>::vector(i3,i2,i1).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; case 8 : { if ((err = std::fscanf(nfile,"%u%u%u%u%u%u%u%u%255[^\n] ",&i0,&i1,&i2,&i3,&i4,&i5,&i6,&i7,line))<7) { cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u from file '%s'.", cimg_instance, nb_read,nb_primitives,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } else { err = std::sscanf(line,"%f%f%f",&c0,&c1,&c2); CImg<tf>::vector(i0,i3,i2,i1).move_to(primitives); CImg<tf>::vector(i0,i5,i4,i3).move_to(primitives); CImg<tf>::vector(i0,i7,i6,i5).move_to(primitives); colors.insert(3,CImg<tc>::vector((tc)(c0*255),(tc)(c1*255),(tc)(c2*255))); ++(++nb_primitives); } } break; default : cimg::warn(_cimg_instance "load_off(): Failed to read primitive %u/%u (%u vertices) from file '%s'.", cimg_instance, nb_read,nb_primitives,prim,filename?filename:"(FILE*)"); err = std::fscanf(nfile,"%*[^\n] "); } } } if (!file) cimg::fclose(nfile); if (primitives._width!=nb_primitives) cimg::warn(_cimg_instance "load_off(): Only %u/%u primitives read from file '%s'.", cimg_instance, primitives._width,nb_primitives,filename?filename:"(FILE*)"); return *this; } //! Load image sequence using FFMPEG's external tool 'ffmpeg'. /** \param filename Filename, as a C-string. \param axis Appending axis, if file contains multiple images. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T>& load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return get_load_ffmpeg_external(filename,axis,align).move_to(*this); } //! Load image sequence using FFMPEG's external tool 'ffmpeg' \newinstance. static CImg<T> get_load_ffmpeg_external(const char *const filename, const char axis='z', const float align=0) { return CImgList<T>().load_ffmpeg_external(filename).get_append(axis,align); } //! Load image using GraphicsMagick's external tool 'gm'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_graphicsmagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_graphicsmagick_external(): Specified filename is (null).", cimg_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file = 0; #if cimg_OS==1 cimg_snprintf(command,sizeof(command),"%s convert \"%s\" pnm:-",cimg::graphicsmagick_path(),filename); file = popen(command,"r"); if (file) { try { load_pnm(file); } catch (...) { pclose(file); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' with external command 'gm'.", cimg_instance, filename); } pclose(file); return *this; } #endif do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.pnm",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s convert \"%s\" \"%s\"",cimg::graphicsmagick_path(),filename,filetmp); cimg::system(command,cimg::graphicsmagick_path()); if (!(file = std::fopen(filetmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_graphicsmagick_external(): Failed to load file '%s' with external command 'gm'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filetmp); std::remove(filetmp); return *this; } //! Load image using GraphicsMagick's external tool 'gm' \newinstance. static CImg<T> get_load_graphicsmagick_external(const char *const filename) { return CImg<T>().load_graphicsmagick_external(filename); } //! Load gzipped image file, using external tool 'gunzip'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimg_instance "load_gzip_external(): Specified filename is (null).", cimg_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; const char *const ext = cimg::split_filename(filename,body), *const ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s -c \"%s\" > %s",cimg::gunzip_path(),filename,filetmp); cimg::system(command); if (!(file = std::fopen(filetmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_gzip_external(): Failed to load file '%s' with external command 'gunzip'.", cimg_instance, filename); } else cimg::fclose(file); load(filetmp); std::remove(filetmp); return *this; } //! Load gzipped image file, using external tool 'gunzip' \newinstance. static CImg<T> get_load_gzip_external(const char *const filename) { return CImg<T>().load_gzip_external(filename); } //! Load image using ImageMagick's external tool 'convert'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_imagemagick_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_imagemagick_external(): Specified filename is (null).", cimg_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file = 0; #if cimg_OS==1 cimg_snprintf(command,sizeof(command),"%s \"%s\" pnm:-",cimg::imagemagick_path(),filename); file = popen(command,"r"); if (file) { try { load_pnm(file); } catch (...) { pclose(file); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with external command 'convert'.", cimg_instance, filename); } pclose(file); return *this; } #endif do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.pnm",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s \"%s\" \"%s\"",cimg::imagemagick_path(),filename,filetmp); cimg::system(command,cimg::imagemagick_path()); if (!(file = std::fopen(filetmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_imagemagick_external(): Failed to load file '%s' with external command 'convert'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filetmp); std::remove(filetmp); return *this; } //! Load image using ImageMagick's external tool 'convert' \newinstance. static CImg<T> get_load_imagemagick_external(const char *const filename) { return CImg<T>().load_imagemagick_external(filename); } //! Load image from a DICOM file, using XMedcon's external tool 'medcon'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_medcon_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_medcon_external(): Specified filename is (null).", cimg_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; cimg::fclose(cimg::fopen(filename,"r")); std::FILE *file = 0; do { cimg_snprintf(filetmp,sizeof(filetmp),"%s.hdr",cimg::filenamerand()); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s -w -c anlz -o %s -f %s",cimg::medcon_path(),filetmp,filename); cimg::system(command); cimg::split_filename(filetmp,body); cimg_snprintf(command,sizeof(command),"%s.hdr",body); file = std::fopen(command,"rb"); if (!file) { cimg_snprintf(command,sizeof(command),"m000-%s.hdr",body); file = std::fopen(command,"rb"); if (!file) { throw CImgIOException(_cimg_instance "load_medcon_external(): Failed to load file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); load_analyze(command); std::remove(command); cimg::split_filename(command,body); cimg_snprintf(command,sizeof(command),"%s.img",body); std::remove(command); return *this; } //! Load image from a DICOM file, using XMedcon's external tool 'medcon' \newinstance. static CImg<T> get_load_medcon_external(const char *const filename) { return CImg<T>().load_medcon_external(filename); } //! Load image from a RAW Color Camera file, using external tool 'dcraw'. /** \param filename Filename, as a C-string. **/ CImg<T>& load_dcraw_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_dcraw_external(): Specified filename is (null).", cimg_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file = 0; #if cimg_OS==1 cimg_snprintf(command,sizeof(command),"%s -w -4 -c \"%s\"",cimg::dcraw_path(),filename); file = popen(command,"r"); if (file) { try { load_pnm(file); } catch (...) { pclose(file); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } pclose(file); return *this; } #endif do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.ppm",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s -w -4 -c \"%s\" > %s",cimg::dcraw_path(),filename,filetmp); cimg::system(command,cimg::dcraw_path()); if (!(file = std::fopen(filetmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "load_dcraw_external(): Failed to load file '%s' with external command 'dcraw'.", cimg_instance, filename); } else cimg::fclose(file); load_pnm(filetmp); std::remove(filetmp); return *this; } //! Load image from a RAW Color Camera file, using external tool 'dcraw' \newinstance. static CImg<T> get_load_dcraw_external(const char *const filename) { return CImg<T>().load_dcraw_external(filename); } //! Load image from a camera stream, using OpenCV. /** \param camera_index Index of the camera to capture images from. \param skip_frames Number of frames to skip before the capture. \param release_camera Tells if the camera ressource must be released at the end of the method. **/ CImg<T>& load_camera(const int camera_index=-1, const unsigned int skip_frames=0, const bool release_camera=false) { #ifdef cimg_use_opencv const int ind = camera_index + 1; if (ind<0 || ind>255) throw CImgArgumentException(_cimg_instance "load_camera(): Invalid request for camera #%d.", cimg_instance, camera_index); static CvCapture *capture[256] = { 0 }; if (release_camera) { if (capture[ind]) cvReleaseCapture(&(capture[ind])); capture[ind] = 0; return *this; } if (!capture[ind]) { capture[ind] = cvCreateCameraCapture(camera_index); if (!capture[ind]) { if (camera_index>=0) throw CImgIOException(_cimg_instance "load_camera(): Failed to initialize camera #%d.", cimg_instance, camera_index); else throw CImgIOException(_cimg_instance "load_camera(): Failed to initialize default camera.", cimg_instance); } } const IplImage *img = 0; for (unsigned int i = 0; i<skip_frames; ++i) img = cvQueryFrame(capture[ind]); img = cvQueryFrame(capture[ind]); if (img) { const int step = (int)(img->widthStep - 3*img->width); assign(img->width,img->height,1,3); const unsigned char* ptrs = (unsigned char*)img->imageData; T *ptr_r = data(0,0,0,0), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2); if (step>0) cimg_forY(*this,y) { cimg_forX(*this,x) { *(ptr_b++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_r++) = (T)*(ptrs++); } ptrs+=step; } else for (unsigned long siz = (unsigned long)img->width*img->height; siz; --siz) { *(ptr_b++) = (T)*(ptrs++); *(ptr_g++) = (T)*(ptrs++); *(ptr_r++) = (T)*(ptrs++); } } #else cimg::unused(camera_index,skip_frames,release_camera); throw CImgIOException(_cimg_instance "load_camera(): This function requires the OpenCV library to run " "(macro 'cimg_use_opencv' must be defined).", cimg_instance); #endif return *this; } //! Load image from a camera stream, using OpenCV \newinstance. static CImg<T> get_load_camera(const int camera_index=-1, const unsigned int skip_frames=0, const bool release_camera=false) { return CImg<T>().load_camera(camera_index,skip_frames,release_camera); } //! Load image using various non-native ways. /** \param filename Filename, as a C-string. **/ CImg<T>& load_other(const char *const filename) { if (!filename) throw CImgArgumentException(_cimg_instance "load_other(): Specified filename is (null).", cimg_instance); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { load_magick(filename); } catch (CImgException&) { try { load_imagemagick_external(filename); } catch (CImgException&) { try { load_graphicsmagick_external(filename); } catch (CImgException&) { try { load_cimg(filename); } catch (CImgException&) { try { std::fclose(cimg::fopen(filename,"rb")); cimg::exception_mode() = omode; throw CImgIOException(_cimg_instance "load_other(): Failed to recognize format of file '%s'.", cimg_instance, filename); } catch (CImgException&) { cimg::exception_mode() = omode; throw CImgIOException(_cimg_instance "load_other(): Failed to open file '%s'.", cimg_instance, filename); } } } } } cimg::exception_mode() = omode; return *this; } //! Load image using various non-native ways \newinstance. static CImg<T> get_load_other(const char *const filename) { return CImg<T>().load_other(filename); } //@} //--------------------------- // //! \name Data Output //@{ //--------------------------- //! Display informations about the image data on the standard error output. /** \param title Name for the considered image. \param display_stats Tells to compute and display image statistics. **/ const CImg<T>& print(const char *const title=0, const bool display_stats=true) const { int xm = 0, ym = 0, zm = 0, vm = 0, xM = 0, yM = 0, zM = 0, vM = 0; static CImg<doubleT> st; if (!is_empty() && display_stats) { st = get_stats(); xm = (int)st[4]; ym = (int)st[5], zm = (int)st[6], vm = (int)st[7]; xM = (int)st[8]; yM = (int)st[9], zM = (int)st[10], vM = (int)st[11]; } const unsigned long siz = size(), msiz = siz*sizeof(T), siz1 = siz-1, mdisp = msiz<8*1024?0:(msiz<8*1024*1024?1:2), width1 = _width-1; char _title[64] = { 0 }; if (!title) cimg_snprintf(_title,sizeof(_title),"CImg<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = (%u,%u,%u,%u) [%lu %s], %sdata%s = (%s*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_height,_depth,_spectrum, mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20)), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p (%s) = [ ",(void*)((char*)end()-1),_is_shared?"shared":"non-shared"); else std::fprintf(cimg::output()," (%s) = [ ",_is_shared?"shared":"non-shared"); if (!is_empty()) cimg_foroff(*this,off) { std::fprintf(cimg::output(),cimg::type<T>::format(),cimg::type<T>::format(_data[off])); if (off!=siz1) std::fprintf(cimg::output(),"%s",off%_width==width1?" ; ":" "); if (off==7 && siz>16) { off = siz1-8; if (off!=7) std::fprintf(cimg::output(),"... "); } } if (!is_empty() && display_stats) std::fprintf(cimg::output()," ], %smin%s = %g, %smax%s = %g, %smean%s = %g, %sstd%s = %g, %scoords_min%s = (%u,%u,%u,%u), %scoords_max%s = (%u,%u,%u,%u).\n", cimg::t_bold,cimg::t_normal,st[0], cimg::t_bold,cimg::t_normal,st[1], cimg::t_bold,cimg::t_normal,st[2], cimg::t_bold,cimg::t_normal,std::sqrt(st[3]), cimg::t_bold,cimg::t_normal,xm,ym,zm,vm, cimg::t_bold,cimg::t_normal,xM,yM,zM,vM); else std::fprintf(cimg::output(),"%s].\n",is_empty()?"":" "); std::fflush(cimg::output()); return *this; } //! Display image into a CImgDisplay window. /** \param disp Display window. **/ const CImg<T>& display(CImgDisplay& disp) const { disp.display(*this); return *this; } //! Display image into a CImgDisplay window, in an interactive way. /** \param disp Display window. \param display_info Tells if image informations are displayed on the standard output. **/ const CImg<T>& display(CImgDisplay &disp, const bool display_info, unsigned int *const XYZ=0) const { return _display(disp,0,display_info,XYZ,false); } //! Display image into an interactive window. /** \param title Window title \param display_info Tells if image informations are displayed on the standard output. **/ const CImg<T>& display(const char *const title=0, const bool display_info=true, unsigned int *const XYZ=0) const { CImgDisplay disp; return _display(disp,title,display_info,XYZ,false); } const CImg<T>& _display(CImgDisplay &disp, const char *const title, const bool display_info, unsigned int *const XYZ, const bool exit_on_simpleclick) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "display(): Empty instance.", cimg_instance); unsigned int oldw = 0, oldh = 0, _XYZ[3], key = 0; int x0 = 0, y0 = 0, z0 = 0, x1 = width() - 1, y1 = height() - 1, z1 = depth() - 1; if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,1); if (!title) disp.set_title("CImg<%s> (%ux%ux%ux%u)",pixel_type(),_width,_height,_depth,_spectrum); } else if (title) disp.set_title("%s",title); disp.show().flush(); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(dtitle); CImg<T> zoom; for (bool reset_view = true, resize_disp = false, is_first_select = true; !key && !disp.is_closed(); ) { if (reset_view) { if (XYZ) { _XYZ[0] = XYZ[0]; _XYZ[1] = XYZ[1]; _XYZ[2] = XYZ[2]; } else { _XYZ[0] = (x0 + x1)/2; _XYZ[1] = (y0 + y1)/2; _XYZ[2] = (z0 + z1)/2; } x0 = 0; y0 = 0; z0 = 0; x1 = _width - 1; y1 = _height-1; z1 = _depth-1; oldw = disp.width(); oldh = disp.height(); reset_view = false; } if (!x0 && !y0 && !z0 && x1==width()-1 && y1==height()-1 && z1==depth()-1) zoom.assign(); else zoom = get_crop(x0,y0,z0,x1,y1,z1); const unsigned int dx = 1 + x1 - x0, dy = 1 + y1 - y0, dz = 1 + z1 - z0, tw = dx + (dz>1?dz:0), th = dy + (dz>1?dz:0); if (!disp.is_fullscreen() && resize_disp) { const unsigned int ttw = tw*disp.width()/oldw, tth = th*disp.height()/oldh, dM = cimg::max(ttw,tth), diM = (unsigned int)cimg::max(disp.width(),disp.height()), imgw = cimg::max(16U,ttw*diM/dM), imgh = cimg::max(16U,tth*diM/dM); disp.set_fullscreen(false).resize(cimg_fitscreen(imgw,imgh,1),false); resize_disp = false; } oldw = tw; oldh = th; bool go_up = false, go_down = false, go_left = false, go_right = false, go_inc = false, go_dec = false, go_in = false, go_out = false, go_in_center = false; const CImg<T>& visu = zoom?zoom:*this; const CImg<intT> selection = visu._get_select(disp,0,2,_XYZ,x0,y0,z0,is_first_select); is_first_select = false; if (disp.wheel()) { if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { go_out = !(go_in = disp.wheel()>0); go_in_center = false; } else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) { go_right = !(go_left = disp.wheel()>0); } else if (disp.is_keyALT() || disp.is_keyALTGR() || _depth==1) { go_down = !(go_up = disp.wheel()>0); } disp.set_wheel(); } const int sx0 = selection(0), sy0 = selection(1), sz0 = selection(2), sx1 = selection(3), sy1 = selection(4), sz1 = selection(5); if (sx0>=0 && sy0>=0 && sz0>=0 && sx1>=0 && sy1>=0 && sz1>=0) { x1 = x0 + sx1; y1 = y0 + sy1; z1 = z0 + sz1; x0+=sx0; y0+=sy0; z0+=sz0; if (sx0==sx1 && sy0==sy1 && sz0==sz1) { if (exit_on_simpleclick && !zoom) break; else reset_view = true; } resize_disp = true; } else switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : case cimg::keySHIFTRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : case cimg::keyPAD5 : case cimg::keySHIFTLEFT : #if cimg_OS!=2 case cimg::keyALTGR : #endif case cimg::keyALT : key = 0; break; case cimg::keyP : if (visu._depth>1 && (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT())) { // Special mode: play stack of frames const unsigned int w1 = visu._width*disp.width()/(visu._width+(visu._depth>1?visu._depth:0)), h1 = visu._height*disp.height()/(visu._height+(visu._depth>1?visu._depth:0)); float frame_timing = 5; bool is_stopped = false; disp.set_key(key,false).set_wheel().resize(cimg_fitscreen(w1,h1,1),false); key = 0; for (unsigned int timer = 0; !key && !disp.is_closed() && !disp.button(); ) { if (disp.is_resized()) disp.resize(false); if (!timer) { visu.get_slice((int)_XYZ[2]).display(disp.set_title("%s | z=%d",dtitle.data(),_XYZ[2])); (++_XYZ[2])%=visu._depth; } if (!is_stopped) { if (++timer>(unsigned int)frame_timing) timer = 0; } else timer = ~0U; if (disp.wheel()) { frame_timing-=disp.wheel()/3.0f; disp.set_wheel(); } switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyPAGEUP : frame_timing-=0.3f; key = 0; break; case cimg::keyPAGEDOWN : frame_timing+=0.3f; key = 0; break; case cimg::keySPACE : is_stopped = !is_stopped; disp.set_key(key,false); key = 0; break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : is_stopped = true; timer = 0; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : is_stopped = true; (_XYZ[2]+=visu._depth-2)%=visu._depth; timer = 0; key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false); disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false).set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false).set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen().set_key(key,false); key = 0; } break; } frame_timing = frame_timing<1?1:(frame_timing>39?39:frame_timing); disp.wait(20); } const unsigned int w2 = (visu._width + (visu._depth>1?visu._depth:0))*disp.width()/visu._width, h2 = (visu._height + (visu._depth>1?visu._depth:0))*disp.height()/visu._height; disp.resize(cimg_fitscreen(w2,h2,1),false).set_title(dtitle.data()).set_key().set_button().set_wheel(); key = 0; } break; case cimg::keyHOME : reset_view = resize_disp = true; key = 0; break; case cimg::keyPADADD : go_in = true; go_in_center = true; key = 0; break; case cimg::keyPADSUB : go_out = true; key = 0; break; case cimg::keyARROWLEFT : case cimg::keyPAD4: go_left = true; key = 0; break; case cimg::keyARROWRIGHT : case cimg::keyPAD6: go_right = true; key = 0; break; case cimg::keyARROWUP : case cimg::keyPAD8: go_up = true; key = 0; break; case cimg::keyARROWDOWN : case cimg::keyPAD2: go_down = true; key = 0; break; case cimg::keyPAD7 : go_up = go_left = true; key = 0; break; case cimg::keyPAD9 : go_up = go_right = true; key = 0; break; case cimg::keyPAD1 : go_down = go_left = true; key = 0; break; case cimg::keyPAD3 : go_down = go_right = true; key = 0; break; case cimg::keyPAGEUP : go_inc = true; key = 0; break; case cimg::keyPAGEDOWN : go_dec = true; key = 0; break; } if (go_in) { const int mx = go_in_center?disp.width()/2:disp.mouse_x(), my = go_in_center?disp.height()/2:disp.mouse_y(), mX = mx*(_width+(_depth>1?_depth:0))/disp.width(), mY = my*(_height+(_depth>1?_depth:0))/disp.height(); int X = _XYZ[0], Y = _XYZ[1], Z = _XYZ[2]; if (mX<width() && mY<height()) { X = x0 + mX*(1+x1-x0)/_width; Y = y0 + mY*(1+y1-y0)/_height; Z = _XYZ[2]; } if (mX<width() && mY>=height()) { X = x0 + mX*(1+x1-x0)/_width; Z = z0 + (mY-_height)*(1+z1-z0)/_depth; Y = _XYZ[1]; } if (mX>=width() && mY<height()) { Y = y0 + mY*(1+y1-y0)/_height; Z = z0 + (mX-_width)*(1+z1-z0)/_depth; X = _XYZ[0]; } if (x1-x0>4) { x0 = X - 7*(X-x0)/8; x1 = X + 7*(x1-X)/8; } if (y1-y0>4) { y0 = Y - 7*(Y-y0)/8; y1 = Y + 7*(y1-Y)/8; } if (z1-z0>4) { z0 = Z - 7*(Z-z0)/8; z1 = Z + 7*(z1-Z)/8; } } if (go_out) { const int delta_x = (x1-x0)/8, delta_y = (y1-y0)/8, delta_z = (z1-z0)/8, ndelta_x = delta_x?delta_x:(_width>1?1:0), ndelta_y = delta_y?delta_y:(_height>1?1:0), ndelta_z = delta_z?delta_z:(_depth>1?1:0); x0-=ndelta_x; y0-=ndelta_y; z0-=ndelta_z; x1+=ndelta_x; y1+=ndelta_y; z1+=ndelta_z; if (x0<0) { x1-=x0; x0 = 0; if (x1>=width()) x1 = width() - 1; } if (y0<0) { y1-=y0; y0 = 0; if (y1>=height()) y1 = height() - 1; } if (z0<0) { z1-=z0; z0 = 0; if (z1>=depth()) z1 = depth() - 1; } if (x1>=width()) { x0-=(x1-width()+1); x1 = width()-1; if (x0<0) x0 = 0; } if (y1>=height()) { y0-=(y1-height()+1); y1 = height()-1; if (y0<0) y0 = 0; } if (z1>=depth()) { z0-=(z1-depth()+1); z1 = depth()-1; if (z0<0) z0 = 0; } } if (go_left) { const int delta = (x1-x0)/5, ndelta = delta?delta:(_width>1?1:0); if (x0-ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } } if (go_right) { const int delta = (x1-x0)/5, ndelta = delta?delta:(_width>1?1:0); if (x1+ndelta<width()) { x0+=ndelta; x1+=ndelta; } else { x0+=(width()-1-x1); x1 = width()-1; } } if (go_up) { const int delta = (y1-y0)/5, ndelta = delta?delta:(_height>1?1:0); if (y0-ndelta>=0) { y0-=ndelta; y1-=ndelta; } else { y1-=y0; y0 = 0; } } if (go_down) { const int delta = (y1-y0)/5, ndelta = delta?delta:(_height>1?1:0); if (y1+ndelta<height()) { y0+=ndelta; y1+=ndelta; } else { y0+=(height()-1-y1); y1 = height()-1; } } if (go_inc) { const int delta = (z1-z0)/5, ndelta = delta?delta:(_depth>1?1:0); if (z0-ndelta>=0) { z0-=ndelta; z1-=ndelta; } else { z1-=z0; z0 = 0; } } if (go_dec) { const int delta = (z1-z0)/5, ndelta = delta?delta:(_depth>1?1:0); if (z1+ndelta<depth()) { z0+=ndelta; z1+=ndelta; } else { z0+=(depth()-1-z1); z1 = depth()-1; } } disp.wait(100); } disp.set_key(key); if (XYZ) { XYZ[0] = _XYZ[0]; XYZ[1] = _XYZ[1]; XYZ[2] = _XYZ[2]; } return *this; } //! Display object 3d in an interactive window. /** \param disp Display window. \param vertices Vertices data of the 3d object. \param primitives Primitives data of the 3d object. \param colors Colors data of the 3d object. \param opacities Opacities data of the 3d object. \param centering Tells if the 3d object must be centered for the display. \param render_static Rendering mode. \param render_motion Rendering mode, when the 3d object is moved. \param is_double_sided Tells if the object primitives are double-sided. \param focale Focale \param light_x X-coordinate of the light source. \param light_y Y-coordinate of the light source. \param light_z Z-coordinate of the light source. \param specular_lightness Amount of specular light. \param specular_shininess Shininess of the object material. \param display_axes Tells if the 3d axes are displayed. \param pose_matrix Pointer to 12 values, defining a 3d pose (as a 4x3 matrix). **/ template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(CImgDisplay& disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return _display_object3d(disp,0,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp, typename tf, typename tc, typename to> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { CImgDisplay disp; return _display_object3d(disp,title,vertices,primitives,colors,opacities,centering,render_static, render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(disp,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp, typename tf, typename tc> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(title,vertices,primitives,colors,CImgList<floatT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(disp,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp, typename tf> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(title,vertices,primitives,CImgList<T>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(CImgDisplay &disp, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(disp,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } //! Display object 3d in an interactive window \simplification. template<typename tp> const CImg<T>& display_object3d(const char *const title, const CImg<tp>& vertices, const bool centering=true, const int render_static=4, const int render_motion=1, const bool is_double_sided=true, const float focale=500, const float light_x=0, const float light_y=0, const float light_z=-5000, const float specular_lightness=0.2f, const float specular_shininess=0.1f, const bool display_axes=true, float *const pose_matrix=0) const { return display_object3d(title,vertices,CImgList<uintT>(),centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } template<typename tp, typename tf, typename tc, typename to> const CImg<T>& _display_object3d(CImgDisplay& disp, const char *const title, const CImg<tp>& vertices, const CImgList<tf>& primitives, const CImgList<tc>& colors, const to& opacities, const bool centering, const int render_static, const int render_motion, const bool is_double_sided, const float focale, const float light_x, const float light_y, const float light_z, const float specular_lightness, const float specular_shininess, const bool display_axes, float *const pose_matrix) const { typedef typename cimg::superset<tp,float>::type tpfloat; // Check input arguments if (is_empty()) { if (disp) return CImg<T>(disp.width(),disp.height(),1,(colors && colors[0].size()==1)?1:3,0). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); else return CImg<T>(1,2,1,1,64,128).resize(cimg_fitscreen(640,480,1),1,(colors && colors[0].size()==1)?1:3,3). _display_object3d(disp,title,vertices,primitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } else { if (disp) disp.resize(*this,false); } char error_message[1024] = { 0 }; if (!vertices.is_object3d(primitives,colors,opacities,true,error_message)) throw CImgArgumentException(_cimg_instance "display_object3d(): Invalid specified 3d object (%u,%u) (%s).", cimg_instance,vertices._width,primitives._width,error_message); if (vertices._width && !primitives) { CImgList<tf> nprimitives(vertices._width,1,1,1,1); cimglist_for(nprimitives,l) nprimitives(l,0) = l; return _display_object3d(disp,title,vertices,nprimitives,colors,opacities,centering, render_static,render_motion,is_double_sided,focale, light_x,light_y,light_z,specular_lightness,specular_shininess, display_axes,pose_matrix); } if (!disp) { disp.assign(cimg_fitscreen(_width,_height,_depth),title?title:0,3); if (!title) disp.set_title("CImg<%s> (%u vertices, %u primitives)",pixel_type(),vertices._width,primitives._width); } else if (title) disp.set_title("%s",title); // Init 3d objects and compute object statistics CImg<floatT> pose, rotated_vertices(vertices._width,3), bbox_vertices, rotated_bbox_vertices, axes_vertices, rotated_axes_vertices, bbox_opacities, axes_opacities; CImgList<uintT> bbox_primitives, axes_primitives; CImgList<tf> reverse_primitives; CImgList<T> bbox_colors, bbox_colors2, axes_colors; unsigned int ns_width = 0, ns_height = 0; int _is_double_sided = (int)is_double_sided; bool ndisplay_axes = display_axes; const CImg<T> background_color(1,1,1,_spectrum,0), foreground_color(1,1,1,_spectrum,255); float Xoff = 0, Yoff = 0, Zoff = 0, sprite_scale = 1, xm = 0, xM = vertices?vertices.get_shared_row(0).max_min(xm):0, ym = 0, yM = vertices?vertices.get_shared_row(1).max_min(ym):0, zm = 0, zM = vertices?vertices.get_shared_row(2).max_min(zm):0; const float delta = cimg::max(xM-xm,yM-ym,zM-zm); rotated_bbox_vertices = bbox_vertices.assign(8,3,1,1, xm,xM,xM,xm,xm,xM,xM,xm, ym,ym,yM,yM,ym,ym,yM,yM, zm,zm,zm,zm,zM,zM,zM,zM); bbox_primitives.assign(6,1,4,1,1, 0,3,2,1, 4,5,6,7, 1,2,6,5, 0,4,7,3, 0,1,5,4, 2,3,7,6); bbox_colors.assign(6,_spectrum,1,1,1,background_color[0]); bbox_colors2.assign(6,_spectrum,1,1,1,foreground_color[0]); bbox_opacities.assign(bbox_colors._width,1,1,1,0.3f); rotated_axes_vertices = axes_vertices.assign(7,3,1,1, 0,20,0,0,22,-6,-6, 0,0,20,0,-6,22,-6, 0,0,0,20,0,0,22); axes_opacities.assign(3,1,1,1,1); axes_colors.assign(3,_spectrum,1,1,1,foreground_color[0]); axes_primitives.assign(3,1,2,1,1, 0,1, 0,2, 0,3); // Begin user interaction loop CImg<T> visu0(*this), visu; CImg<tpfloat> zbuffer(visu0.width(),visu0.height(),1,1,0); bool init_pose = true, clicked = false, redraw = true; unsigned int key = 0; int x0 = 0, y0 = 0, x1 = 0, y1 = 0, nrender_static = render_static, nrender_motion = render_motion; disp.show().flush(); while (!disp.is_closed() && !key) { // Init object pose if (init_pose) { const float ratio = delta>0?(2.0f*cimg::min(disp.width(),disp.height())/(3.0f*delta)):1, dx = (xM + xm)/2, dy = (yM + ym)/2, dz = (zM + zm)/2; if (centering) CImg<floatT>(4,3,1,1, ratio,0.,0.,-ratio*dx, 0.,ratio,0.,-ratio*dy, 0.,0.,ratio,-ratio*dz).move_to(pose); else CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0).move_to(pose); if (pose_matrix) { CImg<floatT> pose0(pose_matrix,4,3,1,1,false); pose0.resize(4,4,1,1,0); pose.resize(4,4,1,1,0); pose0(3,3) = pose(3,3) = 1; (pose0*pose).get_crop(0,0,3,2).move_to(pose); Xoff = pose_matrix[12]; Yoff = pose_matrix[13]; Zoff = pose_matrix[14]; sprite_scale = pose_matrix[15]; } else { Xoff = Yoff = Zoff = 0; sprite_scale = 1; } init_pose = false; redraw = true; } // Rotate and draw 3d object if (redraw) { const float r00 = pose(0,0), r10 = pose(1,0), r20 = pose(2,0), r30 = pose(3,0), r01 = pose(0,1), r11 = pose(1,1), r21 = pose(2,1), r31 = pose(3,1), r02 = pose(0,2), r12 = pose(1,2), r22 = pose(2,2), r32 = pose(3,2); if ((clicked && nrender_motion>=0) || (!clicked && nrender_static>=0)) cimg_forX(vertices,l) { const float x = (float)vertices(l,0), y = (float)vertices(l,1), z = (float)vertices(l,2); rotated_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_vertices(l,2) = r02*x + r12*y + r22*z + r32; } else cimg_forX(bbox_vertices,l) { const float x = bbox_vertices(l,0), y = bbox_vertices(l,1), z = bbox_vertices(l,2); rotated_bbox_vertices(l,0) = r00*x + r10*y + r20*z + r30; rotated_bbox_vertices(l,1) = r01*x + r11*y + r21*z + r31; rotated_bbox_vertices(l,2) = r02*x + r12*y + r22*z + r32; } // Draw object visu = visu0; if ((clicked && nrender_motion<0) || (!clicked && nrender_static<0)) visu.draw_object3d(Xoff + visu._width/2.0f,Yoff + visu._height/2.0f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors,bbox_opacities,2,false,focale). draw_object3d(Xoff + visu._width/2.0f,Yoff + visu._height/2.0f,Zoff, rotated_bbox_vertices,bbox_primitives,bbox_colors2,1,false,focale); else visu._draw_object3d((void*)0,(!clicked && nrender_static>0)?zbuffer.fill(0):CImg<tpfloat>::empty(), Xoff + visu._width/2.0f,Yoff + visu._height/2.0f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static,_is_double_sided==1,focale, width()/2.0f+light_x,height()/2.0f+light_y,light_z,specular_lightness,specular_shininess, sprite_scale); // Draw axes if (ndisplay_axes) { const float n = (float)std::sqrt(1e-8 + r00*r00 + r01*r01 + r02*r02), _r00 = r00/n, _r10 = r10/n, _r20 = r20/n, _r01 = r01/n, _r11 = r11/n, _r21 = r21/n, _r02 = r01/n, _r12 = r12/n, _r22 = r22/n, Xaxes = 25, Yaxes = visu._height - 38.0f; cimg_forX(axes_vertices,l) { const float x = axes_vertices(l,0), y = axes_vertices(l,1), z = axes_vertices(l,2); rotated_axes_vertices(l,0) = _r00*x + _r10*y + _r20*z; rotated_axes_vertices(l,1) = _r01*x + _r11*y + _r21*z; rotated_axes_vertices(l,2) = _r02*x + _r12*y + _r22*z; } axes_opacities(0,0) = (rotated_axes_vertices(1,2)>0)?0.5f:1.0f; axes_opacities(1,0) = (rotated_axes_vertices(2,2)>0)?0.5f:1.0f; axes_opacities(2,0) = (rotated_axes_vertices(3,2)>0)?0.5f:1.0f; visu.draw_object3d(Xaxes,Yaxes,0,rotated_axes_vertices,axes_primitives,axes_colors,axes_opacities,1,false,focale). draw_text((int)(Xaxes+rotated_axes_vertices(4,0)), (int)(Yaxes+rotated_axes_vertices(4,1)), "X",axes_colors[0]._data,0,axes_opacities(0,0),13). draw_text((int)(Xaxes+rotated_axes_vertices(5,0)), (int)(Yaxes+rotated_axes_vertices(5,1)), "Y",axes_colors[1]._data,0,axes_opacities(1,0),13). draw_text((int)(Xaxes+rotated_axes_vertices(6,0)), (int)(Yaxes+rotated_axes_vertices(6,1)), "Z",axes_colors[2]._data,0,axes_opacities(2,0),13); } visu.display(disp); if (!clicked || nrender_motion==nrender_static) redraw = false; } // Handle user interaction disp.wait(); if ((disp.button() || disp.wheel()) && disp.mouse_x()>=0 && disp.mouse_y()>=0) { redraw = true; if (!clicked) { x0 = x1 = disp.mouse_x(); y0 = y1 = disp.mouse_y(); if (!disp.wheel()) clicked = true; } else { x1 = disp.mouse_x(); y1 = disp.mouse_y(); } if (disp.button()&1) { const float R = 0.45f*cimg::min(disp.width(),disp.height()), R2 = R*R, u0 = (float)(x0-disp.width()/2), v0 = (float)(y0-disp.height()/2), u1 = (float)(x1-disp.width()/2), v1 = (float)(y1-disp.height()/2), n0 = (float)std::sqrt(u0*u0+v0*v0), n1 = (float)std::sqrt(u1*u1+v1*v1), nu0 = n0>R?(u0*R/n0):u0, nv0 = n0>R?(v0*R/n0):v0, nw0 = (float)std::sqrt(cimg::max(0,R2-nu0*nu0-nv0*nv0)), nu1 = n1>R?(u1*R/n1):u1, nv1 = n1>R?(v1*R/n1):v1, nw1 = (float)std::sqrt(cimg::max(0,R2-nu1*nu1-nv1*nv1)), u = nv0*nw1-nw0*nv1, v = nw0*nu1-nu0*nw1, w = nv0*nu1-nu0*nv1, n = (float)std::sqrt(u*u+v*v+w*w), alpha = (float)std::asin(n/R2); (CImg<floatT>::rotation_matrix(u,v,w,alpha)*pose).move_to(pose); x0 = x1; y0 = y1; } if (disp.button()&2) { if (focale>0) Zoff-=(y0-y1)*focale/400; else { const float s = std::exp((y0-y1)/400.0f); pose*=s; sprite_scale*=s; } x0 = x1; y0 = y1; } if (disp.wheel()) { if (focale>0) Zoff-=disp.wheel()*focale/20; else { const float s = std::exp(disp.wheel()/20.0f); pose*=s; sprite_scale*=s; } disp.set_wheel(); } if (disp.button()&4) { Xoff+=(x1-x0); Yoff+=(y1-y0); x0 = x1; y0 = y1; } if ((disp.button()&1) && (disp.button()&2)) { init_pose = true; disp.set_button(); x0 = x1; y0 = y1; pose = CImg<floatT>(4,3,1,1, 1,0,0,0, 0,1,0,0, 0,0,1,0); } } else if (clicked) { x0 = x1; y0 = y1; clicked = false; redraw = true; } switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD: if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(_width,_height,_depth),false)._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { if (!ns_width || !ns_height || ns_width>(unsigned int)disp.screen_width() || ns_height>(unsigned int)disp.screen_height()) { ns_width = disp.screen_width()*3U/4; ns_height = disp.screen_height()*3U/4; } if (disp.is_fullscreen()) disp.resize(ns_width,ns_height,false); else { ns_width = (unsigned int)disp.width(); ns_height = disp.height(); disp.resize(disp.screen_width(),disp.screen_height(),false); } disp.toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; } break; case cimg::keyT : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Switch single/double-sided primitives. if (--_is_double_sided==-2) _is_double_sided = 1; if (_is_double_sided>=0) reverse_primitives.assign(); else primitives.get_reverse_object3d().move_to(reverse_primitives); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyZ : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Enable/disable Z-buffer if (zbuffer) zbuffer.assign(); else zbuffer.assign(visu0.width(),visu0.height(),1,1,0); disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyA : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Show/hide 3d axes. ndisplay_axes = !ndisplay_axes; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF1 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to points. nrender_motion = (nrender_static==0 && nrender_motion!=0)?0:-1; nrender_static = 0; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF2 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to lines. nrender_motion = (nrender_static==1 && nrender_motion!=1)?1:-1; nrender_static = 1; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF3 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat. nrender_motion = (nrender_static==2 && nrender_motion!=2)?2:-1; nrender_static = 2; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF4 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to flat-shaded. nrender_motion = (nrender_static==3 && nrender_motion!=3)?3:-1; nrender_static = 3; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF5 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to gouraud-shaded. nrender_motion = (nrender_static==4 && nrender_motion!=4)?4:-1; nrender_static = 4; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyF6 : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Set rendering mode to phong-shaded. nrender_motion = (nrender_static==5 && nrender_motion!=5)?5:-1; nrender_static = 5; disp.set_key(key,false); key = 0; redraw = true; } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save snapshot static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.bmp",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); (+visu).draw_text(0,0," Saving snapshot... ",foreground_color._data,background_color._data,1,13).display(disp); visu.save(filename); visu.draw_text(0,0," Snapshot '%s' saved. ",foreground_color._data,background_color._data,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyG : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .off file static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.off",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving object... ",foreground_color._data,background_color._data,1,13).display(disp); vertices.save_off(reverse_primitives?reverse_primitives:primitives,colors,filename); visu.draw_text(0,0," Object '%s' saved. ",foreground_color._data,background_color._data,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .cimg file static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving object... ",foreground_color._data,background_color._data,1,13).display(disp); vertices.get_object3dtoCImg3d(reverse_primitives?reverse_primitives:primitives,colors,opacities).save(filename); visu.draw_text(0,0," Object '%s' saved. ",foreground_color._data,background_color._data,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; #ifdef cimg_use_board case cimg::keyP : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .EPS file static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.eps",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving EPS snapshot... ",foreground_color._data,background_color._data,1,13).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.0f,Yoff + visu._height/2.0f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.0f+light_x,visu.height()/2.0f+light_y,light_z,specular_lightness,specular_shininess, sprite_scale); board.saveEPS(filename); visu.draw_text(0,0," Object '%s' saved. ",foreground_color._data,background_color._data,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; case cimg::keyV : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { // Save object as a .SVG file static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.svg",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving SVG snapshot... ",foreground_color._data,background_color._data,1,13).display(disp); LibBoard::Board board; (+visu)._draw_object3d(&board,zbuffer.fill(0), Xoff + visu._width/2.0f,Yoff + visu._height/2.0f,Zoff, rotated_vertices,reverse_primitives?reverse_primitives:primitives, colors,opacities,clicked?nrender_motion:nrender_static, _is_double_sided==1,focale, visu.width()/2.0f+light_x,visu.height()/2.0f+light_y,light_z,specular_lightness,specular_shininess, sprite_scale); board.saveSVG(filename); visu.draw_text(0,0," Object '%s' saved. ",foreground_color._data,background_color._data,1,13,filename).display(disp); disp.set_key(key,false); key = 0; } break; #endif } if (disp.is_resized()) { disp.resize(false); visu0 = get_resize(disp,1); if (zbuffer) zbuffer.assign(disp.width(),disp.height()); redraw = true; } } if (pose_matrix) { std::memcpy(pose_matrix,pose._data,12*sizeof(float)); pose_matrix[12] = Xoff; pose_matrix[13] = Yoff; pose_matrix[14] = Zoff; pose_matrix[15] = sprite_scale; } disp.set_button().set_key(key); return *this; } //! Display 1d graph in an interactive window. /** \param disp Display window. \param plot_type Plot type. Can be <tt>{ 0=points | 1=segments | 2=splines | 3=bars }</tt>. \param vertex_type Vertex type. \param labelx Title for the horizontal axis, as a C-string. \param xmin Minimum value along the X-axis. \param xmax Maximum value along the X-axis. \param labely Title for the vertical axis, as a C-string. \param ymin Minimum value along the X-axis. \param ymax Maximum value along the X-axis. **/ const CImg<T>& display_graph(CImgDisplay &disp, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "display_graph(): Empty instance.", cimg_instance); if (!disp) disp.assign(cimg_fitscreen(640,480,1),0,0).set_title("CImg<%s>",pixel_type()); const unsigned long siz = (unsigned long)_width*_height*_depth, siz1 = cimg::max(1U,siz-1); const unsigned int old_normalization = disp.normalization(); disp.show().flush()._normalization = 0; double y0 = ymin, y1 = ymax, nxmin = xmin, nxmax = xmax; if (nxmin==nxmax) { nxmin = 0; nxmax = siz1; } int x0 = 0, x1 = width()*height()*depth() - 1, key = 0; for (bool reset_view = true, resize_disp = false; !key && !disp.is_closed(); ) { if (reset_view) { x0 = 0; x1 = width()*height()*depth()-1; y0 = ymin; y1 = ymax; reset_view = false; } CImg<T> zoom(x1-x0+1,1,1,spectrum()); cimg_forC(*this,c) zoom.get_shared_channel(c) = CImg<T>(data(x0,0,0,c),x1-x0+1,1,1,1,true); if (y0==y1) { y0 = zoom.min_max(y1); const double dy = y1 - y0; y0-=dy/20; y1+=dy/20; } if (y0==y1) { --y0; ++y1; } const CImg<intT> selection = zoom.get_select_graph(disp,plot_type,vertex_type, labelx, nxmin + x0*(nxmax-nxmin)/siz1, nxmin + x1*(nxmax-nxmin)/siz1, labely,y0,y1); const int mouse_x = disp.mouse_x(), mouse_y = disp.mouse_y(); if (selection[0]>=0) { if (selection[2]<0) reset_view = true; else { x1 = x0 + selection[2]; x0+=selection[0]; if (selection[1]>=0 && selection[3]>=0) { y0 = y1 - selection[3]*(y1-y0)/(disp.height()-32); y1-=selection[1]*(y1-y0)/(disp.height()-32); } } } else { bool go_in = false, go_out = false, go_left = false, go_right = false, go_up = false, go_down = false; switch (key = disp.key()) { case cimg::keyHOME : reset_view = resize_disp = true; key = 0; disp.set_key(); break; case cimg::keyPADADD : go_in = true; go_out = false; key = 0; disp.set_key(); break; case cimg::keyPADSUB : go_out = true; go_in = false; key = 0; disp.set_key(); break; case cimg::keyARROWLEFT : case cimg::keyPAD4 : go_left = true; go_right = false; key = 0; disp.set_key(); break; case cimg::keyARROWRIGHT : case cimg::keyPAD6 : go_right = true; go_left = false; key = 0; disp.set_key(); break; case cimg::keyARROWUP : case cimg::keyPAD8 : go_up = true; go_down = false; key = 0; disp.set_key(); break; case cimg::keyARROWDOWN : case cimg::keyPAD2 : go_down = true; go_up = false; key = 0; disp.set_key(); break; case cimg::keyPAD7 : go_left = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD9 : go_right = true; go_up = true; key = 0; disp.set_key(); break; case cimg::keyPAD1 : go_left = true; go_down = true; key = 0; disp.set_key(); break; case cimg::keyPAD3 : go_right = true; go_down = true; key = 0; disp.set_key(); break; } if (disp.wheel()) { if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) go_out = !(go_in = disp.wheel()>0); else if (disp.is_keySHIFTLEFT() || disp.is_keySHIFTRIGHT()) go_left = !(go_right = disp.wheel()>0); else go_up = !(go_down = disp.wheel()<0); key = 0; } if (go_in) { const int xsiz = x1 - x0, mx = (mouse_x-16)*xsiz/(disp.width()-32), cx = x0 + (mx<0?0:(mx>=xsiz?xsiz:mx)); if (x1-x0>4) { x0 = cx - 7*(cx-x0)/8; x1 = cx + 7*(x1-cx)/8; if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { const double ysiz = y1 - y0, my = (mouse_y-16)*ysiz/(disp.height()-32), cy = y1 - (my<0?0:(my>=ysiz?ysiz:my)); y0 = cy - 7*(cy-y0)/8; y1 = cy + 7*(y1-cy)/8; } else y0 = y1 = 0; } } if (go_out) { if (x0>0 || x1<(int)siz1) { const int delta_x = (x1-x0)/8, ndelta_x = delta_x?delta_x:(siz>1?1:0); const double ndelta_y = (y1-y0)/8; x0-=ndelta_x; x1+=ndelta_x; y0-=ndelta_y; y1+=ndelta_y; if (x0<0) { x1-=x0; x0 = 0; if (x1>=(int)siz) x1 = (int)siz1; } if (x1>=(int)siz) { x0-=(x1-siz1); x1 = (int)siz1; if (x0<0) x0 = 0; } } } if (go_left) { const int delta = (x1-x0)/5, ndelta = delta?delta:1; if (x0-ndelta>=0) { x0-=ndelta; x1-=ndelta; } else { x1-=x0; x0 = 0; } go_left = false; } if (go_right) { const int delta = (x1-x0)/5, ndelta = delta?delta:1; if (x1+ndelta<(int)siz) { x0+=ndelta; x1+=ndelta; } else { x0+=(siz1-x1); x1 = siz1; } go_right = false; } if (go_up) { const double delta = (y1-y0)/10, ndelta = delta?delta:1; y0+=ndelta; y1+=ndelta; go_up = false; } if (go_down) { const double delta = (y1-y0)/10, ndelta = delta?delta:1; y0-=ndelta; y1-=ndelta; go_down = false; } } } disp._normalization = old_normalization; return *this; } //! Display 1d graph in an interactive window \overloading. const CImg<T>& display_graph(const char *const title=0, const unsigned int plot_type=1, const unsigned int vertex_type=1, const char *const labelx=0, const double xmin=0, const double xmax=0, const char *const labely=0, const double ymin=0, const double ymax=0) const { if (is_empty()) throw CImgInstanceException(_cimg_instance "display_graph(): Empty instance.", cimg_instance); CImgDisplay disp; return display_graph(disp.set_title("%s",title),plot_type,vertex_type,labelx,xmin,xmax,labely,ymin,ymax); } //! Save image as a file. /** \param filename Filename, as a C-string. \param number When positive, represents an index added to the filename. \note - The used file format is defined by the file extension in the filename \p filename. - Parameter \p number can be used to add a 6-digit number to the filename before saving. **/ const CImg<T>& save(const char *const filename, const int number=-1) const { if (!filename) throw CImgArgumentException(_cimg_instance "save(): Specified filename is (null).", cimg_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const char *const ext = cimg::split_filename(filename); char nfilename[1024] = { 0 }; const char *const fn = (number>=0)?cimg::number_filename(filename,number,6,nfilename):filename; #ifdef cimg_save_plugin cimg_save_plugin(fn); #endif #ifdef cimg_save_plugin1 cimg_save_plugin1(fn); #endif #ifdef cimg_save_plugin2 cimg_save_plugin2(fn); #endif #ifdef cimg_save_plugin3 cimg_save_plugin3(fn); #endif #ifdef cimg_save_plugin4 cimg_save_plugin4(fn); #endif #ifdef cimg_save_plugin5 cimg_save_plugin5(fn); #endif #ifdef cimg_save_plugin6 cimg_save_plugin6(fn); #endif #ifdef cimg_save_plugin7 cimg_save_plugin7(fn); #endif #ifdef cimg_save_plugin8 cimg_save_plugin8(fn); #endif // Ascii formats if (!cimg::strcasecmp(ext,"asc")) return save_ascii(fn); else if (!cimg::strcasecmp(ext,"dlm") || !cimg::strcasecmp(ext,"txt")) return save_dlm(fn); else if (!cimg::strcasecmp(ext,"cpp") || !cimg::strcasecmp(ext,"hpp") || !cimg::strcasecmp(ext,"h") || !cimg::strcasecmp(ext,"c")) return save_cpp(fn); // 2d binary formats else if (!cimg::strcasecmp(ext,"bmp")) return save_bmp(fn); else if (!cimg::strcasecmp(ext,"jpg") || !cimg::strcasecmp(ext,"jpeg") || !cimg::strcasecmp(ext,"jpe") || !cimg::strcasecmp(ext,"jfif") || !cimg::strcasecmp(ext,"jif")) return save_jpeg(fn); else if (!cimg::strcasecmp(ext,"rgb")) return save_rgb(fn); else if (!cimg::strcasecmp(ext,"rgba")) return save_rgba(fn); else if (!cimg::strcasecmp(ext,"png")) return save_png(fn); else if (!cimg::strcasecmp(ext,"pgm") || !cimg::strcasecmp(ext,"ppm") || !cimg::strcasecmp(ext,"pnm")) return save_pnm(fn); else if (!cimg::strcasecmp(ext,"pnk")) return save_pnk(fn); else if (!cimg::strcasecmp(ext,"pfm")) return save_pfm(fn); else if (!cimg::strcasecmp(ext,"exr")) return save_exr(fn); else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); // 3d binary formats else if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg") || !*ext) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"dcm")) return save_medcon_external(fn); else if (!cimg::strcasecmp(ext,"hdr") || !cimg::strcasecmp(ext,"nii")) return save_analyze(fn); else if (!cimg::strcasecmp(ext,"inr")) return save_inr(fn); else if (!cimg::strcasecmp(ext,"mnc")) return save_minc2(fn); else if (!cimg::strcasecmp(ext,"pan")) return save_pandore(fn); else if (!cimg::strcasecmp(ext,"raw")) return save_raw(fn); // Archive files else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); // Image sequences else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_ffmpeg(fn); return save_other(fn); } //! Save image as an ascii file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_ascii(const char *const filename) const { return _save_ascii(0,filename); } //! Save image as an ascii file \overloading. const CImg<T>& save_ascii(std::FILE *const file) const { return _save_ascii(file,0); } const CImg<T>& _save_ascii(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_ascii(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_ascii(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); std::fprintf(nfile,"%u %u %u %u\n",_width,_height,_depth,_spectrum); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.16g ",(double)*(ptrs++)); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a .cpp source file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_cpp(const char *const filename) const { return _save_cpp(0,filename); } //! Save image as a .cpp source file \overloading. const CImg<T>& save_cpp(std::FILE *const file) const { return _save_cpp(file,0); } const CImg<T>& _save_cpp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_cpp(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_cpp(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); char varname[1024] = { 0 }; if (filename) std::sscanf(cimg::basename(filename),"%1023[a-zA-Z0-9_]",varname); if (!*varname) cimg_snprintf(varname,sizeof(varname),"unnamed"); std::fprintf(nfile, "/* Define image '%s' of size %ux%ux%ux%u and type '%s' */\n" "%s data_%s[] = { \n ", varname,_width,_height,_depth,_spectrum,pixel_type(),pixel_type(),varname); for (unsigned long off = 0, siz = size()-1; off<=siz; ++off) { std::fprintf(nfile,cimg::type<T>::format(),cimg::type<T>::format((*this)[off])); if (off==siz) std::fprintf(nfile," };\n"); else if (!((off+1)%16)) std::fprintf(nfile,",\n "); else std::fprintf(nfile,", "); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a DLM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_dlm(const char *const filename) const { return _save_dlm(0,filename); } //! Save image as a DLM file \overloading. const CImg<T>& save_dlm(std::FILE *const file) const { return _save_dlm(file,0); } const CImg<T>& _save_dlm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_dlm(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_dlm(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_depth>1) cimg::warn(_cimg_instance "save_dlm(): Instance is volumetric, values along Z will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>1) cimg::warn(_cimg_instance "save_dlm(): Instance is multispectral, values along C will be unrolled in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); const T* ptrs = _data; cimg_forYZC(*this,y,z,c) { cimg_forX(*this,x) std::fprintf(nfile,"%.16g%s",(double)*(ptrs++),(x==width()-1)?"":","); std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a BMP file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_bmp(const char *const filename) const { return _save_bmp(0,filename); } //! Save image as a BMP file \overloading. const CImg<T>& save_bmp(std::FILE *const file) const { return _save_bmp(file,0); } const CImg<T>& _save_bmp(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_bmp(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_bmp(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_depth>1) cimg::warn(_cimg_instance "save_bmp(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_bmp(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); unsigned char header[54] = { 0 }, align_buf[4] = { 0 }; const unsigned int align = (4 - (3*_width)%4)%4, buf_size = (3*_width + align)*height(), file_size = 54 + buf_size; header[0] = 'B'; header[1] = 'M'; header[0x02] = file_size&0xFF; header[0x03] = (file_size>>8)&0xFF; header[0x04] = (file_size>>16)&0xFF; header[0x05] = (file_size>>24)&0xFF; header[0x0A] = 0x36; header[0x0E] = 0x28; header[0x12] = _width&0xFF; header[0x13] = (_width>>8)&0xFF; header[0x14] = (_width>>16)&0xFF; header[0x15] = (_width>>24)&0xFF; header[0x16] = _height&0xFF; header[0x17] = (_height>>8)&0xFF; header[0x18] = (_height>>16)&0xFF; header[0x19] = (_height>>24)&0xFF; header[0x1A] = 1; header[0x1B] = 0; header[0x1C] = 24; header[0x1D] = 0; header[0x22] = buf_size&0xFF; header[0x23] = (buf_size>>8)&0xFF; header[0x24] = (buf_size>>16)&0xFF; header[0x25] = (buf_size>>24)&0xFF; header[0x27] = 0x1; header[0x2B] = 0x1; cimg::fwrite(header,54,nfile); const T *ptr_r = data(0,_height-1,0,0), *ptr_g = (_spectrum>=2)?data(0,_height-1,0,1):0, *ptr_b = (_spectrum>=3)?data(0,_height-1,0,2):0; switch (_spectrum) { case 1 : { cimg_forY(*this,y) { cimg_forX(*this,x) { const unsigned char val = (unsigned char)*(ptr_r++); std::fputc(val,nfile); std::fputc(val,nfile); std::fputc(val,nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; } } break; case 2 : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc(0,nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; } } break; default : { cimg_forY(*this,y) { cimg_forX(*this,x) { std::fputc((unsigned char)(*(ptr_b++)),nfile); std::fputc((unsigned char)(*(ptr_g++)),nfile); std::fputc((unsigned char)(*(ptr_r++)),nfile); } cimg::fwrite(align_buf,align,nfile); ptr_r-=2*_width; ptr_g-=2*_width; ptr_b-=2*_width; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a JPEG file. /** \param filename Filename, as a C-string. \param quality Image quality (in %) **/ const CImg<T>& save_jpeg(const char *const filename, const unsigned int quality=100) const { return _save_jpeg(0,filename,quality); } //! Save image as a JPEG file \overloading. const CImg<T>& save_jpeg(std::FILE *const file, const unsigned int quality=100) const { return _save_jpeg(file,0,quality); } const CImg<T>& _save_jpeg(std::FILE *const file, const char *const filename, const unsigned int quality) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_jpeg(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_jpeg(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_depth>1) cimg::warn(_cimg_instance "save_jpeg(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); #ifndef cimg_use_jpeg if (!file) return save_other(filename,quality); else throw CImgIOException(_cimg_instance "save_jpeg(): Unable to save data in '(*FILE)' unless libjpeg is enabled.", cimg_instance); #else unsigned int dimbuf = 0; J_COLOR_SPACE colortype = JCS_RGB; switch(_spectrum) { case 1 : dimbuf = 1; colortype = JCS_GRAYSCALE; break; case 2 : dimbuf = 3; colortype = JCS_RGB; break; case 3 : dimbuf = 3; colortype = JCS_RGB; break; default : dimbuf = 4; colortype = JCS_CMYK; break; } // Call libjpeg functions struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); jpeg_stdio_dest(&cinfo,nfile); cinfo.image_width = _width; cinfo.image_height = _height; cinfo.input_components = dimbuf; cinfo.in_color_space = colortype; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo,quality<100?quality:100,TRUE); jpeg_start_compress(&cinfo,TRUE); JSAMPROW row_pointer[1]; CImg<ucharT> buffer((unsigned long)_width*dimbuf); while (cinfo.next_scanline < cinfo.image_height) { unsigned char *ptrd = buffer._data; // Fill pixel buffer switch (_spectrum) { case 1 : { // Greyscale images const T *ptr_g = data(0, cinfo.next_scanline); for(unsigned int b = 0; b < cinfo.image_width; b++) *(ptrd++) = (unsigned char)*(ptr_g++); } break; case 2 : { // RG images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1); for(unsigned int b = 0; b < cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } } break; case 3 : { // RGB images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2); for(unsigned int b = 0; b < cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } } break; default : { // CMYK images const T *ptr_r = data(0,cinfo.next_scanline,0,0), *ptr_g = data(0,cinfo.next_scanline,0,1), *ptr_b = data(0,cinfo.next_scanline,0,2), *ptr_a = data(0,cinfo.next_scanline,0,3); for(unsigned int b = 0; b < cinfo.image_width; ++b) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); *(ptrd++) = (unsigned char)*(ptr_a++); } } } *row_pointer = buffer._data; jpeg_write_scanlines(&cinfo,row_pointer,1); } jpeg_finish_compress(&cinfo); if (!file) cimg::fclose(nfile); jpeg_destroy_compress(&cinfo); return *this; #endif } //! Save image, using built-in ImageMagick++ library. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixel for the saving, when possible. **/ const CImg<T>& save_magick(const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_magick(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_magick(): Empty instance, for file '%s'.", cimg_instance, filename); #ifdef cimg_use_magick double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_magick(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>3) cimg::warn(_cimg_instance "save_magick(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_magick(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); Magick::Image image(Magick::Geometry(_width,_height),"black"); image.type(Magick::TrueColorType); image.depth(bytes_per_pixel?(8*bytes_per_pixel):(stmax>=256?16:8)); const T *ptr_r = data(0,0,0,0), *ptr_g = _spectrum>1?data(0,0,0,1):0, *ptr_b = _spectrum>2?data(0,0,0,2):0; Magick::PixelPacket *pixels = image.getPixels(0,0,_width,_height); switch (_spectrum) { case 1 : // Scalar images for (unsigned long off = (unsigned long)_width*_height; off; --off) { pixels->red = pixels->green = pixels->blue = (Magick::Quantum)*(ptr_r++); ++pixels; } break; case 2 : // RG images for (unsigned long off = (unsigned long)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = 0; ++pixels; } break; default : // RGB images for (unsigned long off = (unsigned long)_width*_height; off; --off) { pixels->red = (Magick::Quantum)*(ptr_r++); pixels->green = (Magick::Quantum)*(ptr_g++); pixels->blue = (Magick::Quantum)*(ptr_b++); ++pixels; } } image.syncPixels(); image.write(filename); #else cimg::unused(bytes_per_pixel); throw CImgIOException(_cimg_instance "save_magick(): Unable to save file '%s' unless libMagick++ is enabled.", cimg_instance, filename); #endif return *this; } //! Save image as a PNG file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving, when possible. **/ const CImg<T>& save_png(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_png(0,filename,bytes_per_pixel); } //! Save image as a PNG file \overloading. const CImg<T>& save_png(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_png(file,0,bytes_per_pixel); } const CImg<T>& _save_png(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_png(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_png(): Empty image, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); #ifndef cimg_use_png cimg::unused(bytes_per_pixel); if (!file) return save_other(filename); else throw CImgIOException(_cimg_instance "save_png(): Unable to save data in '(*FILE)' unless libpng is enabled.", cimg_instance); #else const char *volatile nfilename = filename; // two 'volatile' here to remove a g++ warning due to 'setjmp'. std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"wb"); double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_png(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); if (_spectrum>4) cimg::warn(_cimg_instance "save_png(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_png(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, filename,stmin,stmax); // Setup PNG structures for write png_voidp user_error_ptr = 0; png_error_ptr user_error_fn = 0, user_warning_fn = 0; png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,user_error_ptr, user_error_fn, user_warning_fn); if(!png_ptr){ if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'png_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_write_struct(&png_ptr,(png_infopp)0); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Failed to initialize 'info_ptr' structure when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_write_struct(&png_ptr, &info_ptr); if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_init_io(png_ptr, nfile); const int bit_depth = bytes_per_pixel?(bytes_per_pixel*8):(stmax>=256?16:8); int color_type; switch (spectrum()) { case 1 : color_type = PNG_COLOR_TYPE_GRAY; break; case 2 : color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3 : color_type = PNG_COLOR_TYPE_RGB; break; default : color_type = PNG_COLOR_TYPE_RGB_ALPHA; } const int interlace_type = PNG_INTERLACE_NONE; const int compression_type = PNG_COMPRESSION_TYPE_DEFAULT; const int filter_method = PNG_FILTER_TYPE_DEFAULT; png_set_IHDR(png_ptr,info_ptr,_width,_height,bit_depth,color_type,interlace_type,compression_type,filter_method); png_write_info(png_ptr,info_ptr); const int byte_depth = bit_depth>>3; const int numChan = spectrum()>4?4:spectrum(); const int pixel_bit_depth_flag = numChan * (bit_depth-1); // Allocate Memory for Image Save and Fill pixel data png_bytep *const imgData = new png_byte*[_height]; for (unsigned int row = 0; row<_height; ++row) imgData[row] = new png_byte[byte_depth*numChan*_width]; const T *pC0 = data(0,0,0,0); switch (pixel_bit_depth_flag) { case 7 : { // Gray 8-bit cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) *(ptrd++) = (unsigned char)*(pC0++); } } break; case 14 : { // Gray w/ Alpha 8-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); } } } break; case 21 : { // RGB 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned char *ptrd = imgData[y]; cimg_forX(*this,x) { *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); } } } break; case 28 : { // RGB x/ Alpha 8-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y){ unsigned char *ptrd = imgData[y]; cimg_forX(*this,x){ *(ptrd++) = (unsigned char)*(pC0++); *(ptrd++) = (unsigned char)*(pC1++); *(ptrd++) = (unsigned char)*(pC2++); *(ptrd++) = (unsigned char)*(pC3++); } } } break; case 15 : { // Gray 16-bit cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) *(ptrd++) = (unsigned short)*(pC0++); if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],_width); } } break; case 30 : { // Gray w/ Alpha 16-bit const T *pC1 = data(0,0,0,1); cimg_forY(*this,y){ unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],2*_width); } } break; case 45 : { // RGB 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],3*_width); } } break; case 60 : { // RGB w/ Alpha 16-bit const T *pC1 = data(0,0,0,1), *pC2 = data(0,0,0,2), *pC3 = data(0,0,0,3); cimg_forY(*this,y) { unsigned short *ptrd = (unsigned short*)(imgData[y]); cimg_forX(*this,x) { *(ptrd++) = (unsigned short)*(pC0++); *(ptrd++) = (unsigned short)*(pC1++); *(ptrd++) = (unsigned short)*(pC2++); *(ptrd++) = (unsigned short)*(pC3++); } if (!cimg::endianness()) cimg::invert_endianness((unsigned short*)imgData[y],4*_width); } } break; default : if (!file) cimg::fclose(nfile); throw CImgIOException(_cimg_instance "save_png(): Encountered unknown fatal error in libpng when saving file '%s'.", cimg_instance, nfilename?nfilename:"(FILE*)"); } png_write_image(png_ptr,imgData); png_write_end(png_ptr,info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); // Deallocate Image Write Memory cimg_forY(*this,n) delete[] imgData[n]; delete[] imgData; if (!file) cimg::fclose(nfile); return *this; #endif } //! Save image as a PNM file. /** \param filename Filename, as a C-string. \param bytes_per_pixel Force the number of bytes per pixels for the saving. **/ const CImg<T>& save_pnm(const char *const filename, const unsigned int bytes_per_pixel=0) const { return _save_pnm(0,filename,bytes_per_pixel); } //! Save image as a PNM file \overloading. const CImg<T>& save_pnm(std::FILE *const file, const unsigned int bytes_per_pixel=0) const { return _save_pnm(file,0,bytes_per_pixel); } const CImg<T>& _save_pnm(std::FILE *const file, const char *const filename, const unsigned int bytes_per_pixel=0) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnm(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_pnm(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); double stmin, stmax = (double)max_min(stmin); if (_depth>1) cimg::warn(_cimg_instance "save_pnm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pnm(): Instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (stmin<0 || (bytes_per_pixel==1 && stmax>=256) || stmax>=65536) cimg::warn(_cimg_instance "save_pnm(): Instance has pixel values in [%g,%g], probable type overflow in file '%s'.", cimg_instance, stmin,stmax,filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const unsigned long buf_size = cimg::min(1024*1024UL,_width*_height*(_spectrum==1?1UL:3UL)); std::fprintf(nfile,"P%c\n%u %u\n%u\n", (_spectrum==1?'5':'6'),_width,_height,stmax<256?255:(stmax<4096?4095:65535)); switch (_spectrum) { case 1 : { // Scalar image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PGM 8 bits CImg<ucharT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); unsigned char *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr_r++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Binary PGM 16 bits CImg<ushortT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); unsigned short *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (unsigned short)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } } break; case 2 : { // RG image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = 0; } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } break; default : { // RGB image if (bytes_per_pixel==1 || (!bytes_per_pixel && stmax<256)) { // Binary PPM 8 bits CImg<ucharT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size/3); unsigned char *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (unsigned char)*(ptr_r++); *(ptrd++) = (unsigned char)*(ptr_g++); *(ptrd++) = (unsigned char)*(ptr_b++); } cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } else { // Binary PPM 16 bits CImg<ushortT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size/3); unsigned short *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (unsigned short)*(ptr_r++); *(ptrd++) = (unsigned short)*(ptr_g++); *(ptrd++) = (unsigned short)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PNK file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pnk(const char *const filename) const { return _save_pnk(0,filename); } //! Save image as a PNK file \overloading. const CImg<T>& save_pnk(std::FILE *const file) const { return _save_pnk(file,0); } const CImg<T>& _save_pnk(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pnk(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_pnk(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>1) cimg::warn(_cimg_instance "save_pnk(): Instance is multispectral, only the first channel will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); const unsigned long buf_size = cimg::min(1024*1024LU,_width*_height*_depth); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr = data(0,0,0,0); if (!cimg::type<T>::is_float() && sizeof(T)==1 && _depth<2) _save_pnm(file,filename,0); // Can be saved as regular PNM file. else if (!cimg::type<T>::is_float() && sizeof(T)==1) { // Save as extended P5 file: Binary byte-valued 3d. std::fprintf(nfile,"P5\n%u %u %u\n255\n",_width,_height,_depth); CImg<ucharT> buf(buf_size); for (long to_write = (long)_width*_height*_depth; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); unsigned char *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (unsigned char)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else if (!cimg::type<T>::is_float()) { // Save as P8: Binary int32-valued 3d. if (_depth>1) std::fprintf(nfile,"P8\n%u %u %u\n%d\n",_width,_height,_depth,(int)max()); else std::fprintf(nfile,"P8\n%u %u\n%d\n",_width,_height,(int)max()); CImg<intT> buf(buf_size); for (long to_write = (long)_width*_height*_depth; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); int *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (int)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } else { // Save as P9: Binary float-valued 3d. if (_depth>1) std::fprintf(nfile,"P9\n%u %u %u\n%g\n",_width,_height,_depth,(double)max()); else std::fprintf(nfile,"P9\n%u %u\n%g\n",_width,_height,(double)max()); CImg<floatT> buf(buf_size); for (long to_write = (long)_width*_height*_depth; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); float *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (float)*(ptr++); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a PFM file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_pfm(const char *const filename) const { return get_mirror('y')._save_pfm(0,filename); } //! Save image as a PFM file \overloading. const CImg<T>& save_pfm(std::FILE *const file) const { return get_mirror('y')._save_pfm(file,0); } const CImg<T>& _save_pfm(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pfm(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_pfm(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_depth>1) cimg::warn(_cimg_instance "save_pfm(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum>3) cimg::warn(_cimg_instance "save_pfm(): image instance is multispectral, only the three first channels will be saved in file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const T *ptr_r = data(0,0,0,0), *ptr_g = (_spectrum>=2)?data(0,0,0,1):0, *ptr_b = (_spectrum>=3)?data(0,0,0,2):0; const unsigned int buf_size = cimg::min(1024*1024U,_width*_height*(_spectrum==1?1:3)); std::fprintf(nfile,"P%c\n%u %u\n1.0\n", (_spectrum==1?'f':'F'),_width,_height); switch (_spectrum) { case 1 : { // Scalar image CImg<floatT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned long N = cimg::min((unsigned long)to_write,buf_size); float *ptrd = buf._data; for (unsigned long i = N; i>0; --i) *(ptrd++) = (float)*(ptr_r++); if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,N,nfile); to_write-=N; } } break; case 2 : { // RG image CImg<floatT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned int N = cimg::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = 0; } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } break; default : { // RGB image CImg<floatT> buf(buf_size); for (long to_write = (long)_width*_height; to_write>0; ) { const unsigned int N = cimg::min((unsigned int)to_write,buf_size/3); float *ptrd = buf._data; for (unsigned long i = N; i>0; --i) { *(ptrd++) = (float)*(ptr_r++); *(ptrd++) = (float)*(ptr_g++); *(ptrd++) = (float)*(ptr_b++); } if (!cimg::endianness()) cimg::invert_endianness(buf._data,buf_size); cimg::fwrite(buf._data,3*N,nfile); to_write-=N; } } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a RGB file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgb(const char *const filename) const { return _save_rgb(0,filename); } //! Save image as a RGB file \overloading. const CImg<T>& save_rgb(std::FILE *const file) const { return _save_rgb(file,0); } const CImg<T>& _save_rgb(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgb(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_rgb(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum!=3) cimg::warn(_cimg_instance "save_rgb(): image instance has not exactly 3 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const unsigned long wh = (unsigned long)_width*_height; unsigned char *const buffer = new unsigned char[3*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0; switch (_spectrum) { case 1 : { // Scalar image for (unsigned long k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; } } break; case 2 : { // RG image for (unsigned long k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; } } break; default : { // RGB image for (unsigned long k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); } } } cimg::fwrite(buffer,3*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a RGBA file. /** \param filename Filename, as a C-string. **/ const CImg<T>& save_rgba(const char *const filename) const { return _save_rgba(0,filename); } //! Save image as a RGBA file \overloading. const CImg<T>& save_rgba(std::FILE *const file) const { return _save_rgba(file,0); } const CImg<T>& _save_rgba(std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_rgba(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_rgba(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); if (_spectrum!=4) cimg::warn(_cimg_instance "save_rgba(): image instance has not exactly 4 channels, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const unsigned long wh = (unsigned long)_width*_height; unsigned char *const buffer = new unsigned char[4*wh], *nbuffer = buffer; const T *ptr1 = data(0,0,0,0), *ptr2 = _spectrum>1?data(0,0,0,1):0, *ptr3 = _spectrum>2?data(0,0,0,2):0, *ptr4 = _spectrum>3?data(0,0,0,3):0; switch (_spectrum) { case 1 : { // Scalar images for (unsigned long k = 0; k<wh; ++k) { const unsigned char val = (unsigned char)*(ptr1++); *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = val; *(nbuffer++) = 255; } } break; case 2 : { // RG images for (unsigned long k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = 0; *(nbuffer++) = 255; } } break; case 3 : { // RGB images for (unsigned long k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = 255; } } break; default : { // RGBA images for (unsigned long k = 0; k<wh; ++k) { *(nbuffer++) = (unsigned char)(*(ptr1++)); *(nbuffer++) = (unsigned char)(*(ptr2++)); *(nbuffer++) = (unsigned char)(*(ptr3++)); *(nbuffer++) = (unsigned char)(*(ptr4++)); } } } cimg::fwrite(buffer,4*wh,nfile); if (!file) cimg::fclose(nfile); delete[] buffer; return *this; } //! Save image as a TIFF file. /** \param filename Filename, as a C-string. \param compression_type Type of data compression. Can be <tt>{ 1=None | 2=CCITTRLE | 3=CCITTFAX3 | 4=CCITTFAX4 | 5=LZW | 6=JPEG }</tt>. \note - libtiff support is enabled by defining the precompilation directive \c cimg_use_tif. - When libtiff is enabled, 2D and 3D (multipage) several channel per pixel are supported for <tt>char,uchar,short,ushort,float</tt> and \c double pixel types. - If \c cimg_use_tif is not defined at compilation time the function uses CImg<T>&save_other(const char*). **/ const CImg<T>& save_tiff(const char *const filename, const unsigned int compression_type=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_tiff(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_tiff(): Empty instance, for file '%s'.", cimg_instance, filename); #ifdef cimg_use_tiff TIFF *tif = TIFFOpen(filename,"w"); if (tif) { cimg_forZ(*this,z) get_slice(z)._save_tiff(tif,z,compression_type); TIFFClose(tif); } else throw CImgIOException(_cimg_instance "save_tiff(): Failed to open file '%s' for writing.", cimg_instance, filename); #else cimg::unused(compression_type); return save_other(filename); #endif return *this; } #ifdef cimg_use_tiff #define _cimg_save_tiff(types,typed,compression_type) \ if (!std::strcmp(types,pixel_type())) { const typed foo = (typed)0; return _save_tiff(tif,directory,foo,compression_type); } // [internal] Save a plane into a tiff file template<typename t> const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const t& pixel_t, const unsigned int compression_type) const { if (is_empty() || !tif || pixel_t) return *this; const char *const filename = TIFFFileName(tif); uint32 rowsperstrip = (uint32)-1; uint16 spp = _spectrum, bpp = sizeof(t)*8, photometric; if (spp==3 || spp==4) photometric = PHOTOMETRIC_RGB; else photometric = PHOTOMETRIC_MINISBLACK; TIFFSetDirectory(tif,directory); TIFFSetField(tif,TIFFTAG_IMAGEWIDTH,_width); TIFFSetField(tif,TIFFTAG_IMAGELENGTH,_height); TIFFSetField(tif,TIFFTAG_ORIENTATION,ORIENTATION_TOPLEFT); TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,spp); if (cimg::type<t>::is_float()) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,3); else if (cimg::type<t>::min()==0) TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,1); else TIFFSetField(tif,TIFFTAG_SAMPLEFORMAT,2); TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,bpp); TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,photometric); TIFFSetField(tif,TIFFTAG_COMPRESSION,compression_type?(compression_type-1):COMPRESSION_NONE); rowsperstrip = TIFFDefaultStripSize(tif,rowsperstrip); TIFFSetField(tif,TIFFTAG_ROWSPERSTRIP,rowsperstrip); TIFFSetField(tif,TIFFTAG_FILLORDER,FILLORDER_MSB2LSB); TIFFSetField(tif,TIFFTAG_SOFTWARE,"CImg"); t *const buf = (t*)_TIFFmalloc(TIFFStripSize(tif)); if (buf) { for (unsigned int row = 0; row<_height; row+=rowsperstrip) { uint32 nrow = (row + rowsperstrip>_height?_height-row:rowsperstrip); tstrip_t strip = TIFFComputeStrip(tif,row,0); tsize_t i = 0; for (unsigned int rr = 0; rr<nrow; ++rr) for (unsigned int cc = 0; cc<_width; ++cc) for (unsigned int vv = 0; vv<spp; ++vv) buf[i++] = (t)(*this)(cc,row + rr,0,vv); if (TIFFWriteEncodedStrip(tif,strip,buf,i*sizeof(t))<0) throw CImgIOException(_cimg_instance "save_tiff(): Invalid strip writing when saving file '%s'.", cimg_instance, filename?filename:"(FILE*)"); } _TIFFfree(buf); } TIFFWriteDirectory(tif); return (*this); } const CImg<T>& _save_tiff(TIFF *tif, const unsigned int directory, const unsigned int compression_type) const { _cimg_save_tiff("bool",unsigned char,compression_type); _cimg_save_tiff("char",char,compression_type); _cimg_save_tiff("unsigned char",unsigned char,compression_type); _cimg_save_tiff("short",short,compression_type); _cimg_save_tiff("unsigned short",unsigned short,compression_type); _cimg_save_tiff("int",int,compression_type); _cimg_save_tiff("unsigned int",unsigned int,compression_type); _cimg_save_tiff("long",int,compression_type); _cimg_save_tiff("unsigned long",unsigned int,compression_type); _cimg_save_tiff("float",float,compression_type); _cimg_save_tiff("double",float,compression_type); const char *const filename = TIFFFileName(tif); throw CImgInstanceException(_cimg_instance "save_tiff(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); return *this; } #endif //! Save image as a MINC2 file. /** \param filename Filename, as a C-string. \param imitate_file If non-zero, reference filename, as a C-string, to borrow header from. **/ const CImg<T>& save_minc2(const char *const filename, const char *const imitate_file=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_minc2(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_minc2(): Empty instance, for file '%s'.", cimg_instance, filename); #ifndef cimg_use_minc2 cimg::unused(imitate_file); return save_other(filename); #else minc::minc_1_writer wtr; if (imitate_file) wtr.open(filename, imitate_file); else { minc::minc_info di; if(width()) di.push_back(minc::dim_info(width(), width()*0.5, -1, minc::dim_info::DIM_X)); if(height()) di.push_back(minc::dim_info(height(), height()*0.5, -1, minc::dim_info::DIM_Y)); if(depth()) di.push_back(minc::dim_info(depth(), depth()*0.5, -1, minc::dim_info::DIM_Z)); if(spectrum()) di.push_back(minc::dim_info(spectrum(), spectrum()*0.5, -1, minc::dim_info::DIM_TIME)); wtr.open(filename, di, 1, NC_FLOAT, 0); } if(typeid(T)==typeid(unsigned char)) wtr.setup_write_byte(); else if(typeid(T)==typeid(int)) wtr.setup_write_int(); else if(typeid(T)==typeid(double)) wtr.setup_write_double(); else wtr.setup_write_float(); minc::save_standard_volume(wtr, this->_data); return *this; #endif } //! Save image as an ANALYZE7.5 or NIFTI file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 consecutive values that tell about the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_analyze(const char *const filename, const float *const voxel_size=0) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_analyze(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_analyze(): Empty instance, for file '%s'.", cimg_instance, filename); std::FILE *file; char header[348] = { 0 }, hname[1024] = { 0 }, iname[1024] = { 0 }; const char *const ext = cimg::split_filename(filename); short datatype=-1; std::memset(header,0,348); if (!*ext) { cimg_snprintf(hname,sizeof(hname),"%s.hdr",filename); cimg_snprintf(iname,sizeof(iname),"%s.img",filename); } if (!cimg::strncasecmp(ext,"hdr",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,sizeof(iname)-1); std::sprintf(iname + std::strlen(iname)-3,"img"); } if (!cimg::strncasecmp(ext,"img",3)) { std::strcpy(hname,filename); std::strncpy(iname,filename,sizeof(iname)-1); std::sprintf(hname + std::strlen(iname)-3,"hdr"); } if (!cimg::strncasecmp(ext,"nii",3)) { std::strncpy(hname,filename,sizeof(hname)-1); *iname = 0; } int *const iheader = (int*)header; *iheader = 348; std::strcpy(header + 4,"CImg"); std::strcpy(header + 14," "); ((short*)(header + 36))[0] = 4096; ((char*)(header + 38))[0] = 114; ((short*)(header + 40))[0] = 4; ((short*)(header + 40))[1] = _width; ((short*)(header + 40))[2] = _height; ((short*)(header + 40))[3] = _depth; ((short*)(header + 40))[4] = _spectrum; if (!cimg::strcasecmp(pixel_type(),"bool")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"char")) datatype = 2; if (!cimg::strcasecmp(pixel_type(),"unsigned short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"short")) datatype = 4; if (!cimg::strcasecmp(pixel_type(),"unsigned int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"int")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"unsigned long")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"long")) datatype = 8; if (!cimg::strcasecmp(pixel_type(),"float")) datatype = 16; if (!cimg::strcasecmp(pixel_type(),"double")) datatype = 64; if (datatype<0) throw CImgIOException(_cimg_instance "save_analyze(): Unsupported pixel type '%s' for file '%s'.", cimg_instance, pixel_type(),filename); ((short*)(header+70))[0] = datatype; ((short*)(header+72))[0] = sizeof(T); ((float*)(header+112))[0] = 1; ((float*)(header+76))[0] = 0; if (voxel_size) { ((float*)(header+76))[1] = voxel_size[0]; ((float*)(header+76))[2] = voxel_size[1]; ((float*)(header+76))[3] = voxel_size[2]; } else ((float*)(header+76))[1] = ((float*)(header+76))[2] = ((float*)(header+76))[3] = 1; file = cimg::fopen(hname,"wb"); cimg::fwrite(header,348,file); if (*iname) { cimg::fclose(file); file = cimg::fopen(iname,"wb"); } cimg::fwrite(_data,size(),file); cimg::fclose(file); return *this; } //! Save image as a .cimg file. /** \param filename Filename, as a C-string. \param is_compressed Tells if the file contains compressed image data. **/ const CImg<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(filename,is_compressed); return *this; } //! Save image as a .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const bool is_compressed=false) const { CImgList<T>(*this,true).save_cimg(file,is_compressed); return *this; } //! Save image as a sub-image into an existing .cimg file. /** \param filename Filename, as a C-string. \param n0 Index of the image inside the file. \param x0 X-coordinate of the sub-image location. \param y0 Y-coordinate of the sub-image location. \param z0 Z-coordinate of the sub-image location. \param c0 C-coordinate of the sub-image location. **/ const CImg<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(filename,n0,x0,y0,z0,c0); return *this; } //! Save image as a sub-image into an existing .cimg file \overloading. const CImg<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { CImgList<T>(*this,true).save_cimg(file,n0,x0,y0,z0,c0); return *this; } //! Save blank image as a .cimg file. /** \param filename Filename, as a C-string. \param dx Width of the image. \param dy Height of the image. \param dz Depth of the image. \param dc Number of channels of the image. \note - All pixel values of the saved image are set to \c 0. - Use this method to save large images without having to instanciate and allocate them. **/ static void save_empty_cimg(const char *const filename, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(filename,1,dx,dy,dz,dc); } //! Save blank image as a .cimg file \overloading. /** Same as save_empty_cimg(const char *,unsigned int,unsigned int,unsigned int,unsigned int) with a file stream argument instead of a filename string. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return CImgList<T>::save_empty_cimg(file,1,dx,dy,dz,dc); } //! Save image as an INRIMAGE-4 file. /** \param filename Filename, as a C-string. \param voxel_size Pointer to 3 values specifying the voxel sizes along the X,Y and Z dimensions. **/ const CImg<T>& save_inr(const char *const filename, const float *const voxel_size=0) const { return _save_inr(0,filename,voxel_size); } //! Save image as an INRIMAGE-4 file \overloading. const CImg<T>& save_inr(std::FILE *const file, const float *const voxel_size=0) const { return _save_inr(file,0,voxel_size); } const CImg<T>& _save_inr(std::FILE *const file, const char *const filename, const float *const voxel_size) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_inr(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_inr(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); int inrpixsize=-1; const char *inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; if (!cimg::strcasecmp(pixel_type(),"unsigned char")) { inrtype = "unsigned fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"char")) { inrtype = "fixed\nPIXSIZE=8 bits\nSCALE=2**0"; inrpixsize = 1; } if (!cimg::strcasecmp(pixel_type(),"unsigned short")) { inrtype = "unsigned fixed\nPIXSIZE=16 bits\nSCALE=2**0";inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"short")) { inrtype = "fixed\nPIXSIZE=16 bits\nSCALE=2**0"; inrpixsize = 2; } if (!cimg::strcasecmp(pixel_type(),"unsigned int")) { inrtype = "unsigned fixed\nPIXSIZE=32 bits\nSCALE=2**0";inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"int")) { inrtype = "fixed\nPIXSIZE=32 bits\nSCALE=2**0"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"float")) { inrtype = "float\nPIXSIZE=32 bits"; inrpixsize = 4; } if (!cimg::strcasecmp(pixel_type(),"double")) { inrtype = "float\nPIXSIZE=64 bits"; inrpixsize = 8; } if (inrpixsize<=0) throw CImgIOException(_cimg_instance "save_inr(): Unsupported pixel type '%s' for file '%s'", cimg_instance, pixel_type(),filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); char header[257] = { 0 }; int err = cimg_snprintf(header,sizeof(header),"#INRIMAGE-4#{\nXDIM=%u\nYDIM=%u\nZDIM=%u\nVDIM=%u\n",_width,_height,_depth,_spectrum); if (voxel_size) err+=std::sprintf(header + err,"VX=%g\nVY=%g\nVZ=%g\n",voxel_size[0],voxel_size[1],voxel_size[2]); err+=std::sprintf(header + err,"TYPE=%s\nCPU=%s\n",inrtype,cimg::endianness()?"sun":"decm"); std::memset(header + err,'\n',252 - err); std::memcpy(header + 252,"##}\n",4); cimg::fwrite(header,256,nfile); cimg_forXYZ(*this,x,y,z) cimg_forC(*this,c) cimg::fwrite(&((*this)(x,y,z,c)),1,nfile); if (!file) cimg::fclose(nfile); return *this; } //! Save image as an OpenEXR file. /** \param filename Filename, as a C-string. \note The OpenEXR file format is <a href="http://en.wikipedia.org/wiki/OpenEXR">described here</a>. **/ const CImg<T>& save_exr(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_exr(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_exr(): Empty instance, for file '%s'.", cimg_instance, filename); if (_depth>1) cimg::warn(_cimg_instance "save_exr(): Instance is volumetric, only the first slice will be saved in file '%s'.", cimg_instance, filename); #ifndef cimg_use_openexr return save_other(filename); #else Imf::Rgba *const ptrd0 = new Imf::Rgba[(unsigned long)_width*_height], *ptrd = ptrd0, rgba; switch (_spectrum) { case 1 : { // Grayscale image. for (const T *ptr_r = data(), *const ptr_e = ptr_r + (unsigned long)_width*_height; ptr_r<ptr_e;) { rgba.r = rgba.g = rgba.b = (half)(*(ptr_r++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 2 : { // RG image. for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *const ptr_e = ptr_r + (unsigned long)_width*_height; ptr_r<ptr_e; ) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)0; rgba.a = (half)1; *(ptrd++) = rgba; } } break; case 3 : { // RGB image. for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *const ptr_e = ptr_r + (unsigned long)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)1; *(ptrd++) = rgba; } } break; default : { // RGBA image. for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3), *const ptr_e = ptr_r + (unsigned long)_width*_height; ptr_r<ptr_e;) { rgba.r = (half)(*(ptr_r++)); rgba.g = (half)(*(ptr_g++)); rgba.b = (half)(*(ptr_b++)); rgba.a = (half)(*(ptr_a++)); *(ptrd++) = rgba; } } break; } Imf::RgbaOutputFile outFile(filename,_width,_height, _spectrum==1?Imf::WRITE_Y:_spectrum==2?Imf::WRITE_YA:_spectrum==3?Imf::WRITE_RGB:Imf::WRITE_RGBA); outFile.setFrameBuffer(ptrd0,1,_width); outFile.writePixels(_height); delete[] ptrd0; return *this; #endif } //! Save image as a Pandore-5 file. /** \param filename Filename, as a C-string. \param colorspace Colorspace data field in output file (see <a href="http://www.greyc.ensicaen.fr/~regis/Pandore/#documentation">Pandore file specifications</a> for more informations). **/ const CImg<T>& save_pandore(const char *const filename, const unsigned int colorspace=0) const { return _save_pandore(0,filename,colorspace); } //! Save image as a Pandore-5 file \overloading. /** Same as save_pandore(const char *,unsigned int) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_pandore(std::FILE *const file, const unsigned int colorspace=0) const { return _save_pandore(file,0,colorspace); } unsigned int _save_pandore_header_length(unsigned int id, unsigned int *dims, const unsigned int colorspace) const { unsigned int nbdims = 0; if (id==2 || id==3 || id==4) { dims[0] = 1; dims[1] = _width; nbdims = 2; } if (id==5 || id==6 || id==7) { dims[0] = 1; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==8 || id==9 || id==10) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } if (id==16 || id==17 || id==18) { dims[0] = 3; dims[1] = _height; dims[2] = _width; dims[3] = colorspace; nbdims = 4; } if (id==19 || id==20 || id==21) { dims[0] = 3; dims[1] = _depth; dims[2] = _height; dims[3] = _width; dims[4] = colorspace; nbdims = 5; } if (id==22 || id==23 || id==25) { dims[0] = _spectrum; dims[1] = _width; nbdims = 2; } if (id==26 || id==27 || id==29) { dims[0] = _spectrum; dims[1] = _height; dims[2] = _width; nbdims=3; } if (id==30 || id==31 || id==33) { dims[0] = _spectrum; dims[1] = _depth; dims[2] = _height; dims[3] = _width; nbdims = 4; } return nbdims; } const CImg<T>& _save_pandore(std::FILE *const file, const char *const filename, const unsigned int colorspace) const { #define __cimg_save_pandore_case(dtype) \ dtype *buffer = new dtype[size()]; \ const T *ptrs = _data; \ cimg_foroff(*this,off) *(buffer++) = (dtype)(*(ptrs++)); \ buffer-=size(); \ cimg::fwrite(buffer,size(),nfile); \ delete[] buffer #define _cimg_save_pandore_case(sy,sz,sv,stype,id) \ if (!saved && (sy?(sy==_height):true) && (sz?(sz==_depth):true) && (sv?(sv==_spectrum):true) && !std::strcmp(stype,pixel_type())) { \ unsigned int *iheader = (unsigned int*)(header+12); \ nbdims = _save_pandore_header_length((*iheader=id),dims,colorspace); \ cimg::fwrite(header,36,nfile); \ if (sizeof(unsigned long)==4) { unsigned long ndims[5] = { 0 }; for (int d = 0; d<5; ++d) ndims[d] = (unsigned long)dims[d]; cimg::fwrite(ndims,nbdims,nfile); } \ else if (sizeof(unsigned int)==4) { unsigned int ndims[5] = { 0 }; for (int d = 0; d<5; ++d) ndims[d] = (unsigned int)dims[d]; cimg::fwrite(ndims,nbdims,nfile); } \ else if (sizeof(unsigned short)==4) { unsigned short ndims[5] = { 0 }; for (int d = 0; d<5; ++d) ndims[d] = (unsigned short)dims[d]; cimg::fwrite(ndims,nbdims,nfile); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ if (id==2 || id==5 || id==8 || id==16 || id==19 || id==22 || id==26 || id==30) { \ __cimg_save_pandore_case(unsigned char); \ } else if (id==3 || id==6 || id==9 || id==17 || id==20 || id==23 || id==27 || id==31) { \ if (sizeof(unsigned long)==4) { __cimg_save_pandore_case(unsigned long); } \ else if (sizeof(unsigned int)==4) { __cimg_save_pandore_case(unsigned int); } \ else if (sizeof(unsigned short)==4) { __cimg_save_pandore_case(unsigned short); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } else if (id==4 || id==7 || id==10 || id==18 || id==21 || id==25 || id==29 || id==33) { \ if (sizeof(double)==4) { __cimg_save_pandore_case(double); } \ else if (sizeof(float)==4) { __cimg_save_pandore_case(float); } \ else throw CImgIOException(_cimg_instance \ "save_pandore(): Unsupported datatype for file '%s'.",\ cimg_instance, \ filename?filename:"(FILE*)"); \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_pandore(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_pandore(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); unsigned char header[36] = { 'P','A','N','D','O','R','E','0','4',0,0,0, 0,0,0,0,'C','I','m','g',0,0,0,0,0,'N','o',' ','d','a','t','e',0,0,0,0 }; unsigned int nbdims, dims[5] = { 0 }; bool saved = false; _cimg_save_pandore_case(1,1,1,"unsigned char",2); _cimg_save_pandore_case(1,1,1,"char",3); _cimg_save_pandore_case(1,1,1,"short",3); _cimg_save_pandore_case(1,1,1,"unsigned short",3); _cimg_save_pandore_case(1,1,1,"unsigned int",3); _cimg_save_pandore_case(1,1,1,"int",3); _cimg_save_pandore_case(1,1,1,"unsigned long",4); _cimg_save_pandore_case(1,1,1,"long",3); _cimg_save_pandore_case(1,1,1,"float",4); _cimg_save_pandore_case(1,1,1,"double",4); _cimg_save_pandore_case(0,1,1,"unsigned char",5); _cimg_save_pandore_case(0,1,1,"char",6); _cimg_save_pandore_case(0,1,1,"short",6); _cimg_save_pandore_case(0,1,1,"unsigned short",6); _cimg_save_pandore_case(0,1,1,"unsigned int",6); _cimg_save_pandore_case(0,1,1,"int",6); _cimg_save_pandore_case(0,1,1,"unsigned long",7); _cimg_save_pandore_case(0,1,1,"long",6); _cimg_save_pandore_case(0,1,1,"float",7); _cimg_save_pandore_case(0,1,1,"double",7); _cimg_save_pandore_case(0,0,1,"unsigned char",8); _cimg_save_pandore_case(0,0,1,"char",9); _cimg_save_pandore_case(0,0,1,"short",9); _cimg_save_pandore_case(0,0,1,"unsigned short",9); _cimg_save_pandore_case(0,0,1,"unsigned int",9); _cimg_save_pandore_case(0,0,1,"int",9); _cimg_save_pandore_case(0,0,1,"unsigned long",10); _cimg_save_pandore_case(0,0,1,"long",9); _cimg_save_pandore_case(0,0,1,"float",10); _cimg_save_pandore_case(0,0,1,"double",10); _cimg_save_pandore_case(0,1,3,"unsigned char",16); _cimg_save_pandore_case(0,1,3,"char",17); _cimg_save_pandore_case(0,1,3,"short",17); _cimg_save_pandore_case(0,1,3,"unsigned short",17); _cimg_save_pandore_case(0,1,3,"unsigned int",17); _cimg_save_pandore_case(0,1,3,"int",17); _cimg_save_pandore_case(0,1,3,"unsigned long",18); _cimg_save_pandore_case(0,1,3,"long",17); _cimg_save_pandore_case(0,1,3,"float",18); _cimg_save_pandore_case(0,1,3,"double",18); _cimg_save_pandore_case(0,0,3,"unsigned char",19); _cimg_save_pandore_case(0,0,3,"char",20); _cimg_save_pandore_case(0,0,3,"short",20); _cimg_save_pandore_case(0,0,3,"unsigned short",20); _cimg_save_pandore_case(0,0,3,"unsigned int",20); _cimg_save_pandore_case(0,0,3,"int",20); _cimg_save_pandore_case(0,0,3,"unsigned long",21); _cimg_save_pandore_case(0,0,3,"long",20); _cimg_save_pandore_case(0,0,3,"float",21); _cimg_save_pandore_case(0,0,3,"double",21); _cimg_save_pandore_case(1,1,0,"unsigned char",22); _cimg_save_pandore_case(1,1,0,"char",23); _cimg_save_pandore_case(1,1,0,"short",23); _cimg_save_pandore_case(1,1,0,"unsigned short",23); _cimg_save_pandore_case(1,1,0,"unsigned int",23); _cimg_save_pandore_case(1,1,0,"int",23); _cimg_save_pandore_case(1,1,0,"unsigned long",25); _cimg_save_pandore_case(1,1,0,"long",23); _cimg_save_pandore_case(1,1,0,"float",25); _cimg_save_pandore_case(1,1,0,"double",25); _cimg_save_pandore_case(0,1,0,"unsigned char",26); _cimg_save_pandore_case(0,1,0,"char",27); _cimg_save_pandore_case(0,1,0,"short",27); _cimg_save_pandore_case(0,1,0,"unsigned short",27); _cimg_save_pandore_case(0,1,0,"unsigned int",27); _cimg_save_pandore_case(0,1,0,"int",27); _cimg_save_pandore_case(0,1,0,"unsigned long",29); _cimg_save_pandore_case(0,1,0,"long",27); _cimg_save_pandore_case(0,1,0,"float",29); _cimg_save_pandore_case(0,1,0,"double",29); _cimg_save_pandore_case(0,0,0,"unsigned char",30); _cimg_save_pandore_case(0,0,0,"char",31); _cimg_save_pandore_case(0,0,0,"short",31); _cimg_save_pandore_case(0,0,0,"unsigned short",31); _cimg_save_pandore_case(0,0,0,"unsigned int",31); _cimg_save_pandore_case(0,0,0,"int",31); _cimg_save_pandore_case(0,0,0,"unsigned long",33); _cimg_save_pandore_case(0,0,0,"long",31); _cimg_save_pandore_case(0,0,0,"float",33); _cimg_save_pandore_case(0,0,0,"double",33); if (!file) cimg::fclose(nfile); return *this; } //! Save image as a raw data file. /** \param filename Filename, as a C-string. \param is_multiplexed Tells if the image channels are stored in a multiplexed way (\c true) or not (\c false). \note The .raw format does not store the image dimensions in the output file, so you have to keep track of them somewhere to be able to read the file correctly afterwards. **/ const CImg<T>& save_raw(const char *const filename, const bool is_multiplexed=false) const { return _save_raw(0,filename,is_multiplexed); } //! Save image as a raw data file \overloading. /** Same as save_raw(const char *,bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_raw(std::FILE *const file, const bool is_multiplexed=false) const { return _save_raw(file,0,is_multiplexed); } const CImg<T>& _save_raw(std::FILE *const file, const char *const filename, const bool is_multiplexed) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_raw(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_raw(): empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); if (!is_multiplexed) cimg::fwrite(_data,size(),nfile); else { CImg<T> buf(_spectrum); cimg_forXYZ(*this,x,y,z) { cimg_forC(*this,c) buf[c] = (*this)(x,y,z,c); cimg::fwrite(buf._data,_spectrum,nfile); } } if (!file) cimg::fclose(nfile); return *this; } //! Save image as a video file, using the FFmpeg library. /** \param filename Filename, as a C-string. \param fps Video framerate. \param bitrate Video bitrate. \note - Each slice of the instance image is considered to be a single frame of the output video file. - This method uses functions provided by the <a href="http://www.ffmpeg.org">FFmpeg</a> library. Configuration macro \c cimg_use_ffmpeg must be set for the method to succeed natively. Otherwise, the method calls save_ffmpeg_external(const char*,unsigned int,unsigned int,const char*,unsigned int,unsigned int) const. **/ const CImg<T>& save_ffmpeg(const char *const filename, const unsigned int fps=25, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_ffmpeg(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_ffmpeg(): Empty instance, for file '%s'.", cimg_instance, filename); if (!fps) throw CImgArgumentException(_cimg_instance "save_ffmpeg(): Invalid specified framerate 0, for file '%s'.", cimg_instance, filename); #ifndef cimg_use_ffmpeg return save_ffmpeg_external(filename,0,fps,bitrate); #else CImgList<T> list; get_split('z').move_to(list); list.save_ffmpeg(filename,fps,bitrate); #endif return *this; } //! Save image as a .yuv video file. /** \param filename Filename, as a C-string. \param is_rgb Tells if pixel values of the instance image are RGB-coded (\c true) or YUV-coded (\c false). \note Each slice of the instance image is considered to be a single frame of the output video file. **/ const CImg<T>& save_yuv(const char *const filename, const bool is_rgb=true) const { get_split('z').save_yuv(filename,is_rgb); return *this; } //! Save image as a .yuv video file \overloading. /** Same as save_yuv(const char*,bool) const with a file stream argument instead of a filename string. **/ const CImg<T>& save_yuv(std::FILE *const file, const bool is_rgb=true) const { get_split('z').save_yuv(file,is_rgb); return *this; } //! Save 3d object as an Object File Format (.off) file. /** \param filename Filename, as a C-string. \param primitives List of 3d object primitives. \param colors List of 3d object colors. \note - Instance image contains the vertices data of the 3d object. - Textured, transparent or sphere-shaped primitives cannot be managed by the .off file format. Such primitives will be lost or simplified during file saving. - The .off file format is <a href="http://people.sc.fsu.edu/~jburkardt/html/off_format.html">described here</a>. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, const char *const filename) const { return _save_off(primitives,colors,0,filename); } //! Save 3d object as an Object File Format (.off) file \overloading. /** Same as save_off(const CImgList<tf>&,const CImgList<tc>&,const char*) const with a file stream argument instead of a filename string. **/ template<typename tf, typename tc> const CImg<T>& save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file) const { return _save_off(primitives,colors,file,0); } template<typename tf, typename tc> const CImg<T>& _save_off(const CImgList<tf>& primitives, const CImgList<tc>& colors, std::FILE *const file, const char *const filename) const { if (!file && !filename) throw CImgArgumentException(_cimg_instance "save_off(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_off(): Empty instance, for file '%s'.", cimg_instance, filename?filename:"(FILE*)"); CImgList<T> opacities; char error_message[1024] = { 0 }; if (!is_object3d(primitives,colors,opacities,true,error_message)) throw CImgInstanceException(_cimg_instance "save_off(): Invalid specified 3d object, for file '%s' (%s).", cimg_instance, filename?filename:"(FILE*)",error_message); const CImg<tc> default_color(1,3,1,1,200); std::FILE *const nfile = file?file:cimg::fopen(filename,"w"); unsigned int supported_primitives = 0; cimglist_for(primitives,l) if (primitives[l].size()!=5) ++supported_primitives; std::fprintf(nfile,"OFF\n%u %u %u\n",_width,supported_primitives,3*primitives._width); cimg_forX(*this,i) std::fprintf(nfile,"%f %f %f\n",(float)((*this)(i,0)),(float)((*this)(i,1)),(float)((*this)(i,2))); cimglist_for(primitives,l) { const CImg<tc>& color = l<colors.width()?colors[l]:default_color; const unsigned int psiz = primitives[l].size(), csiz = color.size(); const float r = color[0]/255.0f, g = (csiz>1?color[1]:r)/255.0f, b = (csiz>2?color[2]:g)/255.0f; switch (psiz) { case 1 : std::fprintf(nfile,"1 %u %f %f %f\n",(unsigned int)primitives(l,0),r,g,b); break; case 2 : std::fprintf(nfile,"2 %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 3 : std::fprintf(nfile,"3 %u %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),r,g,b); break; case 4 : std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),r,g,b); break; case 5 : std::fprintf(nfile,"2 %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,1),r,g,b); break; case 6 : { const unsigned int xt = (unsigned int)primitives(l,2), yt = (unsigned int)primitives(l,3); const float rt = color.atXY(xt,yt,0)/255.0f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.0f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.0f; std::fprintf(nfile,"2 %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,1),rt,gt,bt); } break; case 9 : { const unsigned int xt = (unsigned int)primitives(l,3), yt = (unsigned int)primitives(l,4); const float rt = color.atXY(xt,yt,0)/255.0f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.0f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.0f; std::fprintf(nfile,"3 %u %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,2), (unsigned int)primitives(l,1),rt,gt,bt); } break; case 12 : { const unsigned int xt = (unsigned int)primitives(l,4), yt = (unsigned int)primitives(l,5); const float rt = color.atXY(xt,yt,0)/255.0f, gt = (csiz>1?color.atXY(xt,yt,1):r)/255.0f, bt = (csiz>2?color.atXY(xt,yt,2):g)/255.0f; std::fprintf(nfile,"4 %u %u %u %u %f %f %f\n",(unsigned int)primitives(l,0),(unsigned int)primitives(l,3), (unsigned int)primitives(l,2),(unsigned int)primitives(l,1),rt,gt,bt); } break; } } if (!file) cimg::fclose(nfile); return *this; } //! Save volumetric image as a video, using ffmpeg external binary. /** \param filename Filename, as a C-string. \param codec Video codec, as a C-string. \param fps Video framerate. \param bitrate Video bitrate. \note - Each slice of the instance image is considered to be a single frame of the output video file. - This method uses \c ffmpeg, an external executable binary provided by <a href="http://www.ffmpeg.org">FFmpeg</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_ffmpeg_external(const char *const filename, const char *const codec=0, const unsigned int fps=25, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_ffmpeg_external(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_ffmpeg_external(): Empty instance, for file '%s'.", cimg_instance, filename); CImgList<T> list; get_split('z').move_to(list); list.save_ffmpeg_external(filename,codec,fps,bitrate); return *this; } //! Save image using gzip external binary. /** \param filename Filename, as a C-string. \note This method uses \c gzip, an external executable binary provided by <a href="//http://www.gzip.org">gzip</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_gzip_external(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_gzip_external(): Empty instance, for file '%s'.", cimg_instance, filename); char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.cimg",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.cimg",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); save(filetmp); cimg_snprintf(command,sizeof(command),"%s -c %s > \"%s\"",cimg::gzip_path(),filetmp,filename); cimg::system(command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimg_instance, filename); else cimg::fclose(file); std::remove(filetmp); return *this; } //! Save image using GraphicsMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c gm, an external executable binary provided by <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_graphicsmagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_graphicsmagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_graphicsmagick_external(): Empty instance, for file '%s'.", cimg_instance, filename); char command[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file; do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),_spectrum==1?"pgm":"ppm"); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); save_pnm(filetmp); cimg_snprintf(command,sizeof(command),"%s convert -quality %u \"%s\" \"%s\"",cimg::graphicsmagick_path(),quality,filetmp,filename); cimg::system(command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_graphicsmagick_external(): Failed to save file '%s' with external command 'gm'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filetmp); return *this; } //! Save image using ImageMagick's external binary. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note This method uses \c convert, an external executable binary provided by <a href="http://www.imagemagick.org">ImageMagick</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_imagemagick_external(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_imagemagick_external(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_imagemagick_external(): Empty instance, for file '%s'.", cimg_instance, filename); char command[1024] = { 0 }, filetmp[512] = { 0 }; std::FILE *file; do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),_spectrum==1?"pgm":"ppm"); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); save_pnm(filetmp); cimg_snprintf(command,sizeof(command),"%s -quality %u \"%s\" \"%s\"",cimg::imagemagick_path(),quality,filetmp,filename); cimg::system(command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimg_instance "save_imagemagick_external(): Failed to save file '%s' with external command 'convert'.", cimg_instance, filename); if (file) cimg::fclose(file); std::remove(filetmp); return *this; } //! Save image as a Dicom file. /** \param filename Filename, as a C-string. \note This method uses \c medcon, an external executable binary provided by <a href="http://xmedcon.sourceforge.net">(X)Medcon</a>. It must be installed for the method to succeed. **/ const CImg<T>& save_medcon_external(const char *const filename) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_medcon_external(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_medcon_external(): Empty instance, for file '%s'.", cimg_instance, filename); char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; std::FILE *file; do { cimg_snprintf(filetmp,sizeof(filetmp),"%s.hdr",cimg::filenamerand()); if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); save_analyze(filetmp); cimg_snprintf(command,sizeof(command),"%s -w -c dicom -o %s -f %s",cimg::medcon_path(),filename,filetmp); cimg::system(command); std::remove(filetmp); cimg::split_filename(filetmp,body); cimg_snprintf(filetmp,sizeof(filetmp),"%s.img",body); std::remove(filetmp); file = std::fopen(filename,"rb"); if (!file) { cimg_snprintf(command,sizeof(command),"m000-%s",filename); file = std::fopen(command,"rb"); if (!file) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimg_instance "save_medcon_external(): Failed to save file '%s' with external command 'medcon'.", cimg_instance, filename); } } cimg::fclose(file); std::rename(command,filename); return *this; } // Save image for non natively supported formats. /** \param filename Filename, as a C-string. \param quality Image quality (expressed in percent), when the file format supports it. \note - The filename extension tells about the desired file format. - This method tries to save the instance image as a file, using external tools from <a href="http://www.imagemagick.org">ImageMagick</a> or <a href="http://www.graphicsmagick.org">GraphicsMagick</a>. At least one of these tool must be installed for the method to succeed. - It is recommended to use the generic method save(const char*, int) const instead, as it can handle some file formats natively. **/ const CImg<T>& save_other(const char *const filename, const unsigned int quality=100) const { if (!filename) throw CImgArgumentException(_cimg_instance "save_other(): Specified filename is (null).", cimg_instance); if (is_empty()) throw CImgInstanceException(_cimg_instance "save_other(): Empty instance, for file '%s'.", cimg_instance, filename); const unsigned int omode = cimg::exception_mode(); bool is_saved = true; cimg::exception_mode() = 0; try { save_magick(filename); } catch (CImgException&) { try { save_imagemagick_external(filename,quality); } catch (CImgException&) { try { save_graphicsmagick_external(filename,quality); } catch (CImgException&) { is_saved = false; } } } cimg::exception_mode() = omode; if (!is_saved) throw CImgIOException(_cimg_instance "save_other(): Failed to save file '%s'. Format is not natively supported, and no external commands succeeded.", cimg_instance, filename); return *this; } // [internal] Return a 40x38 color logo of a 'danger' item. static CImg<T> _logo40x38() { static bool first_time = true; static CImg<T> res(40,38,1,3); if (first_time) { const unsigned char *ptrs = cimg::logo40x38; T *ptr1 = res.data(0,0,0,0), *ptr2 = res.data(0,0,0,1), *ptr3 = res.data(0,0,0,2); for (unsigned long off = 0; off<(unsigned long)res._width*res._height;) { const unsigned char n = *(ptrs++), r = *(ptrs++), g = *(ptrs++), b = *(ptrs++); for (unsigned int l = 0; l<n; ++off, ++l) { *(ptr1++) = (T)r; *(ptr2++) = (T)g; *(ptr3++) = (T)b; } } first_time = false; } return res; } //@} }; /* #----------------------------------------- # # # # Definition of the CImgList<T> structure # # # #------------------------------------------ */ //! Represent a list of images CImg<T>. template<typename T> struct CImgList { unsigned int _width, _allocated_width; CImg<T> *_data; //! Simple iterator type, to loop through each image of a list. /** \note - The \c CImgList<T>::iterator type is defined as a <tt>CImg<T>*</tt>. - You may use it like this: \code CImgList<> list; // Assuming this image list is not empty. for (CImgList<>::iterator it = list.begin(); it<list.end(); ++it) (*it).mirror('x'); \endcode - Using the loop macro \c cimglist_for is another (more concise) alternative: \code cimglist_for(list,l) list[l].mirror('x'); \endcode **/ typedef CImg<T>* iterator; //! Simple const iterator type, to loop through each image of a \c const list instance. /** \note - The \c CImgList<T>::const_iterator type is defined to be a <tt>const CImg<T>*</tt>. - Similar to CImgList<T>::iterator, but for constant list instances. **/ typedef const CImg<T>* const_iterator; //! Pixel value type. /** Refer to the pixels value type of the images in the list. \note - The \c CImgList<T>::value_type type of a \c CImgList<T> is defined to be a \c T. It is then similar to CImg<T>::value_type. - \c CImgList<T>::value_type is actually not used in %CImg methods. It has been mainly defined for compatibility with STL naming conventions. **/ typedef T value_type; // Define common T-dependant types. typedef typename cimg::superset<T,bool>::type Tbool; typedef typename cimg::superset<T,unsigned char>::type Tuchar; typedef typename cimg::superset<T,char>::type Tchar; typedef typename cimg::superset<T,unsigned short>::type Tushort; typedef typename cimg::superset<T,short>::type Tshort; typedef typename cimg::superset<T,unsigned int>::type Tuint; typedef typename cimg::superset<T,int>::type Tint; typedef typename cimg::superset<T,unsigned long>::type Tulong; typedef typename cimg::superset<T,long>::type Tlong; typedef typename cimg::superset<T,float>::type Tfloat; typedef typename cimg::superset<T,double>::type Tdouble; typedef typename cimg::last<T,bool>::type boolT; typedef typename cimg::last<T,unsigned char>::type ucharT; typedef typename cimg::last<T,char>::type charT; typedef typename cimg::last<T,unsigned short>::type ushortT; typedef typename cimg::last<T,short>::type shortT; typedef typename cimg::last<T,unsigned int>::type uintT; typedef typename cimg::last<T,int>::type intT; typedef typename cimg::last<T,unsigned long>::type ulongT; typedef typename cimg::last<T,long>::type longT; typedef typename cimg::last<T,float>::type floatT; typedef typename cimg::last<T,double>::type doubleT; //@} //--------------------------- // //! \name Plugins //@{ //--------------------------- #ifdef cimglist_plugin #include cimglist_plugin #endif #ifdef cimglist_plugin1 #include cimglist_plugin1 #endif #ifdef cimglist_plugin2 #include cimglist_plugin2 #endif #ifdef cimglist_plugin3 #include cimglist_plugin3 #endif #ifdef cimglist_plugin4 #include cimglist_plugin4 #endif #ifdef cimglist_plugin5 #include cimglist_plugin5 #endif #ifdef cimglist_plugin6 #include cimglist_plugin6 #endif #ifdef cimglist_plugin7 #include cimglist_plugin7 #endif #ifdef cimglist_plugin8 #include cimglist_plugin8 #endif //@} //-------------------------------------------------------- // //! \name Constructors / Destructor / Instance Management //@{ //-------------------------------------------------------- //! Destructor. /** Destroy current list instance. \note - Any allocated buffer is deallocated. - Destroying an empty list does nothing actually. **/ ~CImgList() { delete[] _data; } //! Default constructor. /** Construct a new empty list instance. \note - An empty list has no pixel data and its dimension width() is set to \c 0, as well as its image buffer pointer data(). - An empty list may be reassigned afterwards, with the family of the assign() methods. In all cases, the type of pixels stays \c T. **/ CImgList(): _width(0),_allocated_width(0),_data(0) {} //! Construct list containing empty images. /** \param n Number of empty images. \note Useful when you know by advance the number of images you want to manage, as it will allocate the right amount of memory for the list, without needs for reallocation (that may occur when starting from an empty list and inserting several images in it). **/ explicit CImgList(const unsigned int n):_width(n) { if (n) _data = new CImg<T>[_allocated_width = cimg::max(16UL,cimg::nearest_pow2(n))]; else { _allocated_width = 0; _data = 0; } } //! Construct list containing images of specified size. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \note Pixel values are not initialized and may probably contain garbage. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); } //! Construct list containing images of specified size, and initialize pixel values. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val Initialization value for images pixels. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T val): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of integers. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing integers sequence. \param val1 Second value of the initializing integers sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...): _width(0),_allocated_width(0),_data(0) { #define _CImgList_stdarg(t) { \ assign(n,width,height,depth,spectrum); \ const unsigned long siz = (unsigned long)width*height*depth*spectrum, nsiz = siz*n; \ T *ptrd = _data->_data; \ va_list ap; \ va_start(ap,val1); \ for (unsigned long l = 0, s = 0, i = 0; i<nsiz; ++i) { \ *(ptrd++) = (T)(i==0?val0:(i==1?val1:va_arg(ap,t))); \ if ((++s)==siz) { ptrd = _data[++l]._data; s = 0; } \ } \ va_end(ap); \ } _CImgList_stdarg(int); } //! Construct list containing images of specified size, and initialize pixel values from a sequence of doubles. /** \param n Number of images. \param width Width of images. \param height Height of images. \param depth Depth of images. \param spectrum Number of channels of images. \param val0 First value of the initializing doubles sequence. \param val1 Second value of the initializing doubles sequence. \warning You must specify at least <tt>width*height*depth*spectrum</tt> values in your argument list, or you will probably segfault. **/ CImgList(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...): _width(0),_allocated_width(0),_data(0) { _CImgList_stdarg(double); } //! Construct list containing copies of an input image. /** \param n Number of images. \param img Input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of \c img. **/ template<typename t> CImgList(const unsigned int n, const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(n); cimglist_apply(*this,assign)(img,is_shared); } //! Construct list from one image. /** \param img Input image to copy in the constructed list. \param is_shared Tells if the element of the list is a shared or non-shared copy of \c img. **/ template<typename t> explicit CImgList(const CImg<t>& img, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(1); _data[0].assign(img,is_shared); } //! Construct list from two images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); } //! Construct list from three images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); } //! Construct list from four images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); } //! Construct list from five images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); } //! Construct list from six images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); } //! Construct list from seven images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); } //! Construct list from eight images. /** \param img1 First input image to copy in the constructed list. \param img2 Second input image to copy in the constructed list. \param img3 Third input image to copy in the constructed list. \param img4 Fourth input image to copy in the constructed list. \param img5 Fifth input image to copy in the constructed list. \param img6 Sixth input image to copy in the constructed list. \param img7 Seventh input image to copy in the constructed list. \param img8 Eighth input image to copy in the constructed list. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false): _width(0),_allocated_width(0),_data(0) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); } //! Construct list copy. /** \param list Input list to copy. \note The shared state of each element of the constructed list is kept the same as in \c list. **/ template<typename t> CImgList(const CImgList<t>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); } //! Construct list copy \specialization. CImgList(const CImgList<T>& list):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],list[l]._is_shared); } //! Construct list copy, and force the shared state of the list elements. /** \param list Input list to copy. \param is_shared Tells if the elements of the list are shared or non-shared copies of input images. **/ template<typename t> CImgList(const CImgList<t>& list, const bool is_shared):_width(0),_allocated_width(0),_data(0) { assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],is_shared); } //! Construct list by reading the content of a file. /** \param filename Filename, as a C-string. **/ explicit CImgList(const char *const filename):_width(0),_allocated_width(0),_data(0) { assign(filename); } //! Construct list from the content of a display window. /** \param disp Display window to get content from. \note Constructed list contains a single image only. **/ explicit CImgList(const CImgDisplay& disp):_width(0),_allocated_width(0),_data(0) { assign(disp); } //! Return a list with elements being shared copies of images in the list instance. /** \note <tt>list2 = list1.get_shared()</tt> is equivalent to <tt>list2.assign(list1,true)</tt>. **/ CImgList<T> get_shared() { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Return a list with elements being shared copies of images in the list instance \const. const CImgList<T> get_shared() const { CImgList<T> res(_width); cimglist_for(*this,l) res[l].assign(_data[l],true); return res; } //! Destructor \inplace. /** \see CImgList(). **/ CImgList<T>& assign() { delete[] _data; _width = _allocated_width = 0; _data = 0; return *this; } //! Destructor \inplace. /** Equivalent to assign(). \note Only here for compatibility with STL naming conventions. **/ CImgList<T>& clear() { return assign(); } //! Construct list containing empty images \inplace. /** \see CImgList(unsigned int). **/ CImgList<T>& assign(const unsigned int n) { if (!n) return assign(); if (_allocated_width<n || _allocated_width>(n<<2)) { delete[] _data; _data = new CImg<T>[_allocated_width=cimg::max(16UL,cimg::nearest_pow2(n))]; } _width = n; return *this; } //! Construct list containing images of specified size \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height=1, const unsigned int depth=1, const unsigned int spectrum=1) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum); return *this; } //! Construct list containing images of specified size, and initialize pixel values \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const T). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const T val) { assign(n); cimglist_apply(*this,assign)(width,height,depth,spectrum,val); return *this; } //! Construct list containing images of specified size, and initialize pixel values from a sequence of integers \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const int, const int, ...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const int val0, const int val1, ...) { _CImgList_stdarg(int); return *this; } //! Construct list containing images of specified size, and initialize pixel values from a sequence of doubles \inplace. /** \see CImgList(unsigned int, unsigned int, unsigned int, unsigned int, unsigned int, const double, const double, ...). **/ CImgList<T>& assign(const unsigned int n, const unsigned int width, const unsigned int height, const unsigned int depth, const unsigned int spectrum, const double val0, const double val1, ...) { _CImgList_stdarg(double); return *this; } //! Construct list containing copies of an input image \inplace. /** \see CImgList(unsigned int, const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const unsigned int n, const CImg<t>& img, const bool is_shared=false) { assign(n); cimglist_apply(*this,assign)(img,is_shared); return *this; } //! Construct list from one image \inplace. /** \see CImgList(const CImg<t>&, bool). **/ template<typename t> CImgList<T>& assign(const CImg<t>& img, const bool is_shared=false) { assign(1); _data[0].assign(img,is_shared); return *this; } //! Construct list from two images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const bool is_shared=false) { assign(2); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); return *this; } //! Construct list from three images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false) { assign(3); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); return *this; } //! Construct list from four images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const bool is_shared=false) { assign(4); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); return *this; } //! Construct list from five images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const bool is_shared=false) { assign(5); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); return *this; } //! Construct list from six images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const bool is_shared=false) { assign(6); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); return *this; } //! Construct list from seven images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false) { assign(7); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); return *this; } //! Construct list from eight images \inplace. /** \see CImgList(const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, const CImg<t>&, bool). **/ template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7, typename t8> CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4, const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const CImg<t8>& img8, const bool is_shared=false) { assign(8); _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared); _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared); _data[6].assign(img7,is_shared); _data[7].assign(img8,is_shared); return *this; } //! Construct list as a copy of an existing list and force the shared state of the list elements \inplace. /** \see CImgList(const CImgList<t>&, bool is_shared). **/ template<typename t> CImgList<T>& assign(const CImgList<t>& list, const bool is_shared=false) { cimg::unused(is_shared); assign(list._width); cimglist_for(*this,l) _data[l].assign(list[l],false); return *this; } //! Construct list as a copy of an existing list and force the shared state of the list elements \inplace \specialization. CImgList<T>& assign(const CImgList<T>& list, const bool is_shared=false) { if (this==&list) return *this; CImgList<T> res(list._width); cimglist_for(res,l) res[l].assign(list[l],is_shared); return res.move_to(*this); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& assign(const char *const filename) { return load(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& assign(const CImgDisplay &disp) { return assign(CImg<T>(disp)); } //! Transfer the content of the list instance to another list. /** \param list Destination list. \note When returning, the current list instance is empty and the initial content of \c list is destroyed. **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list) { list.assign(_width); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[l]); assign(); return list; } //! Transfer the content of the list instance at a specified position in another list. /** \param list Destination list. \param pos Index of the insertion in the list. \note When returning, the list instance is empty and the initial content of \c list is preserved (only images indexes may be modified). **/ template<typename t> CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos) { if (is_empty()) return list; const unsigned int npos = pos>list._width?list._width:pos; list.insert(_width,npos); bool is_one_shared_element = false; cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared; if (is_one_shared_element) cimglist_for(*this,l) list[npos+l].assign(_data[l]); else cimglist_for(*this,l) _data[l].move_to(list[npos+l]); assign(); return list; } //! Swap all fields between two list instances. /** \param list List to swap fields with. \note Can be used to exchange the content of two lists in a fast way. **/ CImgList<T>& swap(CImgList<T>& list) { cimg::swap(_width,list._width); cimg::swap(_allocated_width,list._allocated_width); cimg::swap(_data,list._data); return list; } //! Return a reference to an empty list. /** \note Can be used to define default values in a function taking a CImgList<T> as an argument. \code void f(const CImgList<char>& list=CImgList<char>::empty()); \endcode **/ static CImgList<T>& empty() { static CImgList<T> _empty; return _empty.assign(); } //@} //------------------------------------------ // //! \name Overloaded Operators //@{ //------------------------------------------ //! Return a reference to one image element of the list. /** \param pos Indice of the image element. **/ CImg<T>& operator()(const unsigned int pos) { #if cimg_verbosity>=3 if (pos>=_width) { cimg::warn(_cimglist_instance "operator(): Invalid image request, at position [%u].", cimglist_instance, pos); return *_data; } #endif return _data[pos]; } //! Return a reference to one image of the list. /** \param pos Indice of the image element. **/ const CImg<T>& operator()(const unsigned int pos) const { return const_cast<CImgList<T>*>(this)->operator()(pos); } //! Return a reference to one pixel value of one image of the list. /** \param pos Indice of the image element. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list(n,x,y,z,c)</tt> is equivalent to <tt>list[n](x,y,z,c)</tt>. **/ T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) { return (*this)[pos](x,y,z,c); } //! Return a reference to one pixel value of one image of the list \const. const T& operator()(const unsigned int pos, const unsigned int x, const unsigned int y=0, const unsigned int z=0, const unsigned int c=0) const { return (*this)[pos](x,y,z,c); } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ operator CImg<T>*() { return _data; } //! Return pointer to the first image of the list \const. operator const CImg<T>*() const { return _data; } //! Construct list from one image \inplace. /** \param img Input image to copy in the constructed list. \note <tt>list = img;</tt> is equivalent to <tt>list.assign(img);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImg<t>& img) { return assign(img); } //! Construct list from another list. /** \param list Input list to copy. \note <tt>list1 = list2</tt> is equivalent to <tt>list1.assign(list2);</tt>. **/ template<typename t> CImgList<T>& operator=(const CImgList<t>& list) { return assign(list); } //! Construct list from another list \specialization. CImgList<T>& operator=(const CImgList<T>& list) { return assign(list); } //! Construct list by reading the content of a file \inplace. /** \see CImgList(const char *const). **/ CImgList<T>& operator=(const char *const filename) { return assign(filename); } //! Construct list from the content of a display window \inplace. /** \see CImgList(const CImgDisplay&). **/ CImgList<T>& operator=(const CImgDisplay& disp) { return assign(disp); } //! Return a non-shared copy of a list. /** \note <tt>+list</tt> is equivalent to <tt>CImgList<T>(list,false)</tt>. It forces the copy to have non-shared elements. **/ CImgList<T> operator+() const { return CImgList<T>(*this,false); } //! Return a copy of the list instance, where image \c img has been inserted at the end. /** \param img Image inserted at the end of the instance copy. \note Define a convenient way to create temporary lists of images, as in the following code: \code (img1,img2,img3,img4).display("My four images"); \endcode **/ template<typename t> CImgList<T>& operator,(const CImg<t>& img) { return insert(img); } //! Return a copy of the list instance, where all elements of input list \c list have been inserted at the end. /** \param list List inserted at the end of the instance copy. **/ template<typename t> CImgList<T>& operator,(const CImgList<t>& list) { return insert(list); } //! Return image corresponding to the appending of all images of the instance list along specified axis. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \note <tt>list>'x'</tt> is equivalent to <tt>list.get_append('x')</tt>. **/ CImg<T> operator>(const char axis) const { return get_append(axis,0); } //! Return list corresponding to the splitting of all images of the instance list along specified axis. /** \param axis Axis used for image splitting. \note <tt>list<'x'</tt> is equivalent to <tt>list.get_split('x')</tt>. **/ CImgList<T> operator<(const char axis) const { return get_split(axis); } //@} //------------------------------------- // //! \name Instance Characteristics //@{ //------------------------------------- //! Return the type of image pixel values as a C string. /** Return a \c char* string containing the usual type name of the image pixel values (i.e. a stringified version of the template parameter \c T). \note - The returned string may contain spaces (as in \c "unsigned char"). - If the pixel type \c T does not correspond to a registered type, the string <tt>"unknown"</tt> is returned. **/ static const char* pixel_type() { return cimg::type<T>::string(); } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to size() but returns result as a (signed) integer. **/ int width() const { return (int)_width; } //! Return the size of the list, i.e. the number of images contained in it. /** \note Similar to width() but returns result as an unsigned integer. **/ unsigned int size() const { return _width; } //! Return pointer to the first image of the list. /** \note Images in a list are stored as a buffer of \c CImg<T>. **/ CImg<T> *data() { return _data; } //! Return pointer to the first image of the list \const. const CImg<T> *data() const { return _data; } //! Return pointer to the pos-th image of the list. /** \param pos Indice of the image element to access. \note <tt>list.data(n);</tt> is equivalent to <tt>list.data + n;</tt>. **/ #if cimg_verbosity>=3 CImg<T> *data(const unsigned int pos) { if (pos>=size()) { cimg::warn(_cimglist_instance "data(): Invalid pointer request, at position [%u].", cimglist_instance, pos); return _data; } return _data + pos; } const CImg<T> *data(const unsigned int l) const { return const_cast<CImgList<T>*>(this)->data(l); } #else CImg<T> *data(const unsigned int l) { return _data + l; } //! Return pointer to the pos-th image of the list \const. const CImg<T> *data(const unsigned int l) const { return _data + l; } #endif //! Return iterator to the first image of the list. /** **/ iterator begin() { return _data; } //! Return iterator to the first image of the list \const. const_iterator begin() const { return _data; } //! Return iterator to one position after the last image of the list. /** **/ iterator end() { return _data + _width; } //! Return iterator to one position after the last image of the list \const. const_iterator end() const { return _data + _width; } //! Return reference to the first image of the list. /** **/ CImg<T>& front() { return *_data; } //! Return reference to the first image of the list \const. const CImg<T>& front() const { return *_data; } //! Return a reference to the last image of the list. /** **/ const CImg<T>& back() const { return *(_data + _width - 1); } //! Return a reference to the last image of the list \const. CImg<T>& back() { return *(_data + _width - 1); } //! Return pos-th image of the list. /** \param pos Indice of the image element to access. **/ CImg<T>& at(const int pos) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "at(): Empty instance.", cimglist_instance); return _data[pos<0?0:pos>=(int)_width?(int)_width-1:pos]; } //! Access to pixel value with Dirichlet boundary conditions. /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T out_value) { return (pos<0 || pos>=(int)_width)?(cimg::temporary(out_value)=out_value):_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c, const T out_value) const { return (pos<0 || pos>=(int)_width)?out_value:_data[pos].atXYZC(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions. /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZC(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZC(x,y,z,c);</tt>. **/ T& atNXYZC(const int pos, const int x, const int y, const int z, const int c) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions \const. T atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZC(): Empty instance.", cimglist_instance); return _atNXYZC(pos,x,y,z,c); } T& _atNXYZC(const int pos, const int x, const int y, const int z, const int c) { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXYZC(x,y,z,c); } T _atNXYZC(const int pos, const int x, const int y, const int z, const int c) const { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXYZC(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the three first coordinates (\c pos, \c x,\c y,\c z). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T out_value) { return (pos<0 || pos>=(int)_width)?(cimg::temporary(out_value)=out_value):_data[pos].atXYZ(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the three first coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c, const T out_value) const { return (pos<0 || pos>=(int)_width)?out_value:_data[pos].atXYZ(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the four first coordinates (\c pos, \c x,\c y,\c z). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the four first coordinates (\c pos, \c x,\c y,\c z) \const. T atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXYZ(): Empty instance.", cimglist_instance); return _atNXYZ(pos,x,y,z,c); } T& _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXYZ(x,y,z,c); } T _atNXYZ(const int pos, const int x, const int y, const int z, const int c=0) const { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXYZ(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the three first coordinates (\c pos, \c x,\c y). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z, const int c, const T out_value) { return (pos<0 || pos>=(int)_width)?(cimg::temporary(out_value)=out_value):_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the three first coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z, const int c, const T out_value) const { return (pos<0 || pos>=(int)_width)?out_value:_data[pos].atXY(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the three first coordinates (\c pos, \c x,\c y). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the three first coordinates (\c pos, \c x,\c y) \const. T atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNXY(): Empty instance.", cimglist_instance); return _atNXY(pos,x,y,z,c); } T& _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXY(x,y,z,c); } T _atNXY(const int pos, const int x, const int y, const int z=0, const int c=0) const { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atXY(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the two first coordinates (\c pos,\c x). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y, const int z, const int c, const T out_value) { return (pos<0 || pos>=(int)_width)?(cimg::temporary(out_value)=out_value):_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Dirichlet boundary conditions for the two first coordinates (\c pos,\c x) \const. T atNX(const int pos, const int x, const int y, const int z, const int c, const T out_value) const { return (pos<0 || pos>=(int)_width)?out_value:_data[pos].atX(x,y,z,c,out_value); } //! Access to pixel value with Neumann boundary conditions for the two first coordinates (\c pos, \c x). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } //! Access to pixel value with Neumann boundary conditions for the two first coordinates (\c pos, \c x) \const. T atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atNX(): Empty instance.", cimglist_instance); return _atNX(pos,x,y,z,c); } T& _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atX(x,y,z,c); } T _atNX(const int pos, const int x, const int y=0, const int z=0, const int c=0) const { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)].atX(x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the first coordinates (\c pos). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \param out_value Default value returned if \c offset is outside image bounds. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x, const int y, const int z, const int c, const T out_value) { return (pos<0 || pos>=(int)_width)?(cimg::temporary(out_value)=out_value):(*this)(pos,x,y,z,c); } //! Access to pixel value with Dirichlet boundary conditions for the first coordinates (\c pos) \const. T atN(const int pos, const int x, const int y, const int z, const int c, const T out_value) const { return (pos<0 || pos>=(int)_width)?out_value:(*this)(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the first coordinates (\c pos). /** \param pos Indice of the image element to access. \param x X-coordinate of the pixel value. \param y Y-coordinate of the pixel value. \param z Z-coordinate of the pixel value. \param c C-coordinate of the pixel value. \note <tt>list.atNXYZ(p,x,y,z,c);</tt> is equivalent to <tt>list[p].atXYZ(x,y,z,c);</tt>. **/ T& atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } //! Return pixel value with Neumann boundary conditions for the first coordinates (\c pos) \const. T atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "atN(): Empty instance.", cimglist_instance); return _atN(pos,x,y,z,c); } T& _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)](x,y,z,c); } T _atN(const int pos, const int x=0, const int y=0, const int z=0, const int c=0) const { return _data[pos<0?0:(pos>=(int)_width?(int)_width-1:pos)](x,y,z,c); } //! Return a C-string containing the values of all images in the instance list. /** \param separator Character separator set between consecutive pixel values. \param max_size Maximum size of the returned string. \note The result is returne as a <tt>CImg<char></tt> image whose pixel buffer contains the desired C-string. **/ CImg<charT> value_string(const char separator=',', const unsigned int max_size=0) const { if (is_empty()) return CImg<ucharT>(1,1,1,1,0); CImgList<charT> items; for (unsigned int l = 0; l<_width-1; ++l) { CImg<charT> item = _data[l].value_string(separator,0); item.back() = separator; item.move_to(items); } _data[_width-1].value_string(separator,0).move_to(items); CImg<charT> res; (items>'x').move_to(res); if (max_size) { res.crop(0,max_size); res(max_size) = 0; } return res; } //@} //------------------------------------- // //! \name Instance Checking //@{ //------------------------------------- //! Return \c true if list is empty. /** **/ bool is_empty() const { return (!_data || !_width); } //! Test if number of image elements is equal to specified value. /** \param size_n Number of image elements to test. **/ bool is_sameN(const unsigned int size_n) const { return _width==size_n; } //! Test if number of image elements is equal between two images lists. /** \param list Input list to compare with. **/ template<typename t> bool is_sameN(const CImgList<t>& list) const { return is_sameN(list._width); } // Define useful functions to check list dimensions. // (cannot be documented because macro-generated). #define _cimglist_def_is_same1(axis) \ bool is_same##axis(const unsigned int val) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(val); return res; \ } \ bool is_sameN##axis(const unsigned int n, const unsigned int val) const { \ return is_sameN(n) && is_same##axis(val); \ } \ #define _cimglist_def_is_same2(axis1,axis2) \ bool is_same##axis1##axis2(const unsigned int val1, const unsigned int val2) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2(val1,val2); return res; \ } \ bool is_sameN##axis1##axis2(const unsigned int n, const unsigned int val1, const unsigned int val2) const { \ return is_sameN(n) && is_same##axis1##axis2(val1,val2); \ } \ #define _cimglist_def_is_same3(axis1,axis2,axis3) \ bool is_same##axis1##axis2##axis3(const unsigned int val1, const unsigned int val2, const unsigned int val3) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis1##axis2##axis3(val1,val2,val3); return res; \ } \ bool is_sameN##axis1##axis2##axis3(const unsigned int n, const unsigned int val1, const unsigned int val2, const unsigned int val3) const { \ return is_sameN(n) && is_same##axis1##axis2##axis3(val1,val2,val3); \ } \ #define _cimglist_def_is_same(axis) \ template<typename t> bool is_same##axis(const CImg<t>& img) const { \ bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_same##axis(img); return res; \ } \ template<typename t> bool is_same##axis(const CImgList<t>& list) const { \ const unsigned int lmin = cimg::min(_width,list._width); \ bool res = true; for (unsigned int l = 0; l<lmin && res; ++l) res = _data[l].is_same##axis(list[l]); return res; \ } \ template<typename t> bool is_sameN##axis(const unsigned int n, const CImg<t>& img) const { \ return (is_sameN(n) && is_same##axis(img)); \ } \ template<typename t> bool is_sameN##axis(const CImgList<t>& list) const { \ return (is_sameN(list) && is_same##axis(list)); \ } _cimglist_def_is_same(XY) _cimglist_def_is_same(XZ) _cimglist_def_is_same(XC) _cimglist_def_is_same(YZ) _cimglist_def_is_same(YC) _cimglist_def_is_same(XYZ) _cimglist_def_is_same(XYC) _cimglist_def_is_same(YZC) _cimglist_def_is_same(XYZC) _cimglist_def_is_same1(X) _cimglist_def_is_same1(Y) _cimglist_def_is_same1(Z) _cimglist_def_is_same1(C) _cimglist_def_is_same2(X,Y) _cimglist_def_is_same2(X,Z) _cimglist_def_is_same2(X,C) _cimglist_def_is_same2(Y,Z) _cimglist_def_is_same2(Y,C) _cimglist_def_is_same2(Z,C) _cimglist_def_is_same3(X,Y,Z) _cimglist_def_is_same3(X,Y,C) _cimglist_def_is_same3(X,Z,C) _cimglist_def_is_same3(Y,Z,C) //! Test if dimensions of each image of the list match specified arguments. /** \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameXYZC(const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { bool res = true; for (unsigned int l = 0; l<_width && res; ++l) res = _data[l].is_sameXYZC(dx,dy,dz,dc); return res; } //! Test if list dimensions match specified arguments. /** \param n Number of images in the list. \param dx Checked image width. \param dy Checked image height. \param dz Checked image depth. \param dc Checked image spectrum. **/ bool is_sameNXYZC(const unsigned int n, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) const { return is_sameN(n) && is_sameXYZC(dx,dy,dz,dc); } //! Test if list contains one particular pixel location. /** \param n Index of the image whom checked pixel value belong to. \param x X-coordinate of the checked pixel value. \param y Y-coordinate of the checked pixel value. \param z Z-coordinate of the checked pixel value. \param c C-coordinate of the checked pixel value. **/ bool containsNXYZC(const int n, const int x=0, const int y=0, const int z=0, const int c=0) const { if (is_empty()) return false; return n>=0 && n<(int)_width && x>=0 && x<_data[n].width() && y>=0 && y<_data[n].height() && z>=0 && z<_data[n].depth() && c>=0 && c<_data[n].spectrum(); } //! Test if list contains image with specified indice. /** \param n Index of the checked image. **/ bool containsN(const int n) const { if (is_empty()) return false; return n>=0 && n<(int)_width; } //! Test if one image of the list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \param[out] c C-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z,c). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z, t& c) const { if (is_empty()) return false; cimglist_for(*this,l) if (_data[l].contains(pixel,x,y,z,c)) { n = (t)l; return true; } return false; } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \param[out] z Z-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y,z). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y, t& z) const { t c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \param[out] y Y-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x,y). **/ template<typename t> bool contains(const T& pixel, t& n, t& x, t&y) const { t z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \param[out] x X-coordinate of the pixel value, if test succeeds. \note If true, set coordinates (n,x). **/ template<typename t> bool contains(const T& pixel, t& n, t& x) const { t y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. \param[out] n Index of image containing the pixel value, if test succeeds. \note If true, set coordinates (n). **/ template<typename t> bool contains(const T& pixel, t& n) const { t x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if one of the image list contains the specified referenced value. /** \param pixel Reference to pixel value to test. **/ bool contains(const T& pixel) const { unsigned int n, x, y, z, c; return contains(pixel,n,x,y,z,c); } //! Test if the list contains the image 'img'. /** \param img Reference to image to test. \param[out] n Index of image in the list, if test succeeds. \note If true, returns the position (n) of the image in the list. **/ template<typename t> bool contains(const CImg<T>& img, t& n) const { if (is_empty()) return false; const CImg<T> *const ptr = &img; cimglist_for(*this,i) if (_data+i==ptr) { n = (t)i; return true; } return false; } //! Test if the list contains the image img. /** \param img Reference to image to test. **/ bool contains(const CImg<T>& img) const { unsigned int n; return contains(img,n); } //@} //------------------------------------- // //! \name Mathematical Functions //@{ //------------------------------------- //! Return a reference to the minimum pixel value of the instance list. /** **/ T& min() { if (is_empty()) throw CImgInstanceException(_cimglist_instance "min(): Empty instance.", cimglist_instance); T *ptr_min = _data->_data; T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list \const. const T& min() const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "min(): Empty instance.", cimglist_instance); const T *ptr_min = _data->_data; T min_value = *ptr_min; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs); } return *ptr_min; } //! Return a reference to the maximum pixel value of the instance list. /** **/ T& max() { if (is_empty()) throw CImgInstanceException(_cimglist_instance "max(): Empty instance.", cimglist_instance); T *ptr_max = _data->_data; T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the maximum pixel value of the instance list \const. const T& max() const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "max(): Empty instance.", cimglist_instance); const T *ptr_max = _data->_data; T max_value = *ptr_max; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) if (*ptrs>max_value) max_value = *(ptr_max=ptrs); } return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> T& min_max(t& max_val) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "min_max(): Empty instance.", cimglist_instance); T *ptr_min = _data->_data; T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the maximum vvalue as well \const. /** \param[out] max_val Value of the maximum value found. **/ template<typename t> const T& min_max(t& max_val) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "min_max(): Empty instance.", cimglist_instance); const T *ptr_min = _data->_data; T min_value = *ptr_min, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val<min_value) { min_value = val; ptr_min = ptrs; } if (val>max_value) max_value = val; } } max_val = (t)max_value; return *ptr_min; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well. /** \param[out] min_val Value of the minimum value found. **/ template<typename t> T& max_min(t& min_val) { if (is_empty()) throw CImgInstanceException(_cimglist_instance "max_min(): Empty instance.", cimglist_instance); T *ptr_max = _data->_data; T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //! Return a reference to the minimum pixel value of the instance list and return the minimum value as well \const. template<typename t> const T& max_min(t& min_val) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "max_min(): Empty instance.", cimglist_instance); const T *ptr_max = _data->_data; T min_value = *ptr_max, max_value = min_value; cimglist_for(*this,l) { const CImg<T>& img = _data[l]; cimg_for(img,ptrs,T) { const T val = *ptrs; if (val>max_value) { max_value = val; ptr_max = ptrs; } if (val<min_value) min_value = val; } } min_val = (t)min_value; return *ptr_max; } //@} //--------------------------- // //! \name List Manipulation //@{ //--------------------------- //! Insert a copy of the image \c img into the current image list, at position \c pos. /** \param img Image to insert a copy to the list. \param pos Index of the insertion. \param is_shared Tells if the inserted image is a shared copy of \c img or not. **/ template<typename t> CImgList<T>& insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); if (is_shared) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified shared image CImg<%s>(%u,%u,%u,%u,%p) at position %u " "(pixel types are different).", cimglist_instance, img.pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1):(_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list. _data = new_data; *_data = img; } else { if (new_data) { // Insert with re-allocation. if (npos) std::memcpy(new_data,_data,sizeof(CImg<T>)*npos); if (npos!=_width-1) std::memcpy(new_data+npos+1,_data+npos,sizeof(CImg<T>)*(_width-1-npos)); std::memset(_data,0,sizeof(CImg<T>)*(_width-1)); delete[] _data; _data = new_data; } else if (npos!=_width-1) std::memmove(_data+npos+1,_data+npos,sizeof(CImg<T>)*(_width-1-npos)); // Insert without re-allocation. _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \specialization. CImgList<T>& insert(const CImg<T>& img, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if (npos>_width) throw CImgArgumentException(_cimglist_instance "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) at position %u.", cimglist_instance, img._width,img._height,img._depth,img._spectrum,img._data,npos); CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1):(_allocated_width=16)]:0; if (!_data) { // Insert new element into empty list. _data = new_data; if (is_shared && img) { _data->_width = img._width; _data->_height = img._height; _data->_depth = img._depth; _data->_spectrum = img._spectrum; _data->_is_shared = true; _data->_data = img._data; } else *_data = img; } else { if (new_data) { // Insert with re-allocation. if (npos) std::memcpy(new_data,_data,sizeof(CImg<T>)*npos); if (npos!=_width-1) std::memcpy(new_data+npos+1,_data+npos,sizeof(CImg<T>)*(_width-1-npos)); if (is_shared && img) { new_data[npos]._width = img._width; new_data[npos]._height = img._height; new_data[npos]._depth = img._depth; new_data[npos]._spectrum = img._spectrum; new_data[npos]._is_shared = true; new_data[npos]._data = img._data; } else { new_data[npos]._width = new_data[npos]._height = new_data[npos]._depth = new_data[npos]._spectrum = 0; new_data[npos]._data = 0; new_data[npos] = img; } std::memset(_data,0,sizeof(CImg<T>)*(_width-1)); delete[] _data; _data = new_data; } else { // Insert without re-allocation. if (npos!=_width-1) std::memmove(_data+npos+1,_data+npos,sizeof(CImg<T>)*(_width-1-npos)); if (is_shared && img) { _data[npos]._width = img._width; _data[npos]._height = img._height; _data[npos]._depth = img._depth; _data[npos]._spectrum = img._spectrum; _data[npos]._is_shared = true; _data[npos]._data = img._data; } else { _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0; _data[npos]._data = 0; _data[npos] = img; } } } return *this; } //! Insert a copy of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(img,pos,is_shared); } //! Insert n empty images img into the current image list, at position \p pos. /** \param n Number of empty images to insert. \param pos Index of the insertion. **/ CImgList<T>& insert(const unsigned int n, const unsigned int pos=~0U) { CImg<T> empty; if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(empty,npos+i); return *this; } //! Insert n empty images img into the current image list, at position \p pos \newinstance. CImgList<T> get_insert(const unsigned int n, const unsigned int pos=~0U) const { return (+*this).insert(n,pos); } //! Insert \c n copies of the image \c img into the current image list, at position \c pos. /** \param n Number of image copies to insert. \param img Image to insert by copy. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of \c img or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; insert(img,npos,is_shared); for (unsigned int i = 1; i<n; ++i) insert(_data[npos],npos+i,is_shared); return *this; } //! Insert \c n copies of the image \c img into the current image list, at position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,img,pos,is_shared); } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos. /** \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { const unsigned int npos = pos==~0U?_width:pos; if ((void*)this!=(void*)&list) cimglist_for(list,l) insert(list[l],npos+l,is_shared); else insert(CImgList<T>(list),npos,is_shared); return *this; } //! Insert a copy of the image list \c list into the current image list, starting from position \c pos \newinstance. template<typename t> CImgList<T> get_insert(const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(list,pos,is_shared); } //! Insert n copies of the list \c list at position \c pos of the current list. /** \param n Number of list copies to insert. \param list Image list to insert. \param pos Index of the insertion. \param is_shared Tells if inserted images are shared copies of images of \c list or not. **/ template<typename t> CImgList<T>& insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) { if (!n) return *this; const unsigned int npos = pos==~0U?_width:pos; for (unsigned int i = 0; i<n; ++i) insert(list,npos,is_shared); return *this; } //! Insert n copies of the list \c list at position \c pos of the current list \newinstance. template<typename t> CImgList<T> get_insert(const unsigned int n, const CImgList<t>& list, const unsigned int pos=~0U, const bool is_shared=false) const { return (+*this).insert(n,list,pos,is_shared); } //! Remove all images between from indexes. /** \param pos1 Starting index of the removal. \param pos2 Ending index of the removal. **/ CImgList<T>& remove(const unsigned int pos1, const unsigned int pos2) { const unsigned int npos1 = pos1<pos2?pos1:pos2, tpos2 = pos1<pos2?pos2:pos1, npos2 = tpos2<_width?tpos2:_width-1; if (npos1>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); else { if (tpos2>=_width) throw CImgArgumentException(_cimglist_instance "remove(): Invalid remove request at positions %u->%u.", cimglist_instance, npos1,tpos2); for (unsigned int k = npos1; k<=npos2; ++k) _data[k].assign(); const unsigned int nb = 1 + npos2 - npos1; if (!(_width-=nb)) return assign(); if (_width>(_allocated_width>>2) || _allocated_width<=16) { // Removing items without reallocation. if (npos1!=_width) std::memmove(_data+npos1,_data+npos2+1,sizeof(CImg<T>)*(_width - npos1)); std::memset(_data + _width,0,sizeof(CImg<T>)*nb); } else { // Removing items with reallocation. _allocated_width>>=2; while (_allocated_width>16 && _width<(_allocated_width>>1)) _allocated_width>>=1; CImg<T> *const new_data = new CImg<T>[_allocated_width]; if (npos1) std::memcpy(new_data,_data,sizeof(CImg<T>)*npos1); if (npos1!=_width) std::memcpy(new_data+npos1,_data+npos2+1,sizeof(CImg<T>)*(_width-npos1)); if (_width!=_allocated_width) std::memset(new_data+_width,0,sizeof(_allocated_width - _width)); std::memset(_data,0,sizeof(CImg<T>)*(_width+nb)); delete[] _data; _data = new_data; } } return *this; } //! Remove all images between from indexes \newinstance. CImgList<T> get_remove(const unsigned int pos1, const unsigned int pos2) const { return (+*this).remove(pos1,pos2); } //! Remove image at index \c pos from the image list. /** \param pos Index of the image to remove. **/ CImgList<T>& remove(const unsigned int pos) { return remove(pos,pos); } //! Remove image at index \c pos from the image list \newinstance. CImgList<T> get_remove(const unsigned int pos) const { return (+*this).remove(pos); } //! Remove last image. /** **/ CImgList<T>& remove() { return remove(_width-1); } //! Remove last image \newinstance. CImgList<T> get_remove() const { return (+*this).remove(); } //! Reverse list order. CImgList<T>& reverse() { for (unsigned int l = 0; l<_width/2; ++l) (*this)[l].swap((*this)[_width-1-l]); return *this; } //! Reverse list order \newinstance. CImgList<T> get_reverse() const { return (+*this).reverse(); } //! Return a sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T>& images(const unsigned int pos0, const unsigned int pos1) { return get_images(pos0,pos1).move_to(*this); } //! Return a sublist \newinstance. CImgList<T> get_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1-pos0+1); cimglist_for(res,l) res[l].assign(_data[pos0+l]); return res; } //! Return a shared sublist. /** \param pos0 Starting index of the sublist. \param pos1 Ending index of the sublist. **/ CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1-pos0+1); cimglist_for(res,l) res[l].assign(_data[pos0+l],true); return res; } //! Return a shared sublist \newinstance. const CImgList<T> get_shared_images(const unsigned int pos0, const unsigned int pos1) const { if (pos0>pos1 || pos1>=_width) throw CImgArgumentException(_cimglist_instance "get_shared_images(): Specified sub-list indices (%u->%u) are out of bounds.", cimglist_instance, pos0,pos1); CImgList<T> res(pos1-pos0+1); cimglist_for(res,l) res[l].assign(_data[pos0+l],true); return res; } //! Return a single image which is the appending of all images of the current CImgList instance. /** \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ CImg<T> get_append(const char axis, const float align=0) const { if (is_empty()) return CImg<T>(); if (_width==1) return +((*this)[0]); unsigned int dx = 0, dy = 0, dz = 0, dc = 0, pos = 0; CImg<T> res; switch (cimg::uncase(axis)) { case 'x' : { // Along the X-axis. cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx+=img._width; dy = cimg::max(dy,img._height); dz = cimg::max(dz,img._depth); dc = cimg::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image(pos, (int)(align*(dy-img._height)), (int)(align*(dz-img._depth)), (int)(align*(dc-img._spectrum)), img); pos+=img._width; } } break; case 'y' : { // Along the Y-axis. cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = cimg::max(dx,img._width); dy+=img._height; dz = cimg::max(dz,img._depth); dc = cimg::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx-img._width)), pos, (int)(align*(dz-img._depth)), (int)(align*(dc-img._spectrum)), img); pos+=img._height; } } break; case 'z' : { // Along the Z-axis. cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = cimg::max(dx,img._width); dy = cimg::max(dy,img._height); dz+=img._depth; dc = cimg::max(dc,img._spectrum); } } res.assign(dx,dy,dz,dc,0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx-img._width)), (int)(align*(dy-img._height)), pos, (int)(align*(dc-img._spectrum)), img); pos+=img._depth; } } break; default : { // Along the C-axis. cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) { dx = cimg::max(dx,img._width); dy = cimg::max(dy,img._height); dz = cimg::max(dz,img._depth); dc+=img._spectrum; } } res.assign(dx,dy,dz,dc,0); if (res) cimglist_for(*this,l) { const CImg<T>& img = (*this)[l]; if (img) res.draw_image((int)(align*(dx-img._width)), (int)(align*(dy-img._height)), (int)(align*(dz-img._depth)), pos, img); pos+=img._spectrum; } } } return res; } //! Return a list where each image has been split along the specified axis. /** \param axis Axis to split images along. \param nb Number of spliting parts for each image. **/ CImgList<T>& split(const char axis, const int nb=0) { return get_split(axis,nb).move_to(*this); } //! Return a list where each image has been split along the specified axis \newinstance. CImgList<T> get_split(const char axis, const int nb=0) const { CImgList<T> res; cimglist_for(*this,l) _data[l].get_split(axis,nb).move_to(res,~0U); return res; } //! Insert image at the end of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_back(const CImg<t>& img) { return insert(img); } //! Insert image at the front of the list. /** \param img Image to insert. **/ template<typename t> CImgList<T>& push_front(const CImg<t>& img) { return insert(img,0); } //! Insert list at the end of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_back(const CImgList<t>& list) { return insert(list); } //! Insert list at the front of the current list. /** \param list List to insert. **/ template<typename t> CImgList<T>& push_front(const CImgList<t>& list) { return insert(list,0); } //! Remove last image. /** **/ CImgList<T>& pop_back() { return remove(_width-1); } //! Remove first image. /** **/ CImgList<T>& pop_front() { return remove(0); } //! Remove image pointed by iterator. /** \param iter Iterator pointing to the image to remove. **/ CImgList<T>& erase(const iterator iter) { return remove(iter-_data); } //@} //---------------------------------- // //! \name Data Input //@{ //---------------------------------- //! Display a simple interactive interface to select images or sublists. /** \param disp Window instance to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(CImgDisplay &disp, const bool feature_type=true, const char axis='x', const float align=0) const { return _get_select(disp,0,feature_type,axis,align,0,false,false,false); } //! Display a simple interactive interface to select images or sublists. /** \param title Title of a new window used to display selection and user interface. \param feature_type Can be \c false to select a single image, or \c true to select a sublist. \param axis Axis along whom images are appended for visualization. \param align Alignment setting when images have not all the same size. \return A one-column vector containing the selected image indexes. **/ CImg<intT> get_select(const char *const title, const bool feature_type=true, const char axis='x', const float align=0) const { CImgDisplay disp; return _get_select(disp,title,feature_type,axis,align,0,false,false,false); } CImg<intT> _get_select(CImgDisplay &disp, const char *const title, const bool feature_type, const char axis, const float align, const unsigned int orig, const bool resize_disp, const bool exit_on_rightbutton, const bool exit_on_wheel) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "select(): Empty instance.", cimglist_instance); // Create image correspondence table and get list dimensions for visualization. CImgList<uintT> _indices; unsigned int max_width = 0, max_height = 0, sum_width = 0, sum_height = 0; cimglist_for(*this,l) if (_data[l]) { const CImg<T>& img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; if (h>max_height) max_height = h; sum_width+=w; sum_height+=h; if (axis=='x') CImg<uintT>(w,1,1,1,(unsigned int)l).move_to(_indices); else CImg<uintT>(h,1,1,1,(unsigned int)l).move_to(_indices); } const CImg<uintT> indices0 = _indices>'x'; // Create display window. if (!disp) { if (axis=='x') disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:0,1); else disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:0,1); if (!title) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else if (title) disp.set_title("%s",title); if (resize_disp) { if (axis=='x') disp.resize(cimg_fitscreen(sum_width,max_height,1),false); else disp.resize(cimg_fitscreen(max_width,sum_height,1),false); } const unsigned int old_normalization = disp.normalization(); bool old_is_resized = disp.is_resized(); disp._normalization = 0; disp.show().set_key(0); const unsigned char foreground_color[] = { 255,255,255 }, background_color[] = { 0,0,0 }; // Enter event loop. CImg<ucharT> visu0, visu; CImg<uintT> indices; CImg<intT> positions(_width,4,1,1,-1); int oindice0 = -1, oindice1 = -1, indice0 = -1, indice1 = -1; bool is_clicked = false, is_selected = false, text_down = false, update_display = true; unsigned int key = 0; while (!is_selected && !disp.is_closed() && !key) { // Create background image. if (!visu0) { visu0.assign(disp._width,disp._height,1,3,0); visu.assign(); (indices0.get_resize(axis=='x'?visu0._width:visu0._height,1)).move_to(indices); unsigned int ind = 0; if (axis=='x') for (unsigned int x = 0; x<visu0._width; ) { const unsigned int x0 = x; ind = indices[x]; while (x<indices._width && indices[++x]==ind) {} const CImg<T> &src = _data[ind], _img2d = src._depth>1?src.get_projections2d(src._width/2,src._height/2,src._depth/2):CImg<T>(), &img2d = _img2d?_img2d:src; CImg<ucharT> res = old_normalization==1? CImg<ucharT>(img2d.get_channels(0,cimg::min(2,img2d.spectrum()-1)).normalize(0,255)): CImg<ucharT>(img2d.get_channels(0,cimg::min(2,img2d.spectrum()-1))); const unsigned int h = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,true); res.resize(x - x0,cimg::max(32U,h*disp._height/max_height),1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)x0; positions(ind,1) = positions(ind,3) = (int)(align*(visu0.height()-res.height())); positions(ind,2)+=res._width; positions(ind,3)+=res._height - 1; visu0.draw_image(positions(ind,0),positions(ind,1),res); } else for (unsigned int y = 0; y<visu0._height; ) { const unsigned int y0 = y; ind = indices[y]; while (y<visu0._height && indices[++y]==ind) {} const CImg<T> &src = _data[ind], _img2d = src._depth>1?src.get_projections2d(src._width/2,src._height/2,src._depth/2):CImg<T>(), &img2d = _img2d?_img2d:src; CImg<ucharT> res = old_normalization==1?CImg<ucharT>(img2d.get_normalize(0,255)):CImg<ucharT>(img2d); if (res._spectrum>3) res.channels(0,2); const unsigned int w = CImgDisplay::_fitscreen(res._width,res._height,1,128,-85,false); res.resize(cimg::max(32U,w*disp._width/max_width),y - y0,1,res._spectrum==1?3:-100); positions(ind,0) = positions(ind,2) = (int)(align*(visu0.width()-res.width())); positions(ind,1) = positions(ind,3) = (int)y0; positions(ind,2)+=res._width - 1; positions(ind,3)+=res._height; visu0.draw_image(positions(ind,0),positions(ind,1),res); } if (axis=='x') --positions(ind,2); else --positions(ind,3); update_display = true; } if (!visu || oindice0!=indice0 || oindice1!=indice1) { if (indice0>=0 && indice1>=0) { visu.assign(visu0,false); const int indm = cimg::min(indice0,indice1), indM = cimg::max(indice0,indice1); for (int ind = indm; ind<=indM; ++ind) if (positions(ind,0)>=0) { visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3),background_color,0.2f); if ((axis=='x' && positions(ind,2) - positions(ind,0)>=8) || (axis!='x' && positions(ind,3) - positions(ind,1)>=8)) visu.draw_rectangle(positions(ind,0),positions(ind,1),positions(ind,2),positions(ind,3),foreground_color,0.9f,0x55555555); } const int yt = (int)text_down?visu.height()-13:0; if (is_clicked) visu.draw_text(0,yt," Images %u - %u, Size = %u",foreground_color,background_color,0.7f,13, orig + indm,orig + indM,indM - indm + 1); else visu.draw_text(0,yt," Image %u",foreground_color,background_color,0.7f,13, orig + indice0); update_display = true; } else visu.assign(); } if (!visu) { visu.assign(visu0,true); update_display = true; } if (update_display) { visu.display(disp); update_display = false; } disp.wait(); // Manage user events. const int xm = disp.mouse_x(), ym = disp.mouse_y(); int indice = -1; if (xm>=0) { indice = (int)indices(axis=='x'?xm:ym); if (disp.button()&1) { if (!is_clicked) { is_clicked = true; oindice0 = indice0; indice0 = indice; } oindice1 = indice1; indice1 = indice; if (!feature_type) is_selected = true; } else { if (!is_clicked) { oindice0 = oindice1 = indice0; indice0 = indice1 = indice; } else is_selected = true; } } else { if (is_clicked) { if (!(disp.button()&1)) { is_clicked = is_selected = false; indice0 = indice1 = -1; } else indice1 = -1; } else indice0 = indice1 = -1; } if (disp.button()&4) { is_clicked = is_selected = false; indice0 = indice1 = -1; } if (disp.button()&2 && exit_on_rightbutton) { is_selected = true; indice1 = indice0 = -1; } if (disp.wheel() && exit_on_wheel) is_selected = true; switch (key = disp.key()) { #if cimg_OS!=2 case cimg::keyCTRLRIGHT : #endif case 0 : case cimg::keyCTRLLEFT : key = 0; break; case cimg::keyD : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,false), CImgDisplay::_fitscreen(3*disp.width()/2,3*disp.height()/2,1,128,-100,true),false). _is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyC : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(2*disp.width()/3,2*disp.height()/3,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyR : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.set_fullscreen(false).resize(cimg_fitscreen(axis=='x'?sum_width:max_width,axis=='x'?max_height:sum_height,1),false)._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyF : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { disp.resize(disp.screen_width(),disp.screen_height(),false).toggle_fullscreen()._is_resized = true; disp.set_key(key,false); key = 0; visu0.assign(); } break; case cimg::keyS : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.bmp",snap_number++); if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); if (visu0) { visu.draw_text(0,0," Saving snapshot... ",foreground_color,background_color,1,13).display(disp); visu0.save(filename); visu.draw_text(0,0," Snapshot '%s' saved. ",foreground_color,background_color,1,13,filename).display(disp); } disp.set_key(key,false).wait(); key = 0; } break; case cimg::keyO : if (disp.is_keyCTRLLEFT() || disp.is_keyCTRLRIGHT()) { static unsigned int snap_number = 0; char filename[32] = { 0 }; std::FILE *file; do { #ifdef cimg_use_zlib cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimgz",snap_number++); #else cimg_snprintf(filename,sizeof(filename),cimg_appname "_%.4u.cimg",snap_number++); #endif if ((file=std::fopen(filename,"r"))!=0) cimg::fclose(file); } while (file); visu.draw_text(0,0," Saving instance... ",foreground_color,background_color,1,13).display(disp); save(filename); visu.draw_text(0,0," Instance '%s' saved. ",foreground_color,background_color,1,13,filename).display(disp); disp.set_key(key,false).wait(); key = 0; } break; } if (disp.is_resized()) { disp.resize(false); visu0.assign(); } if (ym>=0 && ym<13) { if (!text_down) { visu.assign(); text_down = true; }} else if (ym>=visu.height()-13) { if(text_down) { visu.assign(); text_down = false; }} } CImg<intT> res(1,2,1,1,-1); if (is_selected) { if (feature_type) res.fill(cimg::min(indice0,indice1),cimg::max(indice0,indice1)); else res.fill(indice0); } if (!(disp.button()&2)) disp.set_button(); disp._normalization = old_normalization; disp._is_resized = old_is_resized; disp.set_key(key); return res; } //! Load a list from a file. /** \param filename Filename to read data from. **/ CImgList<T>& load(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load(): Specified filename is (null).", cimglist_instance); if (!cimg::strncasecmp(filename,"http://",7) || !cimg::strncasecmp(filename,"https://",8)) { char filename_local[1024] = { 0 }; load(cimg::load_network_external(filename,filename_local)); std::remove(filename_local); return *this; } const char *const ext = cimg::split_filename(filename); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; try { #ifdef cimglist_load_plugin cimglist_load_plugin(filename); #endif #ifdef cimglist_load_plugin1 cimglist_load_plugin1(filename); #endif #ifdef cimglist_load_plugin2 cimglist_load_plugin2(filename); #endif #ifdef cimglist_load_plugin3 cimglist_load_plugin3(filename); #endif #ifdef cimglist_load_plugin4 cimglist_load_plugin4(filename); #endif #ifdef cimglist_load_plugin5 cimglist_load_plugin5(filename); #endif #ifdef cimglist_load_plugin6 cimglist_load_plugin6(filename); #endif #ifdef cimglist_load_plugin7 cimglist_load_plugin7(filename); #endif #ifdef cimglist_load_plugin8 cimglist_load_plugin8(filename); #endif if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) load_tiff(filename); else if (!cimg::strcasecmp(ext,"cimg") || !cimg::strcasecmp(ext,"cimgz") || !*ext) load_cimg(filename); else if (!cimg::strcasecmp(ext,"rec") || !cimg::strcasecmp(ext,"par")) load_parrec(filename); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) load_ffmpeg(filename); else if (!cimg::strcasecmp(ext,"gz")) load_gzip_external(filename); else throw CImgIOException("CImgList<%s>::load()", pixel_type()); } catch (CImgIOException&) { try { cimg::fclose(cimg::fopen(filename,"rb")); } catch (CImgIOException&) { cimg::exception_mode() = omode; throw CImgIOException(_cimglist_instance "load(): Failed to open file '%s'.", cimglist_instance, filename); } assign(1); try { _data->load(filename); } catch (CImgIOException&) { cimg::exception_mode() = omode; throw CImgIOException(_cimglist_instance "load(): Failed to recognize format of file '%s'.", cimglist_instance, filename); } } cimg::exception_mode() = omode; return *this; } //! Load a list from a file \newinstance. static CImgList<T> get_load(const char *const filename) { return CImgList<T>().load(filename); } //! Load a list from a .cimg file. /** \param filename Filename to read data from. **/ CImgList<T>& load_cimg(const char *const filename) { return _load_cimg(0,filename); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename) { return CImgList<T>().load_cimg(filename); } //! Load a list from a .cimg file. /** \param file File to read data from. **/ CImgList<T>& load_cimg(std::FILE *const file) { return _load_cimg(file,0); } //! Load a list from a .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file) { return CImgList<T>().load_cimg(file); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename) { #ifdef cimg_use_zlib #define _cimgz_load_cimg_case(Tss) { \ Bytef *const cbuf = new Bytef[csiz]; \ cimg::fread(cbuf,csiz,nfile); \ raw.assign(W,H,D,C); \ unsigned long destlen = (unsigned long)raw.size()*sizeof(Tss); \ uncompress((Bytef*)raw._data,&destlen,cbuf,csiz); \ delete[] cbuf; \ const Tss *ptrs = raw._data; \ for (unsigned long off = raw.size(); off; --off) *(ptrd++) = (T)*(ptrs++); \ } #else #define _cimgz_load_cimg_case(Tss) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Unable to load compressed data from file '%s' unless zlib is enabled.", \ cimglist_instance, \ filename?filename:"(FILE*)"); #endif #define _cimg_load_cimg_case(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<N; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; csiz = 0; \ if ((err = std::sscanf(tmp,"%u %u %u %u #%u",&W,&H,&D,&C,&csiz))<4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'", \ cimglist_instance, \ W,H,D,C,l,filename?filename:("(FILE*)")); \ if (W*H*D*C>0) { \ CImg<Tss> raw; \ CImg<T> &img = _data[l]; \ img.assign(W,H,D,C); \ T *ptrd = img._data; \ if (err==5) _cimgz_load_cimg_case(Tss) \ else for (long to_read = (long)img.size(); to_read>0; ) { \ raw.assign(cimg::min(to_read,cimg_iobuffer)); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); \ to_read-=raw._width; \ const Tss *ptrs = raw._data; \ for (unsigned long off = (unsigned long)raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); const int cimg_iobuffer = 12*1024*1024; std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); char tmp[256] = { 0 }, str_pixeltype[256] = { 0 }, str_endian[256] = { 0 }; unsigned int j, err, N = 0, W, H, D, C, csiz; int i; do { j = 0; while ((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; } while (*tmp=='#' && i!=EOF); err = std::sscanf(tmp,"%u%*c%255[A-Za-z_]%*c%255[sA-Za-z_ ]",&N,str_pixeltype,str_endian); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; assign(N); _cimg_load_cimg_case("bool",bool); _cimg_load_cimg_case("unsigned_char",unsigned char); _cimg_load_cimg_case("uchar",unsigned char); _cimg_load_cimg_case("char",char); _cimg_load_cimg_case("unsigned_short",unsigned short); _cimg_load_cimg_case("ushort",unsigned short); _cimg_load_cimg_case("short",short); _cimg_load_cimg_case("unsigned_int",unsigned int); _cimg_load_cimg_case("uint",unsigned int); _cimg_load_cimg_case("int",int); _cimg_load_cimg_case("unsigned_long",unsigned long); _cimg_load_cimg_case("ulong",unsigned long); _cimg_load_cimg_case("long",long); _cimg_load_cimg_case("float",float); _cimg_load_cimg_case("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a sublist list from a (non compressed) .cimg file. /** \param filename Filename to read data from. \param n0 Starting index of images to read. \param n1 Ending index of images to read. \param x0 Starting X-coordinates of image regions to read. \param y0 Starting Y-coordinates of image regions to read. \param z0 Starting Z-coordinates of image regions to read. \param c0 Starting C-coordinates of image regions to read. \param x1 Ending X-coordinates of image regions to read. \param y1 Ending Y-coordinates of image regions to read. \param z1 Ending Z-coordinates of image regions to read. \param c1 Ending C-coordinates of image regions to read. **/ CImgList<T>& load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(0,filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sublist list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file. /** \param file File to read data from. \param n0 Starting index of images to read. \param n1 Ending index of images to read. \param x0 Starting X-coordinates of image regions to read. \param y0 Starting Y-coordinates of image regions to read. \param z0 Starting Z-coordinates of image regions to read. \param c0 Starting C-coordinates of image regions to read. \param x1 Ending X-coordinates of image regions to read. \param y1 Ending Y-coordinates of image regions to read. \param z1 Ending Z-coordinates of image regions to read. \param c1 Ending C-coordinates of image regions to read. **/ CImgList<T>& load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return _load_cimg(file,0,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } //! Load a sub-image list from a (non compressed) .cimg file \newinstance. static CImgList<T> get_load_cimg(std::FILE *const file, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { return CImgList<T>().load_cimg(file,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1); } CImgList<T>& _load_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int n1, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0, const unsigned int x1, const unsigned int y1, const unsigned int z1, const unsigned int c1) { #define _cimg_load_cimg_case2(Ts,Tss) \ if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<=nn1; ++l) { \ j = 0; while ((i=std::fgetc(nfile))!='\n' && i>=0) tmp[j++] = (char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (std::sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "load_cimg(): Invalid specified size (%u,%u,%u,%u) of image %u in file '%s'", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<n0 || x0>=W || y0>=H || z0>=D || c0>=D) std::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const unsigned int \ nx1 = x1>=W?W-1:x1, \ ny1 = y1>=H?H-1:y1, \ nz1 = z1>=D?D-1:z1, \ nc1 = c1>=C?C-1:c1; \ CImg<Tss> raw(1 + nx1 - x0); \ CImg<T> &img = _data[l - n0]; \ img.assign(1 + nx1 - x0,1 + ny1 - y0,1 + nz1 - z0,1 + nc1 - c0); \ T *ptrd = img._data; \ const unsigned int skipvb = c0*W*H*D*sizeof(Tss); \ if (skipvb) std::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int v = 1 + nc1 - c0; v; --v) { \ const unsigned int skipzb = z0*W*H*sizeof(Tss); \ if (skipzb) std::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + nz1 - z0; z; --z) { \ const unsigned int skipyb = y0*W*sizeof(Tss); \ if (skipyb) std::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + ny1 - y0; y; --y) { \ const unsigned int skipxb = x0*sizeof(Tss); \ if (skipxb) std::fseek(nfile,skipxb,SEEK_CUR); \ cimg::fread(raw._data,raw._width,nfile); \ if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw._width); \ const Tss *ptrs = raw._data; \ for (unsigned int off = raw._width; off; --off) *(ptrd++) = (T)*(ptrs++); \ const unsigned int skipxe = (W-1-nx1)*sizeof(Tss); \ if (skipxe) std::fseek(nfile,skipxe,SEEK_CUR); \ } \ const unsigned int skipye = (H-1-ny1)*W*sizeof(Tss); \ if (skipye) std::fseek(nfile,skipye,SEEK_CUR); \ } \ const unsigned int skipze = (D-1-nz1)*W*H*sizeof(Tss); \ if (skipze) std::fseek(nfile,skipze,SEEK_CUR); \ } \ const unsigned int skipve = (C-1-nc1)*W*H*D*sizeof(Tss); \ if (skipve) std::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ loaded = true; \ } if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_cimg(): Specified filename is (null).", cimglist_instance); if (n1<n0 || x1<x0 || y1<y0 || z1<z0 || c1<c0) throw CImgArgumentException(_cimglist_instance "load_cimg(): Invalid specified sub-region coordinates [%u->%u] (%u,%u,%u,%u)->(%u,%u,%u,%u) for file '%s'.", cimglist_instance, n0,n1,x0,y0,z0,c0,x1,y1,z1,filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool loaded = false, endian = cimg::endianness(); char tmp[256] = { 0 }, str_pixeltype[256] = { 0 }, str_endian[256] = { 0 }; unsigned int j, err, N, W, H, D, C; int i; j = 0; while((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = std::sscanf(tmp,"%u%*c%255[A-Za-z_]%*c%255[sA-Za-z_ ]",&N,str_pixeltype,str_endian); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; const unsigned int nn1 = n1>=N?N-1:n1; assign(1+nn1-n0); _cimg_load_cimg_case2("bool",bool); _cimg_load_cimg_case2("unsigned_char",unsigned char); _cimg_load_cimg_case2("uchar",unsigned char); _cimg_load_cimg_case2("char",char); _cimg_load_cimg_case2("unsigned_short",unsigned short); _cimg_load_cimg_case2("ushort",unsigned short); _cimg_load_cimg_case2("short",short); _cimg_load_cimg_case2("unsigned_int",unsigned int); _cimg_load_cimg_case2("uint",unsigned int); _cimg_load_cimg_case2("int",int); _cimg_load_cimg_case2("unsigned_long",unsigned long); _cimg_load_cimg_case2("ulong",unsigned long); _cimg_load_cimg_case2("long",long); _cimg_load_cimg_case2("float",float); _cimg_load_cimg_case2("double",double); if (!loaded) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_cimg(): Unsupported pixel type '%s' for file '%s'.", cimglist_instance, str_pixeltype,filename?filename:"(FILE*)"); } if (!file) cimg::fclose(nfile); return *this; } //! Load a list from a PAR/REC (Philips) file. /** \param filename Filename to read data from. **/ CImgList<T>& load_parrec(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_parrec(): Specified filename is (null).", cimglist_instance); char body[1024] = { 0 }, filenamepar[1024] = { 0 }, filenamerec[1024] = { 0 }; const char *const ext = cimg::split_filename(filename,body); if (!std::strcmp(ext,"par")) { std::strncpy(filenamepar,filename,sizeof(filenamepar)-1); cimg_snprintf(filenamerec,sizeof(filenamerec),"%s.rec",body); } if (!std::strcmp(ext,"PAR")) { std::strncpy(filenamepar,filename,sizeof(filenamepar)-1); cimg_snprintf(filenamerec,sizeof(filenamerec),"%s.REC",body); } if (!std::strcmp(ext,"rec")) { std::strncpy(filenamerec,filename,sizeof(filenamerec)-1); cimg_snprintf(filenamepar,sizeof(filenamepar),"%s.par",body); } if (!std::strcmp(ext,"REC")) { std::strncpy(filenamerec,filename,sizeof(filenamerec)-1); cimg_snprintf(filenamepar,sizeof(filenamepar),"%s.PAR",body); } std::FILE *file = cimg::fopen(filenamepar,"r"); // Parse header file CImgList<floatT> st_slices; CImgList<uintT> st_global; int err; char line[256] = { 0 }; do { err=std::fscanf(file,"%255[^\n]%*c",line); } while (err!=EOF && (*line=='#' || *line=='.')); do { unsigned int sn,size_x,size_y,pixsize; float rs,ri,ss; err = std::fscanf(file,"%u%*u%*u%*u%*u%*u%*u%u%*u%u%u%g%g%g%*[^\n]",&sn,&pixsize,&size_x,&size_y,&ri,&rs,&ss); if (err==7) { CImg<floatT>::vector((float)sn,(float)pixsize,(float)size_x,(float)size_y,ri,rs,ss,0).move_to(st_slices); unsigned int i; for (i = 0; i<st_global._width && sn<=st_global[i][2]; ++i) {} if (i==st_global._width) CImg<uintT>::vector(size_x,size_y,sn).move_to(st_global); else { CImg<uintT> &vec = st_global[i]; if (size_x>vec[0]) vec[0] = size_x; if (size_y>vec[1]) vec[1] = size_y; vec[2] = sn; } st_slices[st_slices._width-1][7] = (float)i; } } while (err==7); // Read data std::FILE *file2 = cimg::fopen(filenamerec,"rb"); cimglist_for(st_global,l) { const CImg<uintT>& vec = st_global[l]; CImg<T>(vec[0],vec[1],vec[2]).move_to(*this); } cimglist_for(st_slices,l) { const CImg<floatT>& vec = st_slices[l]; const unsigned int sn = (unsigned int)vec[0] - 1, pixsize = (unsigned int)vec[1], size_x = (unsigned int)vec[2], size_y = (unsigned int)vec[3], imn = (unsigned int)vec[7]; const float ri = vec[4], rs = vec[5], ss = vec[6]; switch (pixsize) { case 8 : { CImg<ucharT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 16 : { CImg<ushortT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; case 32 : { CImg<uintT> buf(size_x,size_y); cimg::fread(buf._data,size_x*size_y,file2); if (cimg::endianness()) cimg::invert_endianness(buf._data,size_x*size_y); CImg<T>& img = (*this)[imn]; cimg_forXY(img,x,y) img(x,y,sn) = (T)(( buf(x,y)*rs + ri )/(rs*ss)); } break; default : cimg::fclose(file); cimg::fclose(file2); throw CImgIOException(_cimglist_instance "load_parrec(): Unsupported %d-bits pixel type for file '%s'.", cimglist_instance, pixsize,filename); } } cimg::fclose(file); cimg::fclose(file2); if (!_width) throw CImgIOException(_cimglist_instance "load_parrec(): Failed to recognize valid PAR-REC data in file '%s'.", cimglist_instance, filename); return *this; } //! Load a list from a PAR/REC (Philips) file \newinstance. static CImgList<T> get_load_parrec(const char *const filename) { return CImgList<T>().load_parrec(filename); } //! Load a list from a YUV image sequence file. /** \param filename Filename to read data from. \param size_x Width of the images. \param size_y Height of the images. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. \param yuv2rgb Apply YUV to RGB transformation during reading. **/ CImgList<T>& load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(0,filename,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from a YUV image sequence file \newinstance. static CImgList<T> get_load_yuv(const char *const filename, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(filename,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \overloading. CImgList<T>& load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return _load_yuv(file,0,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb); } //! Load a list from an image sequence YUV file \newinstance. static CImgList<T> get_load_yuv(std::FILE *const file, const unsigned int size_x, const unsigned int size_y=1, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool yuv2rgb=true) { return CImgList<T>().load_yuv(file,size_x,size_y,first_frame,last_frame,step_frame,yuv2rgb); } CImgList<T>& _load_yuv(std::FILE *const file, const char *const filename, const unsigned int size_x, const unsigned int size_y, const unsigned int first_frame, const unsigned int last_frame, const unsigned int step_frame, const bool yuv2rgb) { if (!filename && !file) throw CImgArgumentException(_cimglist_instance "load_yuv(): Specified filename is (null).", cimglist_instance); if (size_x%2 || size_y%2) throw CImgArgumentException(_cimglist_instance "load_yuv(): Invalid odd XY dimensions %ux%u in file '%s'.", cimglist_instance, size_x,size_y,filename?filename:"(FILE*)"); if (!size_x || !size_y) throw CImgArgumentException(_cimglist_instance "load_yuv(): Invalid sequence size (%u,%u) in file '%s'.", cimglist_instance, size_x,size_y,filename?filename:"(FILE*)"); const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nlast_frame = first_frame<last_frame?last_frame:first_frame, nstep_frame = step_frame?step_frame:1; CImg<ucharT> tmp(size_x,size_y,1,3), UV(size_x/2,size_y/2,1,2); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb"); bool stopflag = false; int err; if (nfirst_frame) { err = std::fseek(nfile,nfirst_frame*(size_x*size_y + size_x*size_y/2),SEEK_CUR); if (err) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "load_yuv(): File '%s' doesn't contain frame number %u.", cimglist_instance, filename?filename:"(FILE*)",nfirst_frame); } } unsigned int frame; for (frame = nfirst_frame; !stopflag && frame<=nlast_frame; frame+=nstep_frame) { tmp.fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(tmp._data),1,(unsigned long)tmp._width*tmp._height,nfile); if (err!=(int)(tmp._width*tmp._height)) { stopflag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions (%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { UV.fill(0); // *TRY* to read the luminance part, do not replace by cimg::fread! err = (int)std::fread((void*)(UV._data),1,(size_t)(UV.size()),nfile); if (err!=(int)(UV.size())) { stopflag = true; if (err>0) cimg::warn(_cimglist_instance "load_yuv(): File '%s' contains incomplete data or given image dimensions (%u,%u) are incorrect.", cimglist_instance, filename?filename:"(FILE*)",size_x,size_y); } else { cimg_forXY(UV,x,y) { const int x2 = x*2, y2 = y*2; tmp(x2,y2,1) = tmp(x2+1,y2,1) = tmp(x2,y2+1,1) = tmp(x2+1,y2+1,1) = UV(x,y,0); tmp(x2,y2,2) = tmp(x2+1,y2,2) = tmp(x2,y2+1,2) = tmp(x2+1,y2+1,2) = UV(x,y,1); } if (yuv2rgb) tmp.YCbCrtoRGB(); insert(tmp); if (nstep_frame>1) std::fseek(nfile,(nstep_frame-1)*(size_x*size_y + size_x*size_y/2),SEEK_CUR); } } } if (stopflag && nlast_frame!=~0U && frame!=nlast_frame) cimg::warn(_cimglist_instance "load_yuv(): Frame %d not reached since only %u frames were found in file '%s'.", cimglist_instance, nlast_frame,frame-1,filename?filename:"(FILE*)"); if (!file) cimg::fclose(nfile); return *this; } //! Load an image from a video file, using ffmpeg libraries. /** \param filename Filename, as a C-string. \param first_frame Index of the first frame to read. \param last_frame Index of the last frame to read. \param step_frame Step value for frame reading. \param pixel_format To be documented. \param resume To be documented. **/ // This piece of code has been firstly created by David Starweather (starkdg(at)users(dot)sourceforge(dot)net) // I modified it afterwards for direct inclusion in the library core. CImgList<T>& load_ffmpeg(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool pixel_format=true, const bool resume=false) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_ffmpeg(): Specified filename is (null).", cimglist_instance); const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nlast_frame = first_frame<last_frame?last_frame:first_frame, nstep_frame = step_frame?step_frame:1; assign(); #ifndef cimg_use_ffmpeg if ((nfirst_frame || nlast_frame!=~0U || nstep_frame>1) || (resume && (pixel_format || !pixel_format))) throw CImgArgumentException(_cimglist_instance "load_ffmpeg(): Unable to load sub-frames from file '%s' unless libffmpeg is enabled.", cimglist_instance, filename); return load_ffmpeg_external(filename); #else const PixelFormat ffmpeg_pixfmt = pixel_format?PIX_FMT_RGB24:PIX_FMT_GRAY8; avcodec_register_all(); av_register_all(); static AVFormatContext *format_ctx = 0; static AVCodecContext *codec_ctx = 0; static AVCodec *codec = 0; static AVFrame *avframe = avcodec_alloc_frame(), *converted_frame = avcodec_alloc_frame(); static int vstream = 0; if (resume) { if (!format_ctx || !codec_ctx || !codec || !avframe || !converted_frame) throw CImgArgumentException(_cimglist_instance "load_ffmpeg(): Failed to resume loading of file '%s', due to unallocated FFMPEG structures.", cimglist_instance, filename); } else { // Open video file, find main video stream and codec. if (format_ctx) av_close_input_file(format_ctx); if (av_open_input_file(&format_ctx,filename,0,0,0)!=0) throw CImgIOException(_cimglist_instance "load_ffmpeg(): Failed to open file '%s'.", cimglist_instance, filename); if (!avframe || !converted_frame || av_find_stream_info(format_ctx)<0) { av_close_input_file(format_ctx); format_ctx = 0; return load_ffmpeg_external(filename); } #if cimg_verbosity>=3 dump_format(format_ctx,0,0,0); #endif // Special command: Return informations on main video stream. // as a vector 1x4 containing: (nb_frames,width,height,fps). if (!first_frame && !last_frame && !step_frame) { for (vstream = 0; vstream<(int)(format_ctx->nb_streams); ++vstream) if (format_ctx->streams[vstream]->codec->codec_type==CODEC_TYPE_VIDEO) break; if (vstream==(int)format_ctx->nb_streams) assign(); else { CImgList<doubleT> timestamps; int nb_frames; AVPacket packet; // Count frames and store timestamps. for (nb_frames = 0; av_read_frame(format_ctx,&packet)>=0; av_free_packet(&packet)) if (packet.stream_index==vstream) { CImg<doubleT>::vector((double)packet.pts).move_to(timestamps); ++nb_frames; } // Get frame with, height and fps. const int framew = format_ctx->streams[vstream]->codec->width, frameh = format_ctx->streams[vstream]->codec->height; const float num = (float)(format_ctx->streams[vstream]->r_frame_rate).num, den = (float)(format_ctx->streams[vstream]->r_frame_rate).den, fps = num/den; // Return infos as a list. assign(2); (*this)[0].assign(1,4).fill((T)nb_frames,(T)framew,(T)frameh,(T)fps); (*this)[1] = (timestamps>'y'); } av_close_input_file(format_ctx); format_ctx = 0; return *this; } for (vstream = 0; vstream<(int)(format_ctx->nb_streams) && format_ctx->streams[vstream]->codec->codec_type!=CODEC_TYPE_VIDEO; ) ++vstream; if (vstream==(int)format_ctx->nb_streams) { av_close_input_file(format_ctx); format_ctx = 0; return load_ffmpeg_external(filename); } codec_ctx = format_ctx->streams[vstream]->codec; codec = avcodec_find_decoder(codec_ctx->codec_id); if (!codec) { return load_ffmpeg_external(filename); } if (avcodec_open(codec_ctx,codec)<0) { // Open codec return load_ffmpeg_external(filename); } } // Read video frames const unsigned int numBytes = avpicture_get_size(ffmpeg_pixfmt,codec_ctx->width,codec_ctx->height); uint8_t *const buffer = new uint8_t[numBytes]; avpicture_fill((AVPicture *)converted_frame,buffer,ffmpeg_pixfmt,codec_ctx->width,codec_ctx->height); const T foo = (T)0; AVPacket packet; for (unsigned int frame = 0, next_frame = nfirst_frame; frame<=nlast_frame && av_read_frame(format_ctx,&packet)>=0; ) { if (packet.stream_index==(int)vstream) { int decoded = 0; #if defined(AV_VERSION_INT) #if LIBAVCODEC_VERSION_INT<AV_VERSION_INT(52,26,0) avcodec_decode_video(codec_ctx,avframe,&decoded,packet.data, packet.size); #else avcodec_decode_video2(codec_ctx,avframe,&decoded,&packet); #endif #else avcodec_decode_video(codec_ctx,avframe,&decoded,packet.data, packet.size); #endif if (decoded) { if (frame==next_frame) { SwsContext *c = sws_getContext(codec_ctx->width,codec_ctx->height,codec_ctx->pix_fmt,codec_ctx->width, codec_ctx->height,ffmpeg_pixfmt,1,0,0,0); sws_scale(c,avframe->data,avframe->linesize,0,codec_ctx->height,converted_frame->data,converted_frame->linesize); if (ffmpeg_pixfmt==PIX_FMT_RGB24) { CImg<ucharT> next_image(*converted_frame->data,3,codec_ctx->width,codec_ctx->height,1,true); next_image._get_permute_axes("yzcx",foo).move_to(*this); } else { CImg<ucharT> next_image(*converted_frame->data,1,codec_ctx->width,codec_ctx->height,1,true); next_image._get_permute_axes("yzcx",foo).move_to(*this); } next_frame+=nstep_frame; } ++frame; } av_free_packet(&packet); if (next_frame>nlast_frame) break; } } delete[] buffer; #endif return *this; } //! Load an image from a video file, using ffmpeg libraries \newinstance. static CImgList<T> get_load_ffmpeg(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1, const bool pixel_format=true) { return CImgList<T>().load_ffmpeg(filename,first_frame,last_frame,step_frame,pixel_format); } //! Load an image from a video file using the external tool 'ffmpeg'. /** \param filename Filename to read data from. **/ CImgList<T>& load_ffmpeg_external(const char *const filename) { if (!filename) throw CImgArgumentException(_cimglist_instance "load_ffmpeg_external(): Specified filename is (null).", cimglist_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }, filetmp2[512] = { 0 }; std::FILE *file = 0; do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_000001.ppm",filetmp); if ((file=std::fopen(filetmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_%%6d.ppm",filetmp); #if cimg_OS!=2 cimg_snprintf(command,sizeof(command),"%s -i \"%s\" %s >/dev/null 2>&1",cimg::ffmpeg_path(),filename,filetmp2); #else cimg_snprintf(command,sizeof(command),"\"%s -i \"%s\" %s\" >NUL 2>&1",cimg::ffmpeg_path(),filename,filetmp2); #endif cimg::system(command,0); const unsigned int omode = cimg::exception_mode(); cimg::exception_mode() = 0; assign(); unsigned int i = 1; for (bool stopflag = false; !stopflag; ++i) { cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_%.6u.ppm",filetmp,i); CImg<T> img; try { img.load_pnm(filetmp2); } catch (CImgException&) { stopflag = true; } if (img) { img.move_to(*this); std::remove(filetmp2); } } cimg::exception_mode() = omode; if (is_empty()) throw CImgIOException(_cimglist_instance "load_ffmpeg_external(): Failed to open file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); return *this; } //! Load an image from a video file using the external tool 'ffmpeg' \newinstance. static CImgList<T> get_load_ffmpeg_external(const char *const filename) { return CImgList<T>().load_ffmpeg_external(filename); } //! Load a gzipped list, using external tool 'gunzip'. /** \param filename Filename to read data from. **/ CImgList<T>& load_gzip_external(const char *const filename) { if (!filename) throw CImgIOException(_cimglist_instance "load_gzip_external(): Specified filename is (null).", cimglist_instance); std::fclose(cimg::fopen(filename,"rb")); // Check if file exists. char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file = 0; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); cimg_snprintf(command,sizeof(command),"%s -c \"%s\" > %s",cimg::gunzip_path(),filename,filetmp); cimg::system(command); if (!(file = std::fopen(filetmp,"rb"))) { cimg::fclose(cimg::fopen(filename,"r")); throw CImgIOException(_cimglist_instance "load_gzip_external(): Failed to open file '%s'.", cimglist_instance, filename); } else cimg::fclose(file); load(filetmp); std::remove(filetmp); return *this; } //! Load a gzipped list, using external tool 'gunzip' \newinstance. static CImgList<T> get_load_gzip_external(const char *const filename) { return CImgList<T>().load_gzip_external(filename); } //! Load a 3d object from a .OFF file. /** \param filename Filename to read data from. \param[out] primitives At return, contains the list of 3d object primitives. \param[out] colors At return, contains the list of 3d object colors. \return List of 3d object vertices. **/ template<typename tf, typename tc> CImgList<T>& load_off(const char *const filename, CImgList<tf>& primitives, CImgList<tc>& colors) { return get_load_off(filename,primitives,colors).move_to(*this); } //! Load a 3d object from a .OFF file \newinstance. template<typename tf, typename tc> static CImgList<T> get_load_off(const char *const filename, CImgList<tf>& primitives, CImgList<tc>& colors) { return CImg<T>().load_off(filename,primitives,colors)<'x'; } //! Load images from a TIFF file. /** \param filename Filename to read data from. \param first_frame Index of first image frame to read. \param last_frame Index of last image frame to read. \param step_frame Step applied between each frame. **/ CImgList<T>& load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { const unsigned int nfirst_frame = first_frame<last_frame?first_frame:last_frame, nstep_frame = step_frame?step_frame:1; unsigned int nlast_frame = first_frame<last_frame?last_frame:first_frame; #ifndef cimg_use_tiff if (nfirst_frame || nlast_frame!=~0U || nstep_frame!=1) throw CImgArgumentException(_cimglist_instance "load_tiff(): Unable to load sub-images from file '%s' unless libtiff is enabled.", cimglist_instance, filename); return assign(CImg<T>::get_load_tiff(filename)); #else TIFF *tif = TIFFOpen(filename,"r"); if (tif) { unsigned int nb_images = 0; do ++nb_images; while (TIFFReadDirectory(tif)); if (nfirst_frame>=nb_images || (nlast_frame!=~0U && nlast_frame>=nb_images)) cimg::warn(_cimglist_instance "load_tiff(): Invalid specified frame range is [%u,%u] (step %u) since file '%s' contains %u image(s).", cimglist_instance, nfirst_frame,nlast_frame,nstep_frame,filename,nb_images); if (nfirst_frame>=nb_images) return assign(); if (nlast_frame>=nb_images) nlast_frame = nb_images-1; assign(1+(nlast_frame-nfirst_frame)/nstep_frame); TIFFSetDirectory(tif,0); #if cimg_verbosity>=3 TIFFSetWarningHandler(0); TIFFSetErrorHandler(0); #endif cimglist_for(*this,l) _data[l]._load_tiff(tif,nfirst_frame + l*nstep_frame); TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "load_tiff(): Failed to open file '%s'.", cimglist_instance, filename); return *this; #endif } //! Load a multi-page TIFF file \newinstance. static CImgList<T> get_load_tiff(const char *const filename, const unsigned int first_frame=0, const unsigned int last_frame=~0U, const unsigned int step_frame=1) { return CImgList<T>().load_tiff(filename,first_frame,last_frame,step_frame); } //@} //---------------------------------- // //! \name Data Output //@{ //---------------------------------- //! Print informations about the list on the standard output. /** \param title Label set to the informations displayed. \param display_stats Tells if image statistics must be computed and displayed. **/ const CImgList<T>& print(const char *const title=0, const bool display_stats=true) const { unsigned int msiz = 0; cimglist_for(*this,l) msiz+=_data[l].size(); msiz*=sizeof(T); const unsigned int mdisp = msiz<8*1024?0:(msiz<8*1024*1024?1:2); char _title[64] = { 0 }; if (!title) cimg_snprintf(_title,sizeof(_title),"CImgList<%s>",pixel_type()); std::fprintf(cimg::output(),"%s%s%s%s: %sthis%s = %p, %ssize%s = %u/%u [%u %s], %sdata%s = (CImg<%s>*)%p", cimg::t_magenta,cimg::t_bold,title?title:_title,cimg::t_normal, cimg::t_bold,cimg::t_normal,(void*)this, cimg::t_bold,cimg::t_normal,_width,_allocated_width, mdisp==0?msiz:(mdisp==1?(msiz>>10):(msiz>>20)), mdisp==0?"b":(mdisp==1?"Kio":"Mio"), cimg::t_bold,cimg::t_normal,pixel_type(),(void*)begin()); if (_data) std::fprintf(cimg::output(),"..%p.\n",(void*)((char*)end()-1)); else std::fprintf(cimg::output(),".\n"); char tmp[16] = { 0 }; cimglist_for(*this,ll) { cimg_snprintf(tmp,sizeof(tmp),"[%d]",ll); std::fprintf(cimg::output()," "); _data[ll].print(tmp,display_stats); if (ll==3 && _width>8) { ll = _width-5; std::fprintf(cimg::output()," ...\n"); } } std::fflush(cimg::output()); return *this; } //! Display the current CImgList instance in an existing CImgDisplay window (by reference). /** \param disp Reference to an existing CImgDisplay instance, where the current image list will be displayed. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignmenet. \note This function displays the list images of the current CImgList instance into an existing CImgDisplay window. Images of the list are appended in a single temporarly image for visualization purposes. The function returns immediately. **/ const CImgList<T>& display(CImgDisplay &disp, const char axis='x', const float align=0) const { get_append(axis,align).display(disp); return *this; } //! Display the current CImgList instance in a new display window. /** \param disp Display window. \param display_info Tells if image informations are displayed on the standard output. \param axis Alignment axis for images viewing. \param align Apending alignment. \note This function opens a new window with a specific title and displays the list images of the current CImgList instance into it. Images of the list are appended in a single temporarly image for visualization purposes. The function returns when a key is pressed or the display window is closed by the user. **/ const CImgList<T>& display(CImgDisplay &disp, const bool display_info, const char axis='x', const float align=0, unsigned int *const XYZ=0) const { bool is_exit = false; return _display(disp,0,display_info,axis,align,XYZ,0,true,is_exit); } //! Display the current CImgList instance in a new display window. /** \param title Title of the opening display window. \param display_info Tells if list informations must be written on standard output. \param axis Appending axis. Can be <tt>{ 'x' | 'y' | 'z' | 'c' }</tt>. \param align Appending alignment. **/ const CImgList<T>& display(const char *const title=0, const bool display_info=true, const char axis='x', const float align=0, unsigned int *const XYZ=0) const { CImgDisplay disp; bool is_exit = false; return _display(disp,title,display_info,axis,align,XYZ,0,true,is_exit); } const CImgList<T>& _display(CImgDisplay &disp, const char *const title, const bool display_info, const char axis, const float align, unsigned int *const XYZ, const unsigned int orig, const bool is_first_call, bool &is_exit) const { if (is_empty()) throw CImgInstanceException(_cimglist_instance "display(): Empty instance.", cimglist_instance); if (!disp) { if (axis=='x') { unsigned int sum_width = 0, max_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); sum_width+=w; if (h>max_height) max_height = h; } disp.assign(cimg_fitscreen(sum_width,max_height,1),title?title:0,1); } else { unsigned int max_width = 0, sum_height = 0; cimglist_for(*this,l) { const CImg<T> &img = _data[l]; const unsigned int w = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,false), h = CImgDisplay::_fitscreen(img._width,img._height,img._depth,128,-85,true); if (w>max_width) max_width = w; sum_height+=h; } disp.assign(cimg_fitscreen(max_width,sum_height,1),title?title:0,1); } if (!title) disp.set_title("CImgList<%s> (%u)",pixel_type(),_width); } else if (title) disp.set_title("%s",title); const CImg<char> dtitle = CImg<char>::string(disp.title()); if (display_info) print(disp.title()); disp.show().flush(); if (_width==1) { const unsigned int dw = disp._width, dh = disp._height; if (!is_first_call) disp.resize(cimg_fitscreen(_data[0]._width,_data[0]._height,_data[0]._depth),false). set_title("%s (%ux%ux%ux%u)",dtitle.data(),_data[0]._width,_data[0]._height,_data[0]._depth,_data[0]._spectrum); _data[0]._display(disp,0,false,XYZ,!is_first_call); if (disp.key()) is_exit = true; disp.resize(cimg_fitscreen(dw,dh,1),false).set_title("%s",dtitle.data()); } else { bool disp_resize = !is_first_call; while (!disp.is_closed() && !is_exit) { const CImg<intT> s = _get_select(disp,0,true,axis,align,orig,disp_resize,!is_first_call,true); disp_resize = true; if (s[0]<0) { // No selections done. if (disp.button()&2) { disp.flush(); break; } is_exit = true; } else if (disp.wheel()) { // Zoom in/out. const int wheel = disp.wheel(); disp.set_wheel(); if (!is_first_call && wheel<0) break; if (wheel>0 && _width>=4) { const unsigned int delta = cimg::max(1U,(unsigned int)cimg::round(0.3*_width)), ind0 = (unsigned int)cimg::max(0,s[0] - (int)delta), ind1 = (unsigned int)cimg::min(width() - 1,s[0] + (int)delta); if ((ind0!=0 || ind1!=_width-1) && ind1 - ind0>=3) get_shared_images(ind0,ind1)._display(disp,0,false,axis,align,XYZ,orig + ind0,false,is_exit); } } else if (s[0]!=0 || s[1]!=width()-1) get_shared_images(s[0],s[1])._display(disp,0,false,axis,align,XYZ,orig+s[0],false,is_exit); } } return *this; } //! Save list into a file. /** \param filename Filename to write data to. \param number Number of digits used when chosen format requires the saving of multiple files. **/ const CImgList<T>& save(const char *const filename, const int number=-1) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save(): Specified filename is (null).", cimglist_instance); // Do not test for empty instances, since .cimg format is able to manage empty instances. const char *const ext = cimg::split_filename(filename); char nfilename[1024] = { 0 }; const char *const fn = (number>=0)?cimg::number_filename(filename,number,6,nfilename):filename; #ifdef cimglist_save_plugin cimglist_save_plugin(fn); #endif #ifdef cimglist_save_plugin1 cimglist_save_plugin1(fn); #endif #ifdef cimglist_save_plugin2 cimglist_save_plugin2(fn); #endif #ifdef cimglist_save_plugin3 cimglist_save_plugin3(fn); #endif #ifdef cimglist_save_plugin4 cimglist_save_plugin4(fn); #endif #ifdef cimglist_save_plugin5 cimglist_save_plugin5(fn); #endif #ifdef cimglist_save_plugin6 cimglist_save_plugin6(fn); #endif #ifdef cimglist_save_plugin7 cimglist_save_plugin7(fn); #endif #ifdef cimglist_save_plugin8 cimglist_save_plugin8(fn); #endif if (!cimg::strcasecmp(ext,"cimgz")) return save_cimg(fn,true); else if (!cimg::strcasecmp(ext,"cimg") || !*ext) return save_cimg(fn,false); else if (!cimg::strcasecmp(ext,"yuv")) return save_yuv(fn,true); else if (!cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return save_ffmpeg(fn); #ifdef cimg_use_tiff else if (!cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff")) return save_tiff(fn); #endif else if (!cimg::strcasecmp(ext,"gz")) return save_gzip_external(fn); else { if (_width==1) _data[0].save(fn,-1); else cimglist_for(*this,l) _data[l].save(fn,l); } return *this; } //! Tell if an image list can be saved as one single file. /** \param filename Filename, as a C-string. \return \c true if the file format supports multiple images, \c false otherwise. **/ static bool is_saveable(const char *const filename) { const char *const ext = cimg::split_filename(filename); if (!cimg::strcasecmp(ext,"cimgz") || #ifdef cimg_use_tiff !cimg::strcasecmp(ext,"tif") || !cimg::strcasecmp(ext,"tiff") || #endif !cimg::strcasecmp(ext,"yuv") || !cimg::strcasecmp(ext,"avi") || !cimg::strcasecmp(ext,"mov") || !cimg::strcasecmp(ext,"asf") || !cimg::strcasecmp(ext,"divx") || !cimg::strcasecmp(ext,"flv") || !cimg::strcasecmp(ext,"mpg") || !cimg::strcasecmp(ext,"m1v") || !cimg::strcasecmp(ext,"m2v") || !cimg::strcasecmp(ext,"m4v") || !cimg::strcasecmp(ext,"mjp") || !cimg::strcasecmp(ext,"mkv") || !cimg::strcasecmp(ext,"mpe") || !cimg::strcasecmp(ext,"movie") || !cimg::strcasecmp(ext,"ogm") || !cimg::strcasecmp(ext,"ogg") || !cimg::strcasecmp(ext,"qt") || !cimg::strcasecmp(ext,"rm") || !cimg::strcasecmp(ext,"vob") || !cimg::strcasecmp(ext,"wmv") || !cimg::strcasecmp(ext,"xvid") || !cimg::strcasecmp(ext,"mpeg")) return true; return false; } //! Save image sequence as a GIF animated file. /** \param filename Filename to write data to. \param fps Number of desired frames per second. \param nb_loops Number of loops (\c 0 for infinite looping). **/ const CImgList<T>& save_gif_external(const char *const filename, const unsigned int fps=25, const unsigned int nb_loops=0) { char command[1024] = { 0 }, filetmp[512] = { 0 }, filetmp2[512] = { 0 }; CImgList<charT> filenames; std::FILE *file = 0; #ifdef cimg_use_png #define _cimg_save_gif_ext "png" #else #define _cimg_save_gif_ext "ppm" #endif do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_000001." _cimg_save_gif_ext,filetmp); if ((file=std::fopen(filetmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_%.6u." _cimg_save_gif_ext,filetmp,l+1); CImg<charT>::string(filetmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save(filetmp2); else _data[l].save(filetmp2); } #if cimg_OS!=2 cimg_snprintf(command,sizeof(command),"%s -delay 1x%u -loop %u", cimg::imagemagick_path(),fps,nb_loops); CImg<ucharT>::string(command).move_to(filenames,0); cimg_snprintf(command,sizeof(command),"\"%s\" >/dev/null 2>&1", filename); CImg<ucharT>::string(command).move_to(filenames); #else cimg_snprintf(command,sizeof(command),"\"%s -delay 1x%u -loop %u", cimg::imagemagick_path(),fps,nb_loops); CImg<ucharT>::string(command).move_to(filenames,0); cimg_snprintf(command,sizeof(command),"\"%s\"\" >NUL 2>&1", filename); CImg<ucharT>::string(command).move_to(filenames); #endif CImg<charT> _command = filenames>'x'; cimg_for(_command,p,char) if (!*p) *p = ' '; _command.back() = 0; cimg::system(_command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gif_external(): Failed to save file '%s' with external command 'convert'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for_in(*this,1,filenames._width-2,l) std::remove(filenames[l]); return *this; } //! Save image sequence, using FFMPEG library. /** \param filename Filename to write data to. \param fps Desired framerate (in frames per seconds) if chosen format supports it. \param bitrate Desired bitrate (in bits per seconds) if chosen format supports it. **/ // This piece of code has been originally written by David. G. Starkweather. const CImgList<T>& save_ffmpeg(const char *const filename, const unsigned int fps=25, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_ffmpeg(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_ffmpeg(): Empty instance, for file '%s'.", cimglist_instance, filename); if (!fps) throw CImgArgumentException(_cimglist_instance "save_ffmpeg(): Invalid specified framerate 0, for file '%s'.", cimglist_instance, filename); cimglist_for(*this,l) if (!_data[l].is_sameXYZ(_data[0])) throw CImgInstanceException(_cimglist_instance "save_ffmpeg(): Invalid instance dimensions, for file '%s'.", cimglist_instance, filename); #ifndef cimg_use_ffmpeg return save_ffmpeg_external(filename,0,fps,bitrate); #else avcodec_register_all(); av_register_all(); const int frame_dimx = _data[0].width(), frame_dimy = _data[0].height(), frame_dimv = _data[0].spectrum(); if (frame_dimv!=1 && frame_dimv!=3) throw CImgInstanceException(_cimglist_instance "save_ffmpeg(): Image[0] (%u,%u,%u,%u,%p) has not 1 or 3 channels, for file '%s'.", cimglist_instance, _data[0]._width,_data[0]._height,_data[0]._depth,_data[0]._spectrum,_data,filename); PixelFormat dest_pxl_fmt = PIX_FMT_YUV420P; PixelFormat src_pxl_fmt = (frame_dimv==3)?PIX_FMT_RGB24:PIX_FMT_GRAY8; int sws_flags = SWS_FAST_BILINEAR; // Interpolation method (keeping same size images for now). AVOutputFormat *fmt = 0; #if defined(AV_VERSION_INT) #if LIBAVFORMAT_VERSION_INT<AV_VERSION_INT(52,45,0) fmt = guess_format(0,filename,0); if (!fmt) fmt = guess_format("mpeg",0,0); // Default format "mpeg". #else fmt = av_guess_format(0,filename,0); if (!fmt) fmt = av_guess_format("mpeg",0,0); // Default format "mpeg". #endif #else fmt = guess_format(0,filename,0); if (!fmt) fmt = guess_format("mpeg",0,0); // Default format "mpeg". #endif if (!fmt) throw CImgArgumentException(_cimglist_instance "save_ffmpeg(): Unable to determine codec for file '%s'.", cimglist_instance, filename); AVFormatContext *oc = 0; #if defined(AV_VERSION_INT) #if LIBAVFORMAT_VERSION_INT<AV_VERSION_INT(52,36,0) oc = av_alloc_format_context(); #else oc = avformat_alloc_context(); #endif #else oc = av_alloc_format_context(); #endif if (!oc) // Failed to allocate format context. throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate FFMPEG structure for format context, for file '%s'.", cimglist_instance, filename); AVCodec *codec = 0; AVFrame *picture = 0; AVFrame *tmp_pict = 0; oc->oformat = fmt; std::sprintf(oc->filename,"%s",filename); // Add video stream. int stream_index = 0; AVStream *video_str = 0; if (fmt->video_codec!=CODEC_ID_NONE) { video_str = av_new_stream(oc,stream_index); if (!video_str) { // Failed to allocate stream. av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate FFMPEG structure for video stream, for file '%s'.", cimglist_instance, filename); } } else { // No codec identified. av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to identify proper codec, for file '%s'.", cimglist_instance, filename); } AVCodecContext *c = video_str->codec; c->codec_id = fmt->video_codec; c->codec_type = CODEC_TYPE_VIDEO; c->bit_rate = 1024*bitrate; c->width = frame_dimx; c->height = frame_dimy; c->time_base.num = 1; c->time_base.den = fps; c->gop_size = 12; c->pix_fmt = dest_pxl_fmt; if (c->codec_id==CODEC_ID_MPEG2VIDEO) c->max_b_frames = 2; if (c->codec_id==CODEC_ID_MPEG1VIDEO) c->mb_decision = 2; if (av_set_parameters(oc,0)<0) { // Parameters not properly set. av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Invalid parameters set for avcodec, for file '%s'.", cimglist_instance, filename); } // Open codecs and alloc buffers. codec = avcodec_find_encoder(c->codec_id); if (!codec) { // Failed to find codec. av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): No valid codec found for file '%s'.", cimglist_instance, filename); } if (avcodec_open(c,codec)<0) // Failed to open codec. throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to open codec for file '%s'.", cimglist_instance, filename); tmp_pict = avcodec_alloc_frame(); if (!tmp_pict) { // Failed to allocate memory for tmp_pict frame. avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate memory for file '%s'.", cimglist_instance, filename); } tmp_pict->linesize[0] = (src_pxl_fmt==PIX_FMT_RGB24)?3*frame_dimx:frame_dimx; tmp_pict->type = FF_BUFFER_TYPE_USER; int tmp_size = avpicture_get_size(src_pxl_fmt,frame_dimx,frame_dimy); uint8_t *tmp_buffer = (uint8_t*)av_malloc(tmp_size); if (!tmp_buffer) { // Failed to allocate memory for tmp buffer. av_free(tmp_pict); avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate memory for file '%s'.", cimglist_instance, filename); } // Associate buffer with tmp_pict. avpicture_fill((AVPicture*)tmp_pict,tmp_buffer,src_pxl_fmt,frame_dimx,frame_dimy); picture = avcodec_alloc_frame(); if (!picture) { // Failed to allocate picture frame. av_free(tmp_pict->data[0]); av_free(tmp_pict); avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate memory for file '%s'.", cimglist_instance, filename); } int size = avpicture_get_size(c->pix_fmt,frame_dimx,frame_dimy); uint8_t *buffer = (uint8_t*)av_malloc(size); if (!buffer) { // Failed to allocate picture frame buffer. av_free(picture); av_free(tmp_pict->data[0]); av_free(tmp_pict); avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate memory for file '%s'.", cimglist_instance, filename); } // Associate the buffer with picture. avpicture_fill((AVPicture*)picture,buffer,c->pix_fmt,frame_dimx,frame_dimy); // Open file. if (!(fmt->flags&AVFMT_NOFILE)) { if (url_fopen(&oc->pb,filename,URL_WRONLY)<0) throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to open file '%s'.", cimglist_instance, filename); } if (av_write_header(oc)<0) throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to write header in file '%s'.", cimglist_instance, filename); SwsContext *img_convert_context = 0; img_convert_context = sws_getContext(frame_dimx,frame_dimy,src_pxl_fmt, c->width,c->height,c->pix_fmt,sws_flags,0,0,0); if (!img_convert_context) { // Failed to get swscale context. // if (!(fmt->flags & AVFMT_NOFILE)) url_fclose(&oc->pb); av_free(picture->data); av_free(picture); av_free(tmp_pict->data[0]); av_free(tmp_pict); avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to get conversion context for file '%s'.", cimglist_instance, filename); } int ret = 0, out_size; uint8_t *video_outbuf = 0; int video_outbuf_size = 1000000; video_outbuf = (uint8_t*)av_malloc(video_outbuf_size); if (!video_outbuf) { // if (!(fmt->flags & AVFMT_NOFILE)) url_fclose(&oc->pb); av_free(picture->data); av_free(picture); av_free(tmp_pict->data[0]); av_free(tmp_pict); avcodec_close(video_str->codec); av_free(oc); throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to allocate memory, for file '%s'.", cimglist_instance, filename); } // Loop through each desired image in list. cimglist_for(*this,i) { CImg<uint8_t> currentIm = _data[i], red, green, blue, gray; if (src_pxl_fmt==PIX_FMT_RGB24) { red = currentIm.get_shared_channel(0); green = currentIm.get_shared_channel(1); blue = currentIm.get_shared_channel(2); cimg_forXY(currentIm,X,Y) { // Assign pizel values to data buffer in interlaced RGBRGB ... format. tmp_pict->data[0][Y*tmp_pict->linesize[0] + 3*X] = red(X,Y); tmp_pict->data[0][Y*tmp_pict->linesize[0] + 3*X + 1] = green(X,Y); tmp_pict->data[0][Y*tmp_pict->linesize[0] + 3*X + 2] = blue(X,Y); } } else { gray = currentIm.get_shared_channel(0); cimg_forXY(currentIm,X,Y) tmp_pict->data[0][Y*tmp_pict->linesize[0] + X] = gray(X,Y); } if (!video_str) break; if (sws_scale(img_convert_context,tmp_pict->data,tmp_pict->linesize,0,c->height,picture->data,picture->linesize)<0) break; out_size = avcodec_encode_video(c,video_outbuf,video_outbuf_size,picture); if (out_size>0) { AVPacket pkt; av_init_packet(&pkt); pkt.pts = av_rescale_q(c->coded_frame->pts,c->time_base,video_str->time_base); if (c->coded_frame->key_frame) pkt.flags|=PKT_FLAG_KEY; pkt.stream_index = video_str->index; pkt.data = video_outbuf; pkt.size = out_size; ret = av_write_frame(oc,&pkt); } else if (out_size<0) break; if (ret) break; // Error occured in writing frame. } // Close codec. if (video_str) { avcodec_close(video_str->codec); av_free(picture->data[0]); av_free(picture); av_free(tmp_pict->data[0]); av_free(tmp_pict); } if (av_write_trailer(oc)<0) throw CImgIOException(_cimglist_instance "save_ffmpeg(): Failed to write trailer for file '%s'.", cimglist_instance, filename); av_freep(&oc->streams[stream_index]->codec); av_freep(&oc->streams[stream_index]); if (!(fmt->flags&AVFMT_NOFILE)) { /*if (url_fclose(oc->pb)<0) throw CImgIOException(_cimglist_instance "save_ffmpeg(): File '%s', failed to close file.", cimglist_instance, filename); */ } av_free(oc); av_free(video_outbuf); #endif return *this; } const CImgList<T>& _save_yuv(std::FILE *const file, const char *const filename, const bool is_rgb) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_yuv(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_yuv(): Empty instance, for file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); if ((*this)[0].width()%2 || (*this)[0].height()%2) throw CImgInstanceException(_cimglist_instance "save_yuv(): Invalid odd instance dimensions (%u,%u) for file '%s'.", cimglist_instance, (*this)[0].width(),(*this)[0].height(), filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); cimglist_for(*this,l) { CImg<ucharT> YCbCr((*this)[l]); if (is_rgb) YCbCr.RGBtoYCbCr(); cimg::fwrite(YCbCr._data,(unsigned long)YCbCr._width*YCbCr._height,nfile); cimg::fwrite(YCbCr.get_resize(YCbCr._width/2, YCbCr._height/2,1,3,3).data(0,0,0,1), (unsigned long)YCbCr._width*YCbCr._height/2,nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save list as a YUV image sequence file. /** \param filename Filename to write data to. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(const char *const filename=0, const bool is_rgb=true) const { return _save_yuv(0,filename,is_rgb); } //! Save image sequence into a YUV file. /** \param file File to write data to. \param is_rgb Tells if the RGB to YUV conversion must be done for saving. **/ const CImgList<T>& save_yuv(std::FILE *const file, const bool is_rgb=true) const { return _save_yuv(file,0,is_rgb); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const bool is_compressed) const { if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); #ifndef cimg_use_zlib if (is_compressed) cimg::warn(_cimglist_instance "save_cimg(): Unable to save compressed data in file '%s' unless zlib is enabled, saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); #endif std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const char *const ptype = pixel_type(), *const etype = cimg::endianness()?"big":"little"; if (std::strstr(ptype,"unsigned")==ptype) std::fprintf(nfile,"%u unsigned_%s %s_endian\n",_width,ptype+9,etype); else std::fprintf(nfile,"%u %s %s_endian\n",_width,ptype,etype); cimglist_for(*this,l) { const CImg<T>& img = _data[l]; std::fprintf(nfile,"%u %u %u %u",img._width,img._height,img._depth,img._spectrum); if (img._data) { CImg<T> tmp; if (cimg::endianness()) { tmp = img; cimg::invert_endianness(tmp._data,tmp.size()); } const CImg<T>& ref = cimg::endianness()?tmp:img; bool failed_to_compress = true; if (is_compressed) { #ifdef cimg_use_zlib const unsigned long siz = sizeof(T)*ref.size(); unsigned long csiz = siz + siz/100 + 16; Bytef *const cbuf = new Bytef[csiz]; if (compress(cbuf,&csiz,(Bytef*)ref._data,siz)) cimg::warn(_cimglist_instance "save_cimg(): Failed to save compressed data for file '%s', saving them uncompressed.", cimglist_instance, filename?filename:"(FILE*)"); else { std::fprintf(nfile," #%lu\n",csiz); cimg::fwrite(cbuf,csiz,nfile); delete[] cbuf; failed_to_compress = false; } #endif } if (failed_to_compress) { // Write in a non-compressed way. std::fputc('\n',nfile); cimg::fwrite(ref._data,ref.size(),nfile); } } else std::fputc('\n',nfile); } if (!file) cimg::fclose(nfile); return *this; } //! Save list into a .cimg file. /** \param filename Filename to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(const char *const filename, const bool is_compressed=false) const { return _save_cimg(0,filename,is_compressed); } //! Save list into a .cimg file. /** \param file File to write data to. \param is_compressed Tells if data compression must be enabled. **/ const CImgList<T>& save_cimg(std::FILE *file, const bool is_compressed=false) const { return _save_cimg(file,0,is_compressed); } const CImgList<T>& _save_cimg(std::FILE *const file, const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { #define _cimg_save_cimg_case(Ts,Tss) \ if (!saved && !cimg::strcasecmp(Ts,str_pixeltype)) { \ for (unsigned int l = 0; l<lmax; ++l) { \ j = 0; while((i=std::fgetc(nfile))!='\n') tmp[j++]=(char)i; tmp[j] = 0; \ W = H = D = C = 0; \ if (std::sscanf(tmp,"%u %u %u %u",&W,&H,&D,&C)!=4) \ throw CImgIOException(_cimglist_instance \ "save_cimg(): Invalid size (%u,%u,%u,%u) of image[%u], for file '%s'.", \ cimglist_instance, \ W,H,D,C,l,filename?filename:"(FILE*)"); \ if (W*H*D*C>0) { \ if (l<n0 || x0>=W || y0>=H || z0>=D || c0>=D) std::fseek(nfile,W*H*D*C*sizeof(Tss),SEEK_CUR); \ else { \ const CImg<T>& img = (*this)[l - n0]; \ const T *ptrs = img._data; \ const unsigned int \ x1 = x0 + img._width - 1, \ y1 = y0 + img._height - 1, \ z1 = z0 + img._depth - 1, \ c1 = c0 + img._spectrum - 1, \ nx1 = x1>=W?W-1:x1, \ ny1 = y1>=H?H-1:y1, \ nz1 = z1>=D?D-1:z1, \ nc1 = c1>=C?C-1:c1; \ CImg<Tss> raw(1+nx1-x0); \ const unsigned int skipvb = c0*W*H*D*sizeof(Tss); \ if (skipvb) std::fseek(nfile,skipvb,SEEK_CUR); \ for (unsigned int v = 1 + nc1 - c0; v; --v) { \ const unsigned int skipzb = z0*W*H*sizeof(Tss); \ if (skipzb) std::fseek(nfile,skipzb,SEEK_CUR); \ for (unsigned int z = 1 + nz1 - z0; z; --z) { \ const unsigned int skipyb = y0*W*sizeof(Tss); \ if (skipyb) std::fseek(nfile,skipyb,SEEK_CUR); \ for (unsigned int y = 1 + ny1 - y0; y; --y) { \ const unsigned int skipxb = x0*sizeof(Tss); \ if (skipxb) std::fseek(nfile,skipxb,SEEK_CUR); \ raw.assign(ptrs, raw._width); \ ptrs+=img._width; \ if (endian) cimg::invert_endianness(raw._data,raw._width); \ cimg::fwrite(raw._data,raw._width,nfile); \ const unsigned int skipxe = (W - 1 - nx1)*sizeof(Tss); \ if (skipxe) std::fseek(nfile,skipxe,SEEK_CUR); \ } \ const unsigned int skipye = (H - 1 - ny1)*W*sizeof(Tss); \ if (skipye) std::fseek(nfile,skipye,SEEK_CUR); \ } \ const unsigned int skipze = (D - 1 - nz1)*W*H*sizeof(Tss); \ if (skipze) std::fseek(nfile,skipze,SEEK_CUR); \ } \ const unsigned int skipve = (C - 1 - nc1)*W*H*D*sizeof(Tss); \ if (skipve) std::fseek(nfile,skipve,SEEK_CUR); \ } \ } \ } \ saved = true; \ } if (!file && !filename) throw CImgArgumentException(_cimglist_instance "save_cimg(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_cimg(): Empty instance, for file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); std::FILE *const nfile = file?file:cimg::fopen(filename,"rb+"); bool saved = false, endian = cimg::endianness(); char tmp[256] = { 0 }, str_pixeltype[256] = { 0 }, str_endian[256] = { 0 }; unsigned int j, err, N, W, H, D, C; int i; j = 0; while((i=std::fgetc(nfile))!='\n' && i!=EOF && j<256) tmp[j++] = (char)i; tmp[j] = 0; err = std::sscanf(tmp,"%u%*c%255[A-Za-z_]%*c%255[sA-Za-z_ ]",&N,str_pixeltype,str_endian); if (err<2) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): CImg header not found in file '%s'.", cimglist_instance, filename?filename:"(FILE*)"); } if (!cimg::strncasecmp("little",str_endian,6)) endian = false; else if (!cimg::strncasecmp("big",str_endian,3)) endian = true; const unsigned int lmax = cimg::min(N,n0+_width); _cimg_save_cimg_case("bool",bool); _cimg_save_cimg_case("unsigned_char",unsigned char); _cimg_save_cimg_case("uchar",unsigned char); _cimg_save_cimg_case("char",char); _cimg_save_cimg_case("unsigned_short",unsigned short); _cimg_save_cimg_case("ushort",unsigned short); _cimg_save_cimg_case("short",short); _cimg_save_cimg_case("unsigned_int",unsigned int); _cimg_save_cimg_case("uint",unsigned int); _cimg_save_cimg_case("int",int); _cimg_save_cimg_case("unsigned_long",unsigned long); _cimg_save_cimg_case("ulong",unsigned long); _cimg_save_cimg_case("long",long); _cimg_save_cimg_case("float",float); _cimg_save_cimg_case("double",double); if (!saved) { if (!file) cimg::fclose(nfile); throw CImgIOException(_cimglist_instance "save_cimg(): Unsupported data type '%s' for file '%s'.", cimglist_instance, filename?filename:"(FILE*)",str_pixeltype); } if (!file) cimg::fclose(nfile); return *this; } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param filename Filename to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(const char *const filename, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(0,filename,n0,x0,y0,z0,c0); } //! Insert the image instance into into an existing .cimg file, at specified coordinates. /** \param file File to write data to. \param n0 Starting index of images to write. \param x0 Starting X-coordinates of image regions to write. \param y0 Starting Y-coordinates of image regions to write. \param z0 Starting Z-coordinates of image regions to write. \param c0 Starting C-coordinates of image regions to write. **/ const CImgList<T>& save_cimg(std::FILE *const file, const unsigned int n0, const unsigned int x0, const unsigned int y0, const unsigned int z0, const unsigned int c0) const { return _save_cimg(file,0,n0,x0,y0,z0,c0); } static void _save_empty_cimg(std::FILE *const file, const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy, const unsigned int dz, const unsigned int dc) { std::FILE *const nfile = file?file:cimg::fopen(filename,"wb"); const unsigned long siz = (unsigned long)dx*dy*dz*dc*sizeof(T); std::fprintf(nfile,"%u %s\n",nb,pixel_type()); for (unsigned int i=nb; i; --i) { std::fprintf(nfile,"%u %u %u %u\n",dx,dy,dz,dc); for (unsigned long off=siz; off; --off) std::fputc(0,nfile); } if (!file) cimg::fclose(nfile); } //! Save empty (non-compressed) .cimg file with specified dimensions. /** \param filename Filename to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(const char *const filename, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(0,filename,nb,dx,dy,dz,dc); } //! Save empty .cimg file with specified dimensions. /** \param file File to write data to. \param nb Number of images to write. \param dx Width of images in the written file. \param dy Height of images in the written file. \param dz Depth of images in the written file. \param dc Spectrum of images in the written file. **/ static void save_empty_cimg(std::FILE *const file, const unsigned int nb, const unsigned int dx, const unsigned int dy=1, const unsigned int dz=1, const unsigned int dc=1) { return _save_empty_cimg(file,0,nb,dx,dy,dz,dc); } //! Save list as a TIFF file. /** \param filename Filename to write data to. \param compression_type Compression mode used to write data. **/ const CImgList<T>& save_tiff(const char *const filename, const unsigned int compression_type=0) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_tiff(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_tiff(): Empty instance, for file '%s'.", cimglist_instance, filename); #ifndef cimg_use_tiff if (_width==1) _data[0].save_tiff(filename,compression_type); else cimglist_for(*this,l) { char nfilename[1024] = { 0 }; cimg::number_filename(filename,l,6,nfilename); _data[l].save_tiff(nfilename,compression_type); } #else TIFF *tif = TIFFOpen(filename,"w"); if (tif) { for (unsigned int dir = 0, l = 0; l<_width; ++l) { const CImg<T>& img = (*this)[l]; if (img) { if (img._depth==1) img._save_tiff(tif,dir++,compression_type); else cimg_forZ(img,z) img.get_slice(z)._save_tiff(tif,dir++,compression_type); } } TIFFClose(tif); } else throw CImgIOException(_cimglist_instance "save_tiff(): Failed to open stream for file '%s'.", cimglist_instance, filename); #endif return *this; } //! Save list as a gzipped file, using external tool 'gzip'. /** \param filename Filename to write data to. **/ const CImgList<T>& save_gzip_external(const char *const filename) const { if (!filename) throw CImgIOException(_cimglist_instance "save_gzip_external(): Specified filename is (null).", cimglist_instance); char command[1024] = { 0 }, filetmp[512] = { 0 }, body[512] = { 0 }; const char *ext = cimg::split_filename(filename,body), *ext2 = cimg::split_filename(body,0); std::FILE *file; do { if (!cimg::strcasecmp(ext,"gz")) { if (*ext2) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext2); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.cimg",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } else { if (*ext) cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand(),ext); else cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s.cimg",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); } if ((file=std::fopen(filetmp,"rb"))!=0) cimg::fclose(file); } while (file); if (is_saveable(body)) { save(filetmp); cimg_snprintf(command,sizeof(command),"%s -c %s > \"%s\"",cimg::gzip_path(),filetmp,filename); cimg::system(command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_gzip_external(): Failed to save file '%s' with external command 'gzip'.", cimglist_instance, filename); else cimg::fclose(file); std::remove(filetmp); } else { char nfilename[1024] = { 0 }; cimglist_for(*this,l) { cimg::number_filename(body,l,6,nfilename); if (*ext) std::sprintf(nfilename + std::strlen(nfilename),".%s",ext); _data[l].save_gzip_external(nfilename); } } return *this; } //! Save image sequence, using the external tool 'ffmpeg'. /** \param filename Filename to write data to. \param codec Type of compression. \param fps Number of frames per second. \param bitrate Output bitrate **/ const CImgList<T>& save_ffmpeg_external(const char *const filename, const char *const codec=0, const unsigned int fps=25, const unsigned int bitrate=2048) const { if (!filename) throw CImgArgumentException(_cimglist_instance "save_ffmpeg_external(): Specified filename is (null).", cimglist_instance); if (is_empty()) throw CImgInstanceException(_cimglist_instance "save_ffmpeg_external(): Empty instance, for file '%s'.", cimglist_instance, filename); const char *const ext = cimg::split_filename(filename), *const _codec = codec?codec:!cimg::strcasecmp(ext,"flv")?"flv":"mpeg2video"; char command[1024] = { 0 }, filetmp[512] = { 0 }, filetmp2[512] = { 0 }; CImgList<charT> filenames; std::FILE *file = 0; cimglist_for(*this,l) if (!_data[l].is_sameXYZ(_data[0])) throw CImgInstanceException(_cimglist_instance "save_ffmpeg_external(): Invalid instance dimensions for file '%s'.", cimglist_instance, filename); do { cimg_snprintf(filetmp,sizeof(filetmp),"%s%c%s",cimg::temporary_path(),cimg_file_separator,cimg::filenamerand()); cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_000001.ppm",filetmp); if ((file=std::fopen(filetmp2,"rb"))!=0) cimg::fclose(file); } while (file); cimglist_for(*this,l) { cimg_snprintf(filetmp2,sizeof(filetmp2),"%s_%.6u.ppm",filetmp,l+1); CImg<charT>::string(filetmp2).move_to(filenames); if (_data[l]._depth>1 || _data[l]._spectrum!=3) _data[l].get_resize(-100,-100,1,3).save_pnm(filetmp2); else _data[l].save_pnm(filetmp2); } #if cimg_OS!=2 cimg_snprintf(command,sizeof(command),"%s -i %s_%%6d.ppm -vcodec %s -b %uk -r %u -y \"%s\" >/dev/null 2>&1", cimg::ffmpeg_path(),filetmp,_codec,bitrate,fps,filename); #else cimg_snprintf(command,sizeof(command),"\"%s -i %s_%%6d.ppm -vcodec %s -b %uk -r %u -y \"%s\"\" >NUL 2>&1", cimg::ffmpeg_path(),filetmp,_codec,bitrate,fps,filename); #endif cimg::system(command); file = std::fopen(filename,"rb"); if (!file) throw CImgIOException(_cimglist_instance "save_ffmpeg_external(): Failed to save file '%s' with external command 'ffmpeg'.", cimglist_instance, filename); else cimg::fclose(file); cimglist_for(*this,l) std::remove(filenames[l]); return *this; } //@} //---------------------------------- // //! \name Others //@{ //---------------------------------- //! Crop font along the X-axis. /** **/ CImgList<T>& crop_font() { return get_crop_font().move_to(*this); } //! Crop font along the X-axis \newinstance. /** **/ CImgList<T> get_crop_font() const { CImgList<T> res; cimglist_for(*this,l) { const CImg<T>& letter = (*this)[l]; int xmin = letter._width, xmax = 0; cimg_forXY(letter,x,y) if (letter(x,y)) { if (x<xmin) xmin = x; if (x>xmax) xmax = x; } if (xmin>xmax) CImg<T>(letter._width,letter._height,1,letter._spectrum,0).move_to(res); else letter.get_crop(xmin,0,xmax,letter._height-1).move_to(res); } res[' '].resize(res['f']._width,-100,-100,-100,0); if (' '+256<res.size()) res[' '+256].resize(res['f']._width,-100,-100,-100,0); return res; } //! Return a CImg pre-defined font with desired size. /** \param font_height Height of the desired font (exact match for 11,13,17,19,24,32,38,57) \param is_variable_width Decide if the font has a variable (\c true) or fixed (\c false) width. **/ static const CImgList<T>& font(const unsigned int font_height, const bool is_variable_width=true) { #define _cimg_font(sx,sy) \ if (!is_variable_width && (!font || font[0]._height!=sy)) font = _font(cimg::font##sx##x##sy,sx,sy,false); \ if (is_variable_width && (!vfont || vfont[0]._height!=sy)) vfont = _font(cimg::font##sx##x##sy,sx,sy,true); \ if (font_height==sy) return is_variable_width?vfont:font; \ if (is_variable_width) { \ if (cvfont && font_height==cvfont[0]._height) return cvfont; \ cvfont = vfont; \ cimglist_for(cvfont,l) \ cvfont[l].resize(cimg::max(1U,cvfont[l]._width*font_height/cvfont[l]._height),font_height,-100,-100, \ cvfont[0]._height>font_height?2:5); \ return cvfont; \ } else { \ if (cfont && font_height==cfont[0]._height) return cfont; \ cfont = font; \ cimglist_for(cfont,l) \ cfont[l].resize(cimg::max(1U,cfont[l]._width*font_height/cfont[l]._height),font_height,-100,-100, \ cfont[0]._height>font_height?2:5); \ return cfont; \ } \ static CImgList<T> font, vfont, cfont, cvfont; if (!font_height) return CImgList<T>::empty(); if (font_height<=13) { _cimg_font(10,13); } // [1,13] -> ref 13 if (font_height<=28) { _cimg_font(12,24); } // [14,28] -> ref 24 if (font_height<=32) { _cimg_font(16,32); } // [29,32] -> ref 32 _cimg_font(29,57); // [33,+inf] -> ref 57 } static CImgList<T> _font(const unsigned int *const font, const unsigned int w, const unsigned int h, const bool is_variable_width) { CImgList<T> res(256,w,h,1,1); const unsigned int *ptr = font; unsigned int m = 0, val = 0; for (unsigned int y = 0; y<h; ++y) for (unsigned int x = 0; x<256*w; ++x) { m>>=1; if (!m) { m = 0x80000000; val = *(ptr++); } CImg<T>& img = res[x/w]; unsigned int xm = x%w; img(xm,y) = (T)((val&m)?1:0); } if (is_variable_width) res.crop_font(); return res.insert(res); } //! Compute a 1d Fast Fourier Transform, along specified axis. /** \param axis Axis along which the Fourier transform is computed. \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const char axis, const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],axis,invert); return *this; } //! Compute a 1-D Fast Fourier Transform, along specified axis \newinstance. CImgList<Tfloat> get_FFT(const char axis, const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(axis,invert); } //! Compute a n-d Fast Fourier Transform. /** \param invert Tells if the direct (\c false) or inverse transform (\c true) is computed. **/ CImgList<T>& FFT(const bool invert=false) { if (is_empty()) return *this; if (_width==1) insert(1); if (_width>2) cimg::warn(_cimglist_instance "FFT(): Instance has more than 2 images", cimglist_instance); CImg<T>::FFT(_data[0],_data[1],invert); return *this; } //! Compute a n-d Fast Fourier Transform \newinstance. CImgList<Tfloat> get_FFT(const bool invert=false) const { return CImgList<Tfloat>(*this,false).FFT(invert); } //! Reverse primitives orientations of a 3d object. /** **/ CImgList<T>& reverse_object3d() { cimglist_for(*this,l) { CImg<T>& p = _data[l]; switch (p.size()) { case 2: case 3: cimg::swap(p[0],p[1]); break; case 6: cimg::swap(p[0],p[1],p[2],p[4],p[3],p[5]); break; case 9: cimg::swap(p[0],p[1],p[3],p[5],p[4],p[6]); break; case 4: cimg::swap(p[0],p[1],p[2],p[3]); break; case 12: cimg::swap(p[0],p[1],p[2],p[3],p[4],p[6],p[5],p[7],p[8],p[10],p[9],p[11]); break; } } return *this; } //! Reverse primitives orientations of a 3d object \newinstance. CImgList<T> get_reverse_object3d() const { return (+*this).reverse_object3d(); } //@} }; // struct CImgList<T> { ... /* #--------------------------------------------- # # Completion of previously declared functions # #---------------------------------------------- */ namespace cimg { //! Display a simple dialog box, and wait for the user's response. /** \param title Title of the dialog window. \param msg Main message displayed inside the dialog window. \param button1_label Label of the 1st button. \param button2_label Label of the 2nd button (\c 0 to hide button). \param button3_label Label of the 3rd button (\c 0 to hide button). \param button4_label Label of the 4th button (\c 0 to hide button). \param button5_label Label of the 5th button (\c 0 to hide button). \param button6_label Label of the 6th button (\c 0 to hide button). \param logo Image logo displayed at the left of the main message. \param is_centered Tells if the dialog window must be centered on the screen. \return Indice of clicked button (from \c 0 to \c 5), or \c -1 if the dialog window has been closed by the user. \note - Up to 6 buttons can be defined in the dialog window. - The function returns when a user clicked one of the button or closed the dialog window. - If a button text is set to 0, the corresponding button (and the followings) will not appear in the dialog box. At least one button must be specified. **/ template<typename t> inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const CImg<t>& logo, const bool is_centered = false) { #if cimg_display==0 cimg::unused(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label,logo._data,is_centered); throw CImgIOException("cimg::dialog(): No display available."); #else const unsigned char black[] = { 0,0,0 }, white[] = { 255,255,255 }, gray[] = { 200,200,200 }, gray2[] = { 150,150,150 }; // Create buttons and canvas graphics CImgList<unsigned char> buttons, cbuttons, sbuttons; if (button1_label) { CImg<unsigned char>().draw_text(0,0,button1_label,black,gray,1,13).move_to(buttons); if (button2_label) { CImg<unsigned char>().draw_text(0,0,button2_label,black,gray,1,13).move_to(buttons); if (button3_label) { CImg<unsigned char>().draw_text(0,0,button3_label,black,gray,1,13).move_to(buttons); if (button4_label) { CImg<unsigned char>().draw_text(0,0,button4_label,black,gray,1,13).move_to(buttons); if (button5_label) { CImg<unsigned char>().draw_text(0,0,button5_label,black,gray,1,13).move_to(buttons); if (button6_label) { CImg<unsigned char>().draw_text(0,0,button6_label,black,gray,1,13).move_to(buttons); }}}}}} if (!buttons._width) throw CImgArgumentException("cimg::dialog(): No buttons have been defined."); cimglist_for(buttons,l) buttons[l].resize(-100,-100,1,3); unsigned int bw = 0, bh = 0; cimglist_for(buttons,l) { bw = cimg::max(bw,buttons[l]._width); bh = cimg::max(bh,buttons[l]._height); } bw+=8; bh+=8; if (bw<64) bw = 64; if (bw>128) bw = 128; if (bh<24) bh = 24; if (bh>48) bh = 48; CImg<unsigned char> button(bw,bh,1,3); button.draw_rectangle(0,0,bw-1,bh-1,gray); button.draw_line(0,0,bw-1,0,white).draw_line(0,bh-1,0,0,white); button.draw_line(bw-1,0,bw-1,bh-1,black).draw_line(bw-1,bh-1,0,bh-1,black); button.draw_line(1,bh-2,bw-2,bh-2,gray2).draw_line(bw-2,bh-2,bw-2,1,gray2); CImg<unsigned char> sbutton(bw,bh,1,3); sbutton.draw_rectangle(0,0,bw-1,bh-1,gray); sbutton.draw_line(0,0,bw-1,0,black).draw_line(bw-1,0,bw-1,bh-1,black); sbutton.draw_line(bw-1,bh-1,0,bh-1,black).draw_line(0,bh-1,0,0,black); sbutton.draw_line(1,1,bw-2,1,white).draw_line(1,bh-2,1,1,white); sbutton.draw_line(bw-2,1,bw-2,bh-2,black).draw_line(bw-2,bh-2,1,bh-2,black); sbutton.draw_line(2,bh-3,bw-3,bh-3,gray2).draw_line(bw-3,bh-3,bw-3,2,gray2); sbutton.draw_line(4,4,bw-5,4,black,1,0xAAAAAAAA,true).draw_line(bw-5,4,bw-5,bh-5,black,1,0xAAAAAAAA,false); sbutton.draw_line(bw-5,bh-5,4,bh-5,black,1,0xAAAAAAAA,false).draw_line(4,bh-5,4,4,black,1,0xAAAAAAAA,false); CImg<unsigned char> cbutton(bw,bh,1,3); cbutton.draw_rectangle(0,0,bw-1,bh-1,black).draw_rectangle(1,1,bw-2,bh-2,gray2).draw_rectangle(2,2,bw-3,bh-3,gray); cbutton.draw_line(4,4,bw-5,4,black,1,0xAAAAAAAA,true).draw_line(bw-5,4,bw-5,bh-5,black,1,0xAAAAAAAA,false); cbutton.draw_line(bw-5,bh-5,4,bh-5,black,1,0xAAAAAAAA,false).draw_line(4,bh-5,4,4,black,1,0xAAAAAAAA,false); cimglist_for(buttons,ll) { CImg<unsigned char>(cbutton).draw_image(1+(bw-buttons[ll].width())/2,1+(bh-buttons[ll].height())/2,buttons[ll]). move_to(cbuttons); CImg<unsigned char>(sbutton).draw_image((bw-buttons[ll].width())/2,(bh-buttons[ll].height())/2,buttons[ll]). move_to(sbuttons); CImg<unsigned char>(button).draw_image((bw-buttons[ll].width())/2,(bh-buttons[ll].height())/2,buttons[ll]). move_to(buttons[ll]); } CImg<unsigned char> canvas; if (msg) CImg<unsigned char>().draw_text(0,0,"%s",black,gray,1,13,msg).resize(-100,-100,1,3).move_to(canvas); const unsigned int bwall = (buttons._width-1)*(12+bw) + bw, w = cimg::max(196U,36+logo._width+canvas._width,24+bwall), h = cimg::max(96U,36+canvas._height+bh,36+logo._height+bh), lx = 12 + (canvas._data?0:((w-24-logo._width)/2)), ly = (h-12-bh-logo._height)/2, tx = lx+logo._width+12, ty = (h-12-bh-canvas._height)/2, bx = (w-bwall)/2, by = h-12-bh; if (canvas._data) canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w-1,h-1,gray). draw_line(0,0,w-1,0,white).draw_line(0,h-1,0,0,white). draw_line(w-1,0,w-1,h-1,black).draw_line(w-1,h-1,0,h-1,black). draw_image(tx,ty,canvas); else canvas = CImg<unsigned char>(w,h,1,3). draw_rectangle(0,0,w-1,h-1,gray). draw_line(0,0,w-1,0,white).draw_line(0,h-1,0,0,white). draw_line(w-1,0,w-1,h-1,black).draw_line(w-1,h-1,0,h-1,black); if (logo._data) canvas.draw_image(lx,ly,logo); unsigned int xbuttons[6] = { 0 }; cimglist_for(buttons,lll) { xbuttons[lll] = bx+(bw+12)*lll; canvas.draw_image(xbuttons[lll],by,buttons[lll]); } // Open window and enter events loop CImgDisplay disp(canvas,title?title:" ",0,false,is_centered?true:false); if (is_centered) disp.move((CImgDisplay::screen_width() - disp.width())/2, (CImgDisplay::screen_height() - disp.height())/2); bool stopflag = false, refresh = false; int oselected = -1, oclicked = -1, selected = -1, clicked = -1; while (!disp.is_closed() && !stopflag) { if (refresh) { if (clicked>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[clicked],by,cbuttons[clicked]).display(disp); else { if (selected>=0) CImg<unsigned char>(canvas).draw_image(xbuttons[selected],by,sbuttons[selected]).display(disp); else canvas.display(disp); } refresh = false; } disp.wait(15); if (disp.is_resized()) disp.resize(disp,false); if (disp.button()&1) { oclicked = clicked; clicked = -1; cimglist_for(buttons,l) if (disp.mouse_y()>=(int)by && disp.mouse_y()<(int)(by+bh) && disp.mouse_x()>=(int)xbuttons[l] && disp.mouse_x()<(int)(xbuttons[l]+bw)) { clicked = selected = l; refresh = true; } if (clicked!=oclicked) refresh = true; } else if (clicked>=0) stopflag = true; if (disp.key()) { oselected = selected; switch (disp.key()) { case cimg::keyESC : selected=-1; stopflag=true; break; case cimg::keyENTER : if (selected<0) selected = 0; stopflag = true; break; case cimg::keyTAB : case cimg::keyARROWRIGHT : case cimg::keyARROWDOWN : selected = (selected+1)%buttons._width; break; case cimg::keyARROWLEFT : case cimg::keyARROWUP : selected = (selected+buttons._width-1)%buttons._width; break; } disp.set_key(); if (selected!=oselected) refresh = true; } } if (!disp) selected = -1; return selected; #endif } //! Display a simple dialog box, and wait for the user's response \specialization. inline int dialog(const char *const title, const char *const msg, const char *const button1_label, const char *const button2_label, const char *const button3_label, const char *const button4_label, const char *const button5_label, const char *const button6_label, const bool is_centered) { return dialog(title,msg,button1_label,button2_label,button3_label,button4_label,button5_label,button6_label, CImg<unsigned char>::_logo40x38(),is_centered); } //! Evaluate math expression. /** \param expression C-string describing the formula to evaluate. \param x Value of the pre-defined variable \c x. \param y Value of the pre-defined variable \c y. \param z Value of the pre-defined variable \c z. \param c Value of the pre-defined variable \c c. \return Result of the formula evaluation. \note Set \c expression to \c 0 to keep evaluating the last specified \c expression. \par Example \code const double res1 = cimg::eval("cos(x)^2+sin(y)^2",2,2), // will return '1'. res2 = cimg::eval(0,1,1); // will return '1' too. \endcode **/ inline double eval(const char *const expression, const double x, const double y, const double z, const double c) { static const CImg<float> empty; return empty.eval(expression,x,y,z,c); } // End of cimg:: namespace } // End of cimg_library:: namespace } //! Short alias name. namespace cil = cimg_library_suffixed; #ifdef _cimg_redefine_False #define False 0 #endif #ifdef _cimg_redefine_True #define True 1 #endif #ifdef _cimg_redefine_None #define None 0 #endif #ifdef _cimg_redefine_min #define min(a,b) (((a)<(b))?(a):(b)) #endif #ifdef _cimg_redefine_max #define max(a,b) (((a)>(b))?(a):(b)) #endif #ifdef _cimg_redefine_PI #define PI 3.141592653589793238462643383 #endif #endif // Local Variables: // mode: c++ // End:
DRACC_OMP_039_Vector_add_Mult_nowait_yes.c
/* Vector addition then scalar multiplication with no implicit barrier in between. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define N 100 #define C 512 int a; int b[C]; int c[C]; int temp[C]; int init(){ for(int i=0; i<C; i++){ b[i]=0; c[i]=2; temp[i]=0; } a=2; return 0; } int add_Mult(){ #pragma omp target map(tofrom:b[0:C]) map(to:c[0:C],temp[0:C],a) device(0) #pragma omp parallel { for(int i=0; i<N; i++){ #pragma omp for nowait for(int i=0; i<C; i++){ temp[i] = b[i] + c[i]; } #pragma omp for nowait for(int i=C; i>0; i--){ b[i] = temp[i] * a; } } } return 0; } int check(){ bool test = false; int val = 0; for(int i=0; i<N; i++){ val = val + 2; val = val * 2; } for(int i=0; i<C; i++){ if(b[i]!=val){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ init(); add_Mult(); check(); return 0; }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 4; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
ExampleReservoirs_Shared.h
/** * grove: ExampleReservoirs_Shared.h * Copyright (c) Torr Vision Group, University of Oxford, 2017. All rights reserved. */ #ifndef H_GROVE_EXAMPLERESERVOIRS_SHARED #define H_GROVE_EXAMPLERESERVOIRS_SHARED #include <ORUtils/PlatformIndependence.h> #define ALWAYS_ADD_EXAMPLES 0 namespace grove { /** * \brief Attempts to add an example to some reservoirs. * * If the example is valid, we attempt to add it to each specified reservoir. If a * reservoir is not full, then the example is added. Otherwise, if ALWAYS_ADD_EXAMPLES * is 1, a randomly-selected existing example is discarded and replaced by the current * example. If ALWAYS_ADD_EXAMPLES is 0, then an additional random decision is made as * to *whether* to replace an existing example. * * \param example The example to attempt to add to the reservoirs. * \param reservoirIndices The indices of the reservoirs to which to attempt to add the example. * \param reservoirIndexCount The number of reservoirs to which to attempt to add the example. * \param reservoirs The example reservoirs: an image in which each row allows the storage of up to reservoirCapacity examples. * \param reservoirSizes The current size of each reservoir. * \param reservoirAddCalls The number of times the insertion of an example has been attempted for each reservoir. * \param reservoirCapacity The capacity (maximum size) of each reservoir. * \param randomGenerator A random number generator. */ template <typename ExampleType, typename RNGType> _CPU_AND_GPU_CODE_TEMPLATE_ inline void add_example_to_reservoirs(const ExampleType& example, const int *reservoirIndices, uint32_t reservoirIndexCount, ExampleType *reservoirs, int *reservoirSizes, int *reservoirAddCalls, uint32_t reservoirCapacity, RNGType& randomGenerator) { // If the example is invalid, early out. if(!example.valid) return; // Try to add the example to each specified reservoir. for(uint32_t i = 0; i < reservoirIndexCount; ++i) { // The reservoir index (this corresponds to a row in the reservoirs image). const int reservoirIdx = reservoirIndices[i]; // The raster index (in the reservoirs image) of the first example in the reservoir. const int reservoirStartIdx = reservoirIdx * reservoirCapacity; // Get the total number of add calls that have ever been made for the current reservoir, and increment it for next time. uint32_t oldAddCallsCount = 0; #ifdef __CUDACC__ oldAddCallsCount = atomicAdd(&reservoirAddCalls[reservoirIdx], 1); #else #ifdef WITH_OPENMP #pragma omp atomic capture #endif oldAddCallsCount = reservoirAddCalls[reservoirIdx]++; #endif // If the old total number of add calls is less than the reservoir's capacity, then we can immediately add the example. // Otherwise, we need to decide whether or not to replace an existing example with this one. if(oldAddCallsCount < reservoirCapacity) { // Store the example in the reservoir. reservoirs[reservoirStartIdx + oldAddCallsCount] = example; // Increment the reservoir's size. Note that it is not strictly necessary to // maintain the reservoir sizes separately, since we can obtain the same // information from reservoirAddCalls by clamping the values to the reservoir // capacity, but writing it this way is much clearer and the cost in efficiency // is limited in practice. #ifdef __CUDACC__ atomicAdd(&reservoirSizes[reservoirIdx], 1); #else #ifdef WITH_OPENMP #pragma omp atomic #endif ++reservoirSizes[reservoirIdx]; #endif } else { #if ALWAYS_ADD_EXAMPLES // Generate a random offset that will always result in an example being evicted from the reservoir. const uint32_t randomOffset = randomGenerator.generate_int_from_uniform(0, reservoirCapacity - 1); #else // Generate a random offset that may or may not result in an example being evicted from the reservoir. const uint32_t randomOffset = randomGenerator.generate_int_from_uniform(0, oldAddCallsCount - 1); #endif // If the random offset corresponds to an example in the reservoir, replace that with the new example. if(randomOffset < reservoirCapacity) { reservoirs[reservoirStartIdx + randomOffset] = example; } } } } } #endif
heap_mult_generic.h
#ifndef MASKED_SPGEMM_HEAP_MULT_GENERIC_H #define MASKED_SPGEMM_HEAP_MULT_GENERIC_H #include <algorithm> #include "CSR.h" // TODO: move to a separate file namespace tmp { /** ** Count flop of SpGEMM between A and B in CSR format **/ template<typename IT, typename NT> long long int getFlop(const CSR<IT, NT> &A, const CSR<IT, NT> &B, IT *maxnnzc) { long long int flop = 0; // total flop (multiplication) needed to generate C #pragma omp parallel for reduction(+:flop) for (IT i = 0; i < A.rows; ++i) { long long int locmax = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { IT inner = A.colids[j]; IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; locmax += npins; } maxnnzc[i] = locmax; flop += locmax; } return flop * 2; } } namespace heap { template<class RandomAccessIterator, class SizeT> [[gnu::always_inline]] inline void make(RandomAccessIterator heap, SizeT size) { std::make_heap(heap, heap + size); } template<class RandomAccessIterator, class SizeT> [[gnu::always_inline]] inline void pop(RandomAccessIterator heap, SizeT &size) { std::pop_heap(heap, heap + size); size--; } template<class RandomAccessIterator, class SizeT> [[gnu::always_inline]] inline void sinkRoot(RandomAccessIterator heap, SizeT size) { std::pop_heap(heap, heap + size); std::push_heap(heap, heap + size); } } namespace rowAlg { struct HeapBase { const static bool masked = false; template<class IT, class NT> static IT estimateResultSize(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { return std::accumulate(maxnnzc + rowBeginIdx, maxnnzc + rowEndIdx, 0); } template<class IT, class NT> static HeapEntry<IT, void> *allocateAuxiliaryMemory(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { IT threadHeapSize = 0; for (IT i = rowBeginIdx; i < rowEndIdx; ++i) { IT rownnz = A.rowptr[i + 1] - A.rowptr[i]; if (rownnz > threadHeapSize) { threadHeapSize = rownnz; } } return my_malloc<HeapEntry<IT, void>>(threadHeapSize); }; }; struct BasicHeap : HeapBase { template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, HeapEntry<IT, void> *mergeheap, IT &threadNvals) { // Make initial heap for the row IT currRowNvals = 0; IT hsize = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { // For all the nonzeros of the ith column IT inner = A.colids[j]; // get the col id of A (or row id of B) IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; // get the number of nzs in B's row if (npins == 0) { continue; } mergeheap[hsize].loc = B.rowptr[inner]; mergeheap[hsize].runr = j; // the pointer to A.colid's is the run-rank mergeheap[hsize++].key = B.colids[B.rowptr[inner]]; // B's first colid is the first key } heap::make(mergeheap, hsize); // Traverse the heaps while (hsize > 0) { auto &hentry = mergeheap[0]; NT value = multop(A.values[hentry.runr], B.values[hentry.loc]); // Use short circuiting if ((currRowNvals > 0) && *prevColIdC == hentry.key) { *prevValueC = addop(value, *prevValueC); } else { *(++prevValueC) = value; *(++prevColIdC) = hentry.key; currRowNvals++; } IT inner = A.colids[hentry.runr]; // If still unused nonzeros exists in A(:,colind), insert the next nonzero to the heap if (++hentry.loc < B.rowptr[inner + 1]) { hentry.key = B.colids[hentry.loc]; heap::sinkRoot(mergeheap, hsize); } else { heap::pop(mergeheap, hsize); } } rowNvals[i] = currRowNvals; threadNvals += currRowNvals; } }; template<size_t threshold> struct HeapLinear : HeapBase { template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, HeapEntry<IT, void> *mergeheap, IT &threadNvals) { // Make initial heap for the row IT currRowNvals = 0; IT hsize = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { // For all the nonzeros of the ith column IT inner = A.colids[j]; // get the col id of A (or row id of B) IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; // get the number of nzs in B's row if (npins == 0) { continue; } mergeheap[hsize].loc = B.rowptr[inner]; mergeheap[hsize].runr = j; // the pointer to A.colid's is the run-rank mergeheap[hsize++].key = B.colids[B.rowptr[inner]]; // B's first colid is the first key } if (hsize > threshold) { heap::make(mergeheap, hsize); } // Traverse the heaps while (hsize > 0) { IT idx = hsize > threshold ? 0 : std::max_element(mergeheap, mergeheap + hsize) - mergeheap; auto &hentry = mergeheap[idx]; NT value = multop(A.values[hentry.runr], B.values[hentry.loc]); // Use short circuiting if ((currRowNvals > 0) && *prevColIdC == hentry.key) { *prevValueC = addop(value, *prevValueC); } else { *(++prevValueC) = value; *(++prevColIdC) = hentry.key; currRowNvals++; } IT inner = A.colids[hentry.runr]; // If still unused nonzeros exists in A(:,colind), insert the next nonzero to the heap if (++hentry.loc < B.rowptr[inner + 1]) { hentry.key = B.colids[hentry.loc]; if (hsize > threshold) { heap::sinkRoot(mergeheap, hsize); } } else { if (hsize > threshold) { heap::pop(mergeheap, hsize); } else { *(mergeheap + idx) = *(mergeheap + --hsize); } } } rowNvals[i] = currRowNvals; threadNvals += currRowNvals; } }; struct MaskedHeapBase { const static bool masked = true; template<class IT, class NT> static IT estimateResultSize(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { IT size = 0; for (IT row = rowBeginIdx; row < rowEndIdx; row++) { size += std::min(maxnnzc[row], M.rowptr[row + 1] - M.rowptr[row]); } return size; } template<class IT, class NT> static HeapEntry<IT, void> *allocateAuxiliaryMemory(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { IT threadHeapSize = 0; for (IT i = rowBeginIdx; i < rowEndIdx; ++i) { IT rownnz = A.rowptr[i + 1] - A.rowptr[i]; if (rownnz > threadHeapSize) { threadHeapSize = rownnz; } } return my_malloc<HeapEntry<IT, void>>(threadHeapSize); }; }; struct MaskedHeap_v0 : MaskedHeapBase { template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, HeapEntry<IT, void> *mergeheap, IT &threadNvals) { IT maskIdx = M.rowptr[i]; IT maskEnd = M.rowptr[i + 1]; // Make initial heap for the row IT currRowNvals = 0; IT hsize = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { // For all the nonzeros of the ith column IT inner = A.colids[j]; // get the col id of A (or row id of B) IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; // get the number of nzs in B's row if (npins == 0) { continue; } mergeheap[hsize].loc = B.rowptr[inner]; mergeheap[hsize].runr = j; // the pointer to A.colid's is the run-rank mergeheap[hsize++].key = B.colids[B.rowptr[inner]]; // B's first colid is the first key } heap::make(mergeheap, hsize); // Traverse the heaps while (hsize > 0) { auto &hentry = mergeheap[0]; while (maskIdx < maskEnd && hentry.key > M.colids[maskIdx]) { ++maskIdx; } if (maskIdx >= maskEnd) { break; } if (hentry.key == M.colids[maskIdx]) { NT value = multop(A.values[hentry.runr], B.values[hentry.loc]); // Use short circuiting if ((currRowNvals > 0) && *prevColIdC == hentry.key) { *prevValueC = addop(value, *prevValueC); } else { *(++prevValueC) = value; *(++prevColIdC) = hentry.key; currRowNvals++; } } IT inner = A.colids[hentry.runr]; // If still unused nonzeros exists in A(:,colind), insert the next nonzero to the heap if (++hentry.loc < B.rowptr[inner + 1]) { hentry.key = B.colids[hentry.loc]; heap::sinkRoot(mergeheap, hsize); } else { heap::pop(mergeheap, hsize); } } rowNvals[i] = currRowNvals; threadNvals += currRowNvals; } }; struct MaskedHeap_v1 : MaskedHeapBase { template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, HeapEntry<IT, void> *mergeheap, IT &threadNvals) { IT maskIdx = M.rowptr[i]; IT maskEnd = M.rowptr[i + 1]; if (maskIdx == maskEnd) { return; } // Make initial heap for the row IT currRowNvals = 0; IT hsize = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { // For all the nonzeros of the ith column IT inner = A.colids[j]; // get the col id of A (or row id of B) IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; // get the number of nzs in B's row if (npins == 0) { continue; } mergeheap[hsize].loc = B.rowptr[inner]; mergeheap[hsize].runr = j; // the pointer to A.colid's is the run-rank mergeheap[hsize].key = B.colids[B.rowptr[inner]]; // B's first colid is the first key while (mergeheap[hsize].key < M.colids[maskIdx] && (mergeheap[hsize].loc + 1 < B.rowptr[inner + 1])) { mergeheap[hsize].loc++; mergeheap[hsize].key = B.colids[mergeheap[hsize].loc]; } // If we did not reach the end of B's row, add it to the heap if (mergeheap[hsize].loc < B.rowptr[inner + 1]) { hsize++; } } heap::make(mergeheap, hsize); // Traverse the heaps while (hsize > 0) { auto &hentry = mergeheap[0]; while (maskIdx < maskEnd && hentry.key > M.colids[maskIdx]) { ++maskIdx; } if (maskIdx >= maskEnd) { break; } if (hentry.key == M.colids[maskIdx]) { NT value = multop(A.values[hentry.runr], B.values[hentry.loc]); // Use short circuiting if ((currRowNvals > 0) && *prevColIdC == hentry.key) { *prevValueC = addop(value, *prevValueC); } else { *(++prevValueC) = value; *(++prevColIdC) = hentry.key; currRowNvals++; } } IT inner = A.colids[hentry.runr]; // Before pushing the entry back to the queue, remove elements that are < than current mask element while (++hentry.loc < B.rowptr[inner + 1]) { hentry.key = B.colids[hentry.loc]; if (hentry.key >= M.colids[maskIdx]) { break; } } if (hentry.loc < B.rowptr[inner + 1]) { heap::sinkRoot(mergeheap, hsize); } else { heap::pop(mergeheap, hsize); } } rowNvals[i] = currRowNvals; threadNvals += currRowNvals; } }; struct MaskedHeap_v2 : MaskedHeapBase { template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, HeapEntry<IT, void> *mergeheap, IT &threadNvals) { IT maskIdx = M.rowptr[i]; IT maskEnd = M.rowptr[i + 1]; if (maskIdx == maskEnd) { return; } // Make initial heap for the row IT currRowNvals = 0; IT hsize = 0; for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; ++j) { // For all the nonzeros of the ith column IT inner = A.colids[j]; // get the col id of A (or row id of B) IT npins = B.rowptr[inner + 1] - B.rowptr[inner]; // get the number of nzs in B's row if (npins == 0) { continue; } mergeheap[hsize].loc = B.rowptr[inner]; mergeheap[hsize].runr = j; // the pointer to A.colid's is the run-rank mergeheap[hsize].key = B.colids[B.rowptr[inner]]; // B's first colid is the first key // Find the first match in the intersection of the mask column and the A column IT maskIdxCopy = maskIdx; while (true) { if (mergeheap[hsize].key < M.colids[maskIdx]) { if (++mergeheap[hsize].loc < B.rowptr[inner + 1]) { mergeheap[hsize].key = B.colids[mergeheap[hsize].loc]; } else { break; } } else if (mergeheap[hsize].key > M.colids[maskIdx]) { if (++maskIdx == maskEnd) { break; } } else { hsize++; break; } } maskIdx = maskIdxCopy; } heap::make(mergeheap, hsize); // Traverse the heaps while (hsize > 0) { auto &hentry = mergeheap[0]; while (maskIdx < maskEnd && hentry.key > M.colids[maskIdx]) { ++maskIdx; } if (maskIdx >= maskEnd) { break; } if (hentry.key == M.colids[maskIdx]) { NT value = multop(A.values[hentry.runr], B.values[hentry.loc]); // Use short circuiting if ((currRowNvals > 0) && *prevColIdC == hentry.key) { *prevValueC = addop(value, *prevValueC); } else { *(++prevValueC) = value; *(++prevColIdC) = hentry.key; currRowNvals++; } } IT inner = A.colids[hentry.runr]; // Check if we are done with the current row from B, and if we are not move to the next element. if (++hentry.loc >= B.rowptr[inner + 1]) { heap::pop(mergeheap, hsize); continue; } hentry.key = B.colids[hentry.loc]; // Find the first match in the intersection of // the mask column (starting with maskIdx) and the A column (starting with hentry.loc) IT maskIdxCopy = maskIdx; while (true) { if (hentry.key < M.colids[maskIdx]) { if (++hentry.loc < B.rowptr[inner + 1]) { hentry.key = B.colids[hentry.loc]; } else { heap::pop(mergeheap, hsize); break; } } else if (hentry.key > M.colids[maskIdx]) { if (++maskIdx == maskEnd) { heap::pop(mergeheap, hsize); break; } } else { // put the merge heap in the valid state again heap::sinkRoot(mergeheap, hsize); break; } } maskIdx = maskIdxCopy; } rowNvals[i] = currRowNvals; threadNvals += currRowNvals; } }; struct MCABase { const static bool masked = true; template<class IT, class NT> static IT estimateResultSize(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { IT size = 0; for (IT row = rowBeginIdx; row < rowEndIdx; row++) { size += std::min(maxnnzc[row], M.rowptr[row + 1] - M.rowptr[row]); } return size; } template<class IT, class NT> static bool *allocateAuxiliaryMemory(IT rowBeginIdx, IT rowEndIdx, IT *maxnnzc, const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M) { IT flagsSize = 0; for (IT i = rowBeginIdx; i < rowEndIdx; ++i) { IT maxMRow = M.rowptr[i + 1] - M.rowptr[i]; if (maxMRow > flagsSize) { flagsSize = maxMRow; } } return my_malloc<bool>(flagsSize); }; }; struct MCA_v1 : MCABase { const static bool masked = true; template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, bool *flags, IT &threadNvals) { IT maskBegin = M.rowptr[i]; const IT maskEnd = M.rowptr[i + 1]; const IT maskSize = maskEnd - maskBegin; prevColIdC++; prevValueC++; std::fill(flags, flags + maskSize, false); // Iterate though nonzeros in the A's current row for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; j++) { const IT inner = A.colids[j]; IT loc = B.rowptr[inner]; IT key = A.colids[loc]; if (loc == B.rowptr[inner + 1]) { continue; } IT maskIdx = maskBegin; // Find the intersection between the mask's row and the A's row while (true) { if (key < M.colids[maskIdx]) { if (++loc < B.rowptr[inner + 1]) { key = B.colids[loc]; } else { break; } } else if (key > M.colids[maskIdx]) { if (++maskIdx == maskEnd) { break; } } else { // colid is found in both arrays const auto idx = maskIdx - maskBegin; const NT value = multop(A.values[j], B.values[loc]); if (!flags[idx]) { prevValueC[idx] = value; flags[idx] = true; } else { prevValueC[idx] = addop(prevValueC[idx], value); } if (++loc < B.rowptr[inner + 1]) { key = B.colids[loc]; } else { break; } if (++maskIdx == maskEnd) { break; } } } } /* Remove empty values the destination arrays and set row IDs */ size_t dst = 0; for (size_t src = 0; src < maskSize; src++) { if (flags[src]) { prevColIdC[dst] = M.colids[maskBegin + src]; prevValueC[dst] = prevValueC[src]; dst++; } } prevColIdC += dst - 1; prevValueC += dst - 1; rowNvals[i] = dst; threadNvals += dst; } }; struct MCA_v2 : MCABase { const static bool masked = true; template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, bool *flags, IT &threadNvals) { IT maskBegin = M.rowptr[i]; const IT maskEnd = M.rowptr[i + 1]; const IT maskSize = maskEnd - maskBegin; // Since prev***C point to the previous element, increment them prevColIdC++; prevValueC++; std::fill(flags, flags + maskSize, false); // Iterate though nonzeros in the A's current row for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; j++) { const IT inner = A.colids[j]; IT loc = B.rowptr[inner]; IT key = A.colids[loc]; if (loc == B.rowptr[inner + 1]) { continue; } // Find the intersection between the mask's row and the A's row for (IT maskIdx = maskBegin; maskIdx < maskEnd; maskIdx++) { while (key < M.colids[maskIdx]) { if (++loc < B.rowptr[inner + 1]) { key = B.colids[loc]; } else { goto outerLoopBreak; } } if (key == M.colids[maskIdx]) { // colid is found in both arrays const auto idx = maskIdx - maskBegin; const NT value = multop(A.values[j], B.values[loc]); if (!flags[idx]) { prevValueC[idx] = value; flags[idx] = true; } else { prevValueC[idx] = addop(prevValueC[idx], value); } if (++loc < B.rowptr[inner + 1]) { key = B.colids[loc]; } else { break; } } } outerLoopBreak: continue; } /* Remove empty values the destination arrays and set row IDs */ size_t dst = 0; for (size_t src = 0; src < maskSize; src++) { if (flags[src]) { prevColIdC[dst] = M.colids[maskBegin + src]; prevValueC[dst] = prevValueC[src]; dst++; } } prevColIdC += dst - 1; prevValueC += dst - 1; rowNvals[i] = dst; threadNvals += dst; } }; struct MCA_v3 : MCABase { const static bool masked = true; template<typename IT, typename NT, typename MultiplyOperation, typename AddOperation> [[gnu::always_inline]] static void row(const CSR<IT, NT> &A, const CSR<IT, NT> &B, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, IT i, IT *rowNvals, IT *&prevColIdC, NT *&prevValueC, bool *flags, IT &threadNvals) { const auto maskBegin = &M.colids[M.rowptr[i]]; const auto maskEnd = &M.colids[M.rowptr[i + 1]]; const auto maskSize = maskEnd - maskBegin; prevColIdC++; prevValueC++; std::fill(flags, flags + maskSize, false); // Iterate though nonzeros in the A's current row for (IT j = A.rowptr[i]; j < A.rowptr[i + 1]; j++) { const IT inner = A.colids[j]; auto colIdsIt = &B.colids[B.rowptr[inner]]; const auto colIdsBegin = &B.colids[B.rowptr[inner]]; const auto colIdsEnd = &B.colids[B.rowptr[inner + 1]]; auto maskIt = maskBegin; if (colIdsIt == colIdsEnd) { continue; } // Find the intersection between the mask's row and the A's row while (true) { if (*colIdsIt < *maskIt) { if (++colIdsIt == colIdsEnd) { break; } } else if (*colIdsIt > *maskIt) { if (++maskIt == maskEnd) { break; } } else { // colid is found in both arrays const auto idx = maskIt - maskBegin; const NT value = multop(A.values[j], B.values[B.rowptr[inner] + colIdsIt - colIdsBegin]); if (!flags[idx]) { prevValueC[idx] = value; flags[idx] = true; } else { prevValueC[idx] = addop(prevValueC[idx], value); } if (++colIdsIt >= colIdsEnd) { break; } if (++maskIt == maskEnd) { break; } } } } /* Remove empty values the destination arrays and set row IDs */ size_t dst = 0; for (size_t src = 0; src < maskSize; src++) { if (flags[src]) { prevColIdC[dst] = maskBegin[src]; prevValueC[dst] = prevValueC[src]; dst++; } } prevColIdC += dst - 1; prevValueC += dst - 1; rowNvals[i] = dst; threadNvals += dst; } }; } template<bool masked, class RowAlgorithm, typename IT, typename NT, typename MultiplyOperation, typename AddOperation> void HeapSpGEMMImpl(const CSR<IT, NT> &A, const CSR<IT, NT> &B, CSR<IT, NT> &C, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, unsigned numThreads) { static_assert(masked == RowAlgorithm::masked || masked, "Row algorithm does not support mask."); static_assert(masked == RowAlgorithm::masked || !masked, "Row algorithm is used for masked computation."); if (numThreads == 0) { #pragma omp parallel #pragma omp single numThreads = omp_get_num_threads(); } if (!C.isEmpty()) { C.make_empty(); } C.rows = A.rows; C.cols = B.cols; // Load-balancing Thread Scheduling IT *maxnnzc = my_malloc<IT>(A.rows); long long int flops = tmp::getFlop(A, B, maxnnzc) / 2; IT flopsPerThread = flops / numThreads; // amount of work that will be assigned to each thread IT *rowStart = my_malloc<IT>(A.rows); //start index in the global array for storing ith column of C IT *rowNvals = my_malloc<IT>(A.rows); // number of nonzeros in each each column in C rowStart[0] = 0; // Global space used to store result IT *threadsNvals = my_malloc<IT>(numThreads); // Parallelized version scan(maxnnzc, rowStart, A.rows); // ************************ Numeric Phase ************************************* #pragma omp parallel num_threads(numThreads) { int thisThread = omp_get_thread_num(); // @formatter:off IT rowBegin = thisThread != 0 ? (lower_bound(rowStart, rowStart + A.rows, flopsPerThread * thisThread)) - rowStart : 0; IT rowEnd = thisThread != numThreads - 1 ? (lower_bound(rowStart, rowStart + A.rows, flopsPerThread * (thisThread + 1))) - rowStart : A.rows; // @formatter:on IT localsum = RowAlgorithm::estimateResultSize(rowBegin, rowEnd, maxnnzc, A, B, M); // We need +1 even though the first element of the array is never accessed. // However, the first element may be prefetched so we have to allocate it together with the rest of the array. IT *colIdsLocalMem = my_malloc<IT>(localsum + 1); NT *valuesLocalMem = my_malloc<NT>(localsum + 1); IT *prevColIdC = colIdsLocalMem; NT *prevValueC = valuesLocalMem; auto auxMemory = RowAlgorithm::allocateAuxiliaryMemory(rowBegin, rowEnd, maxnnzc, A, B, M); IT threadNvals = 0; // Iterate through all rows in A for (IT i = rowBegin; i < rowEnd; ++i) { RowAlgorithm::row(A, B, M, multop, addop, i, rowNvals, prevColIdC, prevValueC, auxMemory, threadNvals); } threadsNvals[thisThread] = threadNvals; my_free(auxMemory); #pragma omp barrier #pragma omp master { C.rowptr = my_malloc<IT>(C.rows + 1); C.rowptr[0] = 0; C.nnz = std::accumulate(threadsNvals, threadsNvals + numThreads, IT(0));; C.colids = my_malloc<IT>(C.nnz); C.values = my_malloc<NT>(C.nnz); } IT rowPtrOffset = std::accumulate(threadsNvals, threadsNvals + thisThread, IT(0)); #pragma omp barrier // set rowptr in C for local rows for (IT i = rowBegin; i < rowEnd; ++i) { C.rowptr[i] = rowPtrOffset; rowPtrOffset += rowNvals[i]; } if (thisThread == numThreads - 1) { C.rowptr[C.rows] = rowPtrOffset; } // copy local values to C copy(colIdsLocalMem + 1, colIdsLocalMem + threadNvals + 1, C.colids + C.rowptr[rowBegin]); copy(valuesLocalMem + 1, valuesLocalMem + threadNvals + 1, C.values + C.rowptr[rowBegin]); my_free<IT>(colIdsLocalMem); my_free<NT>(valuesLocalMem); } my_free<IT>(maxnnzc); my_free<IT>(rowStart); my_free<IT>(rowNvals); } template<class RowAlgorithm, typename IT, typename NT, typename MultiplyOperation, typename AddOperation> void HeapSpGEMM(const CSR<IT, NT> &A, const CSR<IT, NT> &B, CSR<IT, NT> &C, MultiplyOperation multop, AddOperation addop, unsigned numThreads = 0) { HeapSpGEMMImpl<false, RowAlgorithm>(A, B, C, CSR<IT, NT>{}, multop, addop, numThreads); } template<class RowAlgorithm, typename IT, typename NT, typename MultiplyOperation, typename AddOperation> void HeapSpGEMM(const CSR<IT, NT> &A, const CSR<IT, NT> &B, CSR<IT, NT> &C, const CSR<IT, NT> &M, MultiplyOperation multop, AddOperation addop, unsigned numThreads = 0) { HeapSpGEMMImpl<true, RowAlgorithm>(A, B, C, M, multop, addop, numThreads); } #endif //MASKED_SPGEMM_HEAP_MULT_GENERIC_H
ParallelHashMap.h
/** * @file ParallelHashMap.h * @brief A thread-safe hash map supporting insertion and lookup operations * @details The parallel hash map is built on top of a fixed-sized hash map * object and features OpenMP concurrency structures. The underlying * fixed-sized hash map handles collisions with chaining. * @date June 6, 2015 * @author Geoffrey Gunow, MIT, Course 22 ([email protected]) */ #ifndef __PARALLEL_HASH_MAP__ #define __PARALLEL_HASH_MAP__ #include<iostream> #include<stdexcept> #include<functional> #ifdef OPENMP #include<omp.h> #endif /** * @class FixedHashMap ParallelHashMap.h "src/ParallelHashMap.h" * @brief A fixed-size hash map supporting insertion and lookup operations * @details The FixedHashMap class supports insertion and lookup operations * but not deletion as deletion is not needed in the OpenMOC application. * This hash table uses chaining for collisions and does not incorporate * concurrency objects except for tracking the number of entries in the * table for which an atomic increment is used. This hash table is not * thread safe but is used as a building block for the ParallelHashMap * class. This table guarantees O(1) insertions and lookups on average. */ template <class K, class V> class FixedHashMap { struct node { node(K k_in, V v_in) : next(NULL), key(k_in), value(v_in){} K key; V value; node *next; }; private: size_t _M; /* table size */ size_t _N; /* number of elements present in table */ node ** _buckets; /* buckets of values stored in nodes */ public: FixedHashMap(size_t M = 64); virtual ~FixedHashMap(); bool contains(K key); V& at(K key); void insert(K key, V value); int insert_and_get_count(K key, V value); size_t size(); size_t bucket_count(); K* keys(); V* values(); void clear(); void print_buckets(); }; /** * @class ParallelHashMap ParallelHashMap.h "src/ParallelHashMap.h" * @brief A thread-safe hash map supporting insertion and lookup operations * @details The ParallelHashMap class is built on top of the FixedHashMap * class, supporting insertion and lookup operations but not deletion as * deletion is not needed in the OpenMOC application. This hash table uses * chaining for collisions, as defined in FixedHashMap. It offers lock * free lookups in O(1) time on average and fine-grained locking for * insertions in O(1) time on average as well. Resizing is conducted * periodically during inserts, although the starting table size can be * chosen to limit the number of resizing operations. */ template <class K, class V> class ParallelHashMap { /* padded pointer to hash table to avoid false sharing */ struct paddedPointer { volatile long pad_L1; volatile long pad_L2; volatile long pad_L3; volatile long pad_L4; volatile long pad_L5; volatile long pad_L7; volatile long pad_L8; FixedHashMap<K,V>* volatile value; volatile long pad_R1; volatile long pad_R2; volatile long pad_R3; volatile long pad_R4; volatile long pad_R5; volatile long pad_R6; volatile long pad_R7; volatile long pad_R8; }; private: FixedHashMap<K,V> *_table; paddedPointer *_announce; size_t _num_threads; size_t _N; #ifdef OPENMP omp_lock_t * _locks; size_t _num_locks; #endif void resize(); public: ParallelHashMap(size_t M = 64, size_t L = 64); virtual ~ParallelHashMap(); bool contains(K key); V& at(K key); void insert(K key, V value); int insert_and_get_count(K key, V value); size_t size(); size_t bucket_count(); size_t num_locks(); K* keys(); V* values(); void clear(); void print_buckets(); }; /** * @brief Constructor initializes fixed-size table of buckets filled with empty * linked lists. * @details The constructor initializes a fixed-size hash map with the size * as an input parameter. If no size is given the default size (64) * is used. Buckets are filled with empty linked lists presented as * NULL pointers. * @param M size of fixed hash map */ template <class K, class V> FixedHashMap<K,V>::FixedHashMap(size_t M) { /* ensure M is a power of 2 */ if ((M & (M-1)) != 0) { /* if not, round up to nearest power of 2 */ M--; for (size_t i = 1; i < 8 * sizeof(size_t); i*=2) M |= M >> i; M++; } /* allocate table */ _M = M; _N = 0; _buckets = new node*[_M](); } /** * @brief Destructor deletes all nodes in the linked lists associated with each * bucket in the fixed-size table and their pointers. */ template <class K, class V> FixedHashMap<K,V>::~FixedHashMap() { /* for each bucket, scan through linked list and delete all nodes */ for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { node *next_node = iter_node->next; delete iter_node; iter_node = next_node; } } /* delete all buckets (now pointers to empty linked lists) */ delete[] _buckets; } /** * @brief Determine whether the fixed-size table contains a given key * @details The linked list in the bucket associated with the key is searched * to determine whether the key is present. * @param key key to be searched * @return boolean value referring to whether the key is contained in the map */ template <class K, class V> bool FixedHashMap<K,V>::contains(K key) { /* get hash into table assuming M is a power of 2, using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* search corresponding bucket for key */ node *iter_node = _buckets[key_hash]; while (iter_node != NULL) { if (iter_node->key == key) return true; else iter_node = iter_node->next; } return false; } /** * @brief Determine the value associated with a given key in the fixed-size * table. * @details The linked list in the bucket associated with the key is searched * and once the key is found, the corresponding value is returned. * An exception is thrown if the key is not present in the map. * @param key key whose corresponding value is desired * @return value associated with the given key */ template <class K, class V> V& FixedHashMap<K,V>::at(K key) { /* get hash into table assuming M is a power of 2, using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* search bucket for key and return the corresponding value if found */ node *iter_node = _buckets[key_hash]; while (iter_node != NULL) if (iter_node->key == key) return iter_node->value; else iter_node = iter_node->next; /* after the bucket has been completely searched without finding the key, throw an exception */ throw std::out_of_range("Key not present in map"); } /** * @brief Inserts a key/value pair into the fixed-size table. * @details The specified key value pair is inserted into the fixed-size table. * If the key already exists in the table, the pair is not inserted * and the function returns. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted */ template <class K, class V> void FixedHashMap<K,V>::insert(K key, V value) { /* get hash into table using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* check to see if key already exists in map */ if (contains(key)) return; /* create new node */ node *new_node = new node(key, value); /* find where to place element in linked list */ node **iter_node = &_buckets[key_hash]; while (*iter_node != NULL) iter_node = &(*iter_node)->next; /* place element in linked list */ *iter_node = new_node; /* increment counter */ #pragma omp atomic _N++; } /** * @brief Inserts a key/value pair into the fixed-size table and returns the * order number with which it was inserted. * @details The specified key value pair is inserted into the fixed-size table. * If the key already exists in the table, the pair is not inserted * and the function returns -1. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted * @return order number in which key/value pair was inserted, -1 is returned if * key was already present in map. */ template <class K, class V> int FixedHashMap<K,V>::insert_and_get_count(K key, V value) { /* get hash into table using fast modulus */ size_t key_hash = std::hash<K>()(key) & (_M-1); /* check to see if key already exists in map */ if (contains(key)) return -1; /* create new node */ node *new_node = new node(key, value); /* find where to place element in linked list */ node **iter_node = &_buckets[key_hash]; while (*iter_node != NULL) iter_node = &(*iter_node)->next; /* place element in linked list */ *iter_node = new_node; /* increment counter and return number */ size_t N; #pragma omp critical (node_incr) { N = _N++; } return (int) N; } /** * @brief Returns the number of key/value pairs in the fixed-size table * @return number of key/value pairs in the map */ template <class K, class V> size_t FixedHashMap<K,V>::size() { return _N; } /** * @brief Returns the number of buckets in the fixed-size table * @return number of buckets in the map */ template <class K, class V> size_t FixedHashMap<K,V>::bucket_count() { return _M; } /** * @brief Returns an array of the keys in the fixed-size table * @details All buckets are scanned in order to form a list of all keys * present in the table and then the list is returned. WARNING: The user * is responsible for freeing the allocated memory once the array is no * longer needed. * @return an array of keys in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> K* FixedHashMap<K,V>::keys() { /* allocate array of keys */ K *key_list = new K[_N]; /* fill array with keys */ size_t ind = 0; for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { key_list[ind] = iter_node->key; iter_node = iter_node->next; ind++; } } return key_list; } /** * @brief Returns an array of the values in the fixed-size table * @details All buckets are scanned in order to form a list of all values * present in the table and then the list is returned. WARNING: The user * is responsible for freeing the allocated memory once the array is no * longer needed. * @return an array of values in the map whose length is the number of * key/value pairs in the table. */ template <class K, class V> V* FixedHashMap<K,V>::values() { /* allocate array of values */ V *values = new V[_N]; /* fill array with values */ size_t ind = 0; for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { values[ind] = iter_node->value; iter_node = iter_node->next; ind++; } } return values; } /** * @brief Clears all key/value pairs form the hash table. */ template <class K, class V> void FixedHashMap<K,V>::clear() { /* for each bucket, scan through linked list and delete all nodes */ for (size_t i=0; i<_M; i++) { node *iter_node = _buckets[i]; while (iter_node != NULL) { node *next_node = iter_node->next; delete iter_node; iter_node = next_node; } } /* reset each bucket to null */ for (size_t i=0; i<_M; i++) _buckets[i] = NULL; /* reset the number of entries to zero */ _N = 0; } /** * @brief Prints the contents of each bucket to the screen * @details All buckets are scanned and the contents of the buckets are * printed, which are pointers to linked lists. If the pointer is NULL * suggesting that the linked list is empty, NULL is printed to the * screen. */ template <class K, class V> void FixedHashMap<K,V>::print_buckets() { for (size_t i=0; i<_M; i++) { if (_buckets[i] == NULL) std::cout << i << " -> NULL" << std::endl; else std::cout << i << " -> " << _buckets[i] << std::endl; } } /** * @brief Constructor generates initial underlying table as a fixed-sized * hash map and intializes concurrency structures. */ template <class K, class V> ParallelHashMap<K,V>::ParallelHashMap(size_t M, size_t L) { /* allocate table */ _table = new FixedHashMap<K,V>(M); /* get number of threads and create concurrency structures */ _num_threads = 1; #ifdef OPENMP _num_threads = omp_get_max_threads(); _num_locks = L; _locks = new omp_lock_t[_num_locks]; for (size_t i=0; i<_num_locks; i++) omp_init_lock(&_locks[i]); #endif _announce = new paddedPointer[_num_threads]; } /** * @brief Destructor frees memory associated with fixed-sized hash map and * concurrency structures. */ template <class K, class V> ParallelHashMap<K,V>::~ParallelHashMap() { delete _table; #ifdef OPENMP delete[] _locks; #endif delete[] _announce; } /** * @brief Determine whether the parallel hash map contains a given key * @details First the thread accessing the table announces its presence and * which table it is reading. Then the linked list in the bucket * associated with the key is searched without setting any locks * to determine whether the key is present. When the thread has * finished accessing the table, the announcement is reset to NULL. * The announcement ensures that the data in the map is not freed * during a resize until all threads have finished accessing the map. * @param key key to be searched * @return boolean value referring to whether the key is contained in the map */ template <class K, class V> bool ParallelHashMap<K,V>::contains(K key) { /* get thread ID */ size_t tid = 0; #ifdef OPENMP tid = omp_get_thread_num(); #endif /* get pointer to table, announce it will be searched, and ensure consistency */ FixedHashMap<K,V> *table_ptr; do{ table_ptr = _table; _announce[tid].value = table_ptr; } while (table_ptr != _table); /* see if current table contains the thread */ bool present = table_ptr->contains(key); /* reset table announcement to not searching */ _announce[tid].value = NULL; return present; } /** * @brief Determine the value associated with a given key. * @details This function follows the same algorithm as <contains> except that * the value associated with the searched key is returned. * First the thread accessing the table announces its presence and * which table it is reading. Then the linked list in the bucket * associated with the key is searched without setting any locks * to determine the associated value. An exception is thrown if the * key is not found. When the thread has finished accessing the table, * the announcement is reset to NULL. The announcement ensures that * the data in the map is not freed during a resize until all threads * have finished accessing the map. * @param key key to be searched * @return value associated with the key */ template <class K, class V> V& ParallelHashMap<K,V>::at(K key) { /* get thread ID */ size_t tid = 0; #ifdef OPENMP tid = omp_get_thread_num(); #endif /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do{ table_ptr = _table; _announce[tid].value = table_ptr; } while (table_ptr != _table); /* get value associated with the key in the underlying table */ V& value = table_ptr->at(key); /* reset table announcement to not searching */ _announce[tid].value = NULL; return value; } /** * @brief Insert a given key/value pair into the parallel hash map. * @details First the underlying table is checked to determine if a resize * should be conducted. Then, the table is checked to see if it * already contains the key. If so, the key/value pair is not inserted * and the function returns. Otherwise, the lock of the associated * bucket is acquired and the key/value pair is added to the bucket. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted */ template <class K, class V> void ParallelHashMap<K,V>::insert(K key, V value) { /* check if resize needed */ if (2*_table->size() > _table->bucket_count()) resize(); /* check to see if key is already contained in the table */ if (contains(key)) return; /* get lock hash */ #ifdef OPENMP size_t lock_hash = (std::hash<K>()(key) & (_table->bucket_count() - 1)) % _num_locks; /* acquire lock */ omp_set_lock(&_locks[lock_hash]); #endif /* insert value */ _table->insert(key, value); /* release lock */ #ifdef OPENMP omp_unset_lock(&_locks[lock_hash]); #endif } /** * @brief Insert a given key/value pair into the parallel hash map and return the order number. * @details First the underlying table is checked to determine if a resize * should be conducted. Then, the table is checked to see if it * already contains the key. If so, the key/value pair is not inserted * and the function returns. Otherwise, the lock of the associated * bucket is acquired and the key/value pair is added to the bucket. * @param key key of the key/value pair to be inserted * @param value value of the key/value pair to be inserted * @return order number in which the key/value pair was inserted, -1 if it * already exists */ template <class K, class V> int ParallelHashMap<K,V>::insert_and_get_count(K key, V value) { /* check if resize needed */ if (2*_table->size() > _table->bucket_count()) resize(); /* check to see if key is already contained in the table */ if (contains(key)) return -1; /* get lock hash */ #ifdef OPENMP size_t lock_hash = (std::hash<K>()(key) & (_table->bucket_count() - 1)) % _num_locks; /* acquire lock */ omp_set_lock(&_locks[lock_hash]); #endif /* insert value */ int N =_table->insert_and_get_count(key, value); /* release lock */ #ifdef OPENMP omp_unset_lock(&_locks[lock_hash]); #endif return N; } /** * @brief Resizes the underlying table to twice its current capacity. * @details In a thread-safe manner, this procedure resizes the underlying * FixedHashMap table to twice its current capacity using locks and the * announce array. First, all locks are set in order to block inserts and * prevent deadlock. A new table is allocated of twice the size and all * key/value pairs from the old table, then the pointer is switched to the * new table and locks are released. Finally the memory needs to be freed. * To prevent threads currently reading the table from encountering * segmentation faults, the resizing threads waits for the announce array * to be free of references to the old table before freeing the memory. */ template <class K, class V> void ParallelHashMap<K,V>::resize() { /* acquire all locks in order */ #ifdef OPENMP for (size_t i=0; i<_num_locks; i++) omp_set_lock(&_locks[i]); #endif /* recheck if resize needed */ if (2*_table->size() < _table->bucket_count()) { /* release locks */ #ifdef OPENMP for (size_t i=0; i<_num_locks; i++) omp_unset_lock(&_locks[i]); #endif return; } /* allocate new hash map of double the size */ FixedHashMap<K,V> *new_map = new FixedHashMap<K,V>(2*_table->bucket_count()); /* get keys, values, and number of elements */ K *key_list = _table->keys(); V *value_list = _table->values(); /* insert key/value pairs into new hash map */ for (size_t i=0; i<_table->size(); i++) new_map->insert(key_list[i], value_list[i]); /* save pointer of old table */ FixedHashMap<K,V> *old_table = _table; /* reassign pointer */ _table = new_map; /* release all locks */ #ifdef OPENMP for (size_t i=0; i<_num_locks; i++) omp_unset_lock(&_locks[i]); #endif /* delete key and value list */ delete[] key_list; delete[] value_list; /* wait for all threads to stop reading from the old table */ for (size_t i=0; i<_num_threads; i++) while (_announce[i].value == old_table) {}; /* free memory associated with old table */ delete old_table; } /** * @brief Returns the number of key/value pairs in the underlying table * @return number of key/value pairs in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::size() { return _table->size(); } /** * @brief Returns the number of buckets in the underlying table * @return number of buckets in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::bucket_count() { return _table->bucket_count(); } /** * @brief Returns the number of locks in the parallel hash map * @return number of locks in the map */ template <class K, class V> size_t ParallelHashMap<K,V>::num_locks() { return _num_locks; } /** * @brief Returns an array of the keys in the underlying table * @details All buckets are scanned in order to form a list of all keys * present in the table and then the list is returned. Threads * announce their presence to ensure table memory is not freed * during access. WARNING: The user is responsible for freeing the * allocated memory once the array is no longer needed. * @return an array of keys in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> K* ParallelHashMap<K,V>::keys() { /* get thread ID */ size_t tid = 0; #ifdef OPENMP tid = omp_get_thread_num(); #endif /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do{ table_ptr = _table; _announce[tid].value = table_ptr; } while (table_ptr != _table); /* get key list */ K* key_list = table_ptr->keys(); /* reset table announcement to not searching */ _announce[tid].value = NULL; return key_list; } /** * @brief Returns an array of the values in the underlying table * @details All buckets are scanned in order to form a list of all values * present in the table and then the list is returned. Threads * announce their presence to ensure table memory is not freed * during access. WARNING: The user is responsible for freeing the * allocated memory once the array is no longer needed. * @return an array of values in the map whose length is the number of key/value * pairs in the table. */ template <class K, class V> V* ParallelHashMap<K,V>::values() { /* get thread ID */ size_t tid = 0; #ifdef OPENMP tid = omp_get_thread_num(); #endif /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do{ table_ptr = _table; _announce[tid].value = table_ptr; } while (table_ptr != _table); /* get value list */ V* value_list = table_ptr->values(); /* reset table announcement to not searching */ _announce[tid].value = NULL; return value_list; } /** * @brief Clears all key/value pairs form the hash table. */ template <class K, class V> void ParallelHashMap<K,V>::clear() { /* acquire all locks in order */ #ifdef OPENMP for (size_t i=0; i<_num_locks; i++) omp_set_lock(&_locks[i]); #endif /* clear underlying fixed table */ _table->clear(); } /** * @brief Prints the contents of each bucket to the screen * @details All buckets are scanned and the contents of the buckets are * printed, which are pointers to linked lists. If the pointer is NULL * suggesting that the linked list is empty, NULL is printed to the * screen. Threads announce their presence to ensure table memory is * not freed during access. */ template <class K, class V> void ParallelHashMap<K,V>::print_buckets() { /* get thread ID */ size_t tid = 0; #ifdef OPENMP tid = omp_get_thread_num(); #endif /* get pointer to table, announce it will be searched */ FixedHashMap<K,V> *table_ptr; do{ table_ptr = _table; _announce[tid].value = table_ptr; } while (table_ptr != _table); /* print buckets */ table_ptr->print_buckets(); /* reset table announcement to not searching */ _announce[tid].value = NULL; } #endif
GB_binop__eq_fc32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__eq_fc32 // A.*B function (eWiseMult): GB_AemultB__eq_fc32 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__eq_fc32 // C+=b function (dense accum): GB_Cdense_accumb__eq_fc32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__eq_fc32 // C=scalar+B GB_bind1st__eq_fc32 // C=scalar+B' GB_bind1st_tran__eq_fc32 // C=A+scalar GB_bind2nd__eq_fc32 // C=A'+scalar GB_bind2nd_tran__eq_fc32 // C type: bool // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_eq (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = (crealf (Ax [pA]) != 0) || (cimagf (Ax [pA]) != 0) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = (crealf (Bx [pB]) != 0) || (cimagf (Bx [pB]) != 0) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_FC32_eq (x, y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_FC32 || GxB_NO_EQ_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__eq_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__eq_fc32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__eq_fc32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__eq_fc32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__eq_fc32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__eq_fc32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_eq (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__eq_fc32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_eq (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_eq (x, aij) ; \ } GrB_Info GB_bind1st_tran__eq_fc32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_eq (aij, y) ; \ } GrB_Info GB_bind2nd_tran__eq_fc32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB056-jacobi2d-tile-no.c
/** * jacobi-2d-imper.c: This file is part of the PolyBench/C 3.2 test suite. * Jacobi with array copying, no reduction. with tiling and nested SIMD. * * Contact: Louis-Noel Pouchet <[email protected]> * Web address: http://polybench.sourceforge.net * License: /LICENSE.OSU.txt */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include "polybench/polybench.h" /* Include benchmark-specific header. */ /* Default data type is double, default size is 20x1000. */ #include "polybench/jacobi-2d-imper.h" /* Array initialization. */ static void init_array(int n,double A[500 + 0][500 + 0],double B[500 + 0][500 + 0]) { //int i; //int j; { int c1; int c2; int c4; int c3; if (n >= 1) { #pragma omp parallel for private(c1 ,c3 ,c4 ,c2 ) for (c1 = 0; c1 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c1++) { #pragma omp parallel for private(c2 ,c3 ,c4 ) for (c2 = 0; c2 <= (((n + -1) * 16 < 0?((16 < 0?-((-(n + -1) + 16 + 1) / 16) : -((-(n + -1) + 16 - 1) / 16))) : (n + -1) / 16)); c2++) { #pragma omp parallel for private(c3 ,c4 ) for (c3 = 16 * c2; c3 <= ((16 * c2 + 15 < n + -1?16 * c2 + 15 : n + -1)); c3++) { #pragma omp parallel for private(c4 ) for (c4 = 16 * c1; c4 <= ((16 * c1 + 15 < n + -1?16 * c1 + 15 : n + -1)); c4++) { A[c4][c3] = (((double )c4) * (c3 + 2) + 2) / n; B[c4][c3] = (((double )c4) * (c3 + 3) + 3) / n; } } } } } } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int n,double A[500 + 0][500 + 0]) { int i; int j; for (i = 0; i < n; i++) for (j = 0; j < n; j++) { fprintf(stderr,"%0.2lf ",A[i][j]); if ((i * n + j) % 20 == 0) fprintf(stderr,"\n"); } fprintf(stderr,"\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_jacobi_2d_imper(int tsteps,int n,double A[500 + 0][500 + 0],double B[500 + 0][500 + 0]) { //int t; //int i; //int j; //#pragma scop { int c0; int c1; int c3; int c2; int c4; int c5; if (n >= 3 && tsteps >= 1) { for (c0 = 0; c0 <= (((n + 3 * tsteps + -4) * 16 < 0?((16 < 0?-((-(n + 3 * tsteps + -4) + 16 + 1) / 16) : -((-(n + 3 * tsteps + -4) + 16 - 1) / 16))) : (n + 3 * tsteps + -4) / 16)); c0++) { #pragma omp parallel for private(c1 ,c5 ,c4 ,c2 ,c3 ) for (c1 = (((2 * c0 * 3 < 0?-(-(2 * c0) / 3) : ((3 < 0?(-(2 * c0) + - 3 - 1) / - 3 : (2 * c0 + 3 - 1) / 3)))) > (((16 * c0 + -1 * tsteps + 1) * 16 < 0?-(-(16 * c0 + -1 * tsteps + 1) / 16) : ((16 < 0?(-(16 * c0 + -1 * tsteps + 1) + - 16 - 1) / - 16 : (16 * c0 + -1 * tsteps + 1 + 16 - 1) / 16))))?((2 * c0 * 3 < 0?-(-(2 * c0) / 3) : ((3 < 0?(-(2 * c0) + - 3 - 1) / - 3 : (2 * c0 + 3 - 1) / 3)))) : (((16 * c0 + -1 * tsteps + 1) * 16 < 0?-(-(16 * c0 + -1 * tsteps + 1) / 16) : ((16 < 0?(-(16 * c0 + -1 * tsteps + 1) + - 16 - 1) / - 16 : (16 * c0 + -1 * tsteps + 1 + 16 - 1) / 16))))); c1 <= (((((((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)) < (((32 * c0 + n + 29) * 48 < 0?((48 < 0?-((-(32 * c0 + n + 29) + 48 + 1) / 48) : -((-(32 * c0 + n + 29) + 48 - 1) / 48))) : (32 * c0 + n + 29) / 48))?(((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)) : (((32 * c0 + n + 29) * 48 < 0?((48 < 0?-((-(32 * c0 + n + 29) + 48 + 1) / 48) : -((-(32 * c0 + n + 29) + 48 - 1) / 48))) : (32 * c0 + n + 29) / 48)))) < c0?(((((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)) < (((32 * c0 + n + 29) * 48 < 0?((48 < 0?-((-(32 * c0 + n + 29) + 48 + 1) / 48) : -((-(32 * c0 + n + 29) + 48 - 1) / 48))) : (32 * c0 + n + 29) / 48))?(((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)) : (((32 * c0 + n + 29) * 48 < 0?((48 < 0?-((-(32 * c0 + n + 29) + 48 + 1) / 48) : -((-(32 * c0 + n + 29) + 48 - 1) / 48))) : (32 * c0 + n + 29) / 48)))) : c0)); c1++) { for (c2 = ((((16 * c1 + -1 * n + -12) * 16 < 0?-(-(16 * c1 + -1 * n + -12) / 16) : ((16 < 0?(-(16 * c1 + -1 * n + -12) + - 16 - 1) / - 16 : (16 * c1 + -1 * n + -12 + 16 - 1) / 16)))) > 2 * c0 + -2 * c1?(((16 * c1 + -1 * n + -12) * 16 < 0?-(-(16 * c1 + -1 * n + -12) / 16) : ((16 < 0?(-(16 * c1 + -1 * n + -12) + - 16 - 1) / - 16 : (16 * c1 + -1 * n + -12 + 16 - 1) / 16)))) : 2 * c0 + -2 * c1); c2 <= (((((((16 * c1 + n + 12) * 16 < 0?((16 < 0?-((-(16 * c1 + n + 12) + 16 + 1) / 16) : -((-(16 * c1 + n + 12) + 16 - 1) / 16))) : (16 * c1 + n + 12) / 16)) < (((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16))?(((16 * c1 + n + 12) * 16 < 0?((16 < 0?-((-(16 * c1 + n + 12) + 16 + 1) / 16) : -((-(16 * c1 + n + 12) + 16 - 1) / 16))) : (16 * c1 + n + 12) / 16)) : (((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)))) < (((32 * c0 + -32 * c1 + n + 29) * 16 < 0?((16 < 0?-((-(32 * c0 + -32 * c1 + n + 29) + 16 + 1) / 16) : -((-(32 * c0 + -32 * c1 + n + 29) + 16 - 1) / 16))) : (32 * c0 + -32 * c1 + n + 29) / 16))?(((((16 * c1 + n + 12) * 16 < 0?((16 < 0?-((-(16 * c1 + n + 12) + 16 + 1) / 16) : -((-(16 * c1 + n + 12) + 16 - 1) / 16))) : (16 * c1 + n + 12) / 16)) < (((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16))?(((16 * c1 + n + 12) * 16 < 0?((16 < 0?-((-(16 * c1 + n + 12) + 16 + 1) / 16) : -((-(16 * c1 + n + 12) + 16 - 1) / 16))) : (16 * c1 + n + 12) / 16)) : (((n + 2 * tsteps + -3) * 16 < 0?((16 < 0?-((-(n + 2 * tsteps + -3) + 16 + 1) / 16) : -((-(n + 2 * tsteps + -3) + 16 - 1) / 16))) : (n + 2 * tsteps + -3) / 16)))) : (((32 * c0 + -32 * c1 + n + 29) * 16 < 0?((16 < 0?-((-(32 * c0 + -32 * c1 + n + 29) + 16 + 1) / 16) : -((-(32 * c0 + -32 * c1 + n + 29) + 16 - 1) / 16))) : (32 * c0 + -32 * c1 + n + 29) / 16)))); c2++) { if (c0 <= (((32 * c1 + 16 * c2 + -1 * n + 1) * 32 < 0?((32 < 0?-((-(32 * c1 + 16 * c2 + -1 * n + 1) + 32 + 1) / 32) : -((-(32 * c1 + 16 * c2 + -1 * n + 1) + 32 - 1) / 32))) : (32 * c1 + 16 * c2 + -1 * n + 1) / 32)) && c1 <= c2 + -1) { if ((n + 1) % 2 == 0) { for (c4 = (16 * c1 > 16 * c2 + -1 * n + 3?16 * c1 : 16 * c2 + -1 * n + 3); c4 <= 16 * c1 + 15; c4++) { A[-16 * c2 + c4 + n + -2][n + -2] = B[-16 * c2 + c4 + n + -2][n + -2]; } } } if (c0 <= (((48 * c1 + -1 * n + 1) * 32 < 0?((32 < 0?-((-(48 * c1 + -1 * n + 1) + 32 + 1) / 32) : -((-(48 * c1 + -1 * n + 1) + 32 - 1) / 32))) : (48 * c1 + -1 * n + 1) / 32)) && c1 >= c2) { if ((n + 1) % 2 == 0) { for (c5 = (16 * c2 > 16 * c1 + -1 * n + 3?16 * c2 : 16 * c1 + -1 * n + 3); c5 <= ((16 * c1 < 16 * c2 + 15?16 * c1 : 16 * c2 + 15)); c5++) { A[n + -2][-16 * c1 + c5 + n + -2] = B[n + -2][-16 * c1 + c5 + n + -2]; } } } for (c3 = ((((((16 * c1 + -1 * n + 2) * 2 < 0?-(-(16 * c1 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c1 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c1 + -1 * n + 2 + 2 - 1) / 2)))) > (((16 * c2 + -1 * n + 2) * 2 < 0?-(-(16 * c2 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c2 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c2 + -1 * n + 2 + 2 - 1) / 2))))?(((16 * c1 + -1 * n + 2) * 2 < 0?-(-(16 * c1 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c1 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c1 + -1 * n + 2 + 2 - 1) / 2)))) : (((16 * c2 + -1 * n + 2) * 2 < 0?-(-(16 * c2 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c2 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c2 + -1 * n + 2 + 2 - 1) / 2)))))) > 16 * c0 + -16 * c1?(((((16 * c1 + -1 * n + 2) * 2 < 0?-(-(16 * c1 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c1 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c1 + -1 * n + 2 + 2 - 1) / 2)))) > (((16 * c2 + -1 * n + 2) * 2 < 0?-(-(16 * c2 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c2 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c2 + -1 * n + 2 + 2 - 1) / 2))))?(((16 * c1 + -1 * n + 2) * 2 < 0?-(-(16 * c1 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c1 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c1 + -1 * n + 2 + 2 - 1) / 2)))) : (((16 * c2 + -1 * n + 2) * 2 < 0?-(-(16 * c2 + -1 * n + 2) / 2) : ((2 < 0?(-(16 * c2 + -1 * n + 2) + - 2 - 1) / - 2 : (16 * c2 + -1 * n + 2 + 2 - 1) / 2)))))) : 16 * c0 + -16 * c1); c3 <= ((((((8 * c1 + 6 < 8 * c2 + 6?8 * c1 + 6 : 8 * c2 + 6)) < tsteps + -1?((8 * c1 + 6 < 8 * c2 + 6?8 * c1 + 6 : 8 * c2 + 6)) : tsteps + -1)) < 16 * c0 + -16 * c1 + 15?((((8 * c1 + 6 < 8 * c2 + 6?8 * c1 + 6 : 8 * c2 + 6)) < tsteps + -1?((8 * c1 + 6 < 8 * c2 + 6?8 * c1 + 6 : 8 * c2 + 6)) : tsteps + -1)) : 16 * c0 + -16 * c1 + 15)); c3++) { if (c1 <= ((c3 * 8 < 0?((8 < 0?-((-c3 + 8 + 1) / 8) : -((-c3 + 8 - 1) / 8))) : c3 / 8))) { for (c5 = (16 * c2 > 2 * c3 + 1?16 * c2 : 2 * c3 + 1); c5 <= ((16 * c2 + 15 < 2 * c3 + n + -2?16 * c2 + 15 : 2 * c3 + n + -2)); c5++) { B[1][-2 * c3 + c5] = 0.2 * (A[1][-2 * c3 + c5] + A[1][-2 * c3 + c5 - 1] + A[1][1 + (-2 * c3 + c5)] + A[1 + 1][-2 * c3 + c5] + A[1 - 1][-2 * c3 + c5]); } } for (c4 = (16 * c1 > 2 * c3 + 2?16 * c1 : 2 * c3 + 2); c4 <= ((16 * c1 + 15 < 2 * c3 + n + -2?16 * c1 + 15 : 2 * c3 + n + -2)); c4++) { if (c2 <= ((c3 * 8 < 0?((8 < 0?-((-c3 + 8 + 1) / 8) : -((-c3 + 8 - 1) / 8))) : c3 / 8))) { B[-2 * c3 + c4][1] = 0.2 * (A[-2 * c3 + c4][1] + A[-2 * c3 + c4][1 - 1] + A[-2 * c3 + c4][1 + 1] + A[1 + (-2 * c3 + c4)][1] + A[-2 * c3 + c4 - 1][1]); } for (c5 = (16 * c2 > 2 * c3 + 2?16 * c2 : 2 * c3 + 2); c5 <= ((16 * c2 + 15 < 2 * c3 + n + -2?16 * c2 + 15 : 2 * c3 + n + -2)); c5++) { B[-2 * c3 + c4][-2 * c3 + c5] = 0.2 * (A[-2 * c3 + c4][-2 * c3 + c5] + A[-2 * c3 + c4][-2 * c3 + c5 - 1] + A[-2 * c3 + c4][1 + (-2 * c3 + c5)] + A[1 + (-2 * c3 + c4)][-2 * c3 + c5] + A[-2 * c3 + c4 - 1][-2 * c3 + c5]); A[-2 * c3 + c4 + -1][-2 * c3 + c5 + -1] = B[-2 * c3 + c4 + -1][-2 * c3 + c5 + -1]; } if (c2 >= (((2 * c3 + n + -16) * 16 < 0?-(-(2 * c3 + n + -16) / 16) : ((16 < 0?(-(2 * c3 + n + -16) + - 16 - 1) / - 16 : (2 * c3 + n + -16 + 16 - 1) / 16))))) { A[-2 * c3 + c4 + -1][n + -2] = B[-2 * c3 + c4 + -1][n + -2]; } } if (c1 >= (((2 * c3 + n + -16) * 16 < 0?-(-(2 * c3 + n + -16) / 16) : ((16 < 0?(-(2 * c3 + n + -16) + - 16 - 1) / - 16 : (2 * c3 + n + -16 + 16 - 1) / 16))))) { for (c5 = (16 * c2 > 2 * c3 + 2?16 * c2 : 2 * c3 + 2); c5 <= ((16 * c2 + 15 < 2 * c3 + n + -1?16 * c2 + 15 : 2 * c3 + n + -1)); c5++) { A[n + -2][-2 * c3 + c5 + -1] = B[n + -2][-2 * c3 + c5 + -1]; } } } if (c0 >= (((2 * c1 + c2 + -1) * 2 < 0?-(-(2 * c1 + c2 + -1) / 2) : ((2 < 0?(-(2 * c1 + c2 + -1) + - 2 - 1) / - 2 : (2 * c1 + c2 + -1 + 2 - 1) / 2)))) && c1 >= c2 + 1 && c2 <= (((tsteps + -8) * 8 < 0?((8 < 0?-((-(tsteps + -8) + 8 + 1) / 8) : -((-(tsteps + -8) + 8 - 1) / 8))) : (tsteps + -8) / 8))) { for (c4 = 16 * c1; c4 <= ((16 * c1 + 15 < 16 * c2 + n + 12?16 * c1 + 15 : 16 * c2 + n + 12)); c4++) { B[-16 * c2 + c4 + -14][1] = 0.2 * (A[-16 * c2 + c4 + -14][1] + A[-16 * c2 + c4 + -14][1 - 1] + A[-16 * c2 + c4 + -14][1 + 1] + A[1 + (-16 * c2 + c4 + -14)][1] + A[-16 * c2 + c4 + -14 - 1][1]); } } if (c0 >= (((3 * c1 + -1) * 2 < 0?-(-(3 * c1 + -1) / 2) : ((2 < 0?(-(3 * c1 + -1) + - 2 - 1) / - 2 : (3 * c1 + -1 + 2 - 1) / 2)))) && c1 <= (((((tsteps + -8) * 8 < 0?((8 < 0?-((-(tsteps + -8) + 8 + 1) / 8) : -((-(tsteps + -8) + 8 - 1) / 8))) : (tsteps + -8) / 8)) < c2?(((tsteps + -8) * 8 < 0?((8 < 0?-((-(tsteps + -8) + 8 + 1) / 8) : -((-(tsteps + -8) + 8 - 1) / 8))) : (tsteps + -8) / 8)) : c2))) { for (c5 = (16 * c2 > 16 * c1 + 15?16 * c2 : 16 * c1 + 15); c5 <= ((16 * c2 + 15 < 16 * c1 + n + 12?16 * c2 + 15 : 16 * c1 + n + 12)); c5++) { B[1][-16 * c1 + c5 + -14] = 0.2 * (A[1][-16 * c1 + c5 + -14] + A[1][-16 * c1 + c5 + -14 - 1] + A[1][1 + (-16 * c1 + c5 + -14)] + A[1 + 1][-16 * c1 + c5 + -14] + A[1 - 1][-16 * c1 + c5 + -14]); } } } } } } } //#pragma endscop } int main(int argc,char **argv) { /* Retrieve problem size. */ int n = 500; int tsteps = 10; /* Variable declaration/allocation. */ double (*A)[500 + 0][500 + 0]; A = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double ))))); ; double (*B)[500 + 0][500 + 0]; B = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double ))))); ; /* Initialize array(s). */ init_array(n, *A, *B); /* Start timer. */ polybench_timer_start(); ; /* Run kernel. */ kernel_jacobi_2d_imper(tsteps,n, *A, *B); /* Stop and print timer. */ polybench_timer_stop(); ; polybench_timer_print(); ; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ if (argc > 42 && !strcmp(argv[0],"")) print_array(n, *A); /* Be clean. */ free(((void *)A)); ; free(((void *)B)); ; return 0; }
cmontecarlo.c
#include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #ifdef WITHOPENMP #include <omp.h> #endif #include "io.h" #include "abbrev.h" #include "status.h" #include "rpacket.h" #include "cmontecarlo.h" /** Look for a place to insert a value in an inversely sorted float array. * * @param x an inversely (largest to lowest) sorted float array * @param x_insert a value to insert * @param imin lower bound * @param imax upper bound * * @return index of the next boundary to the left */ tardis_error_t reverse_binary_search (const double *x, double x_insert, int64_t imin, int64_t imax, int64_t * result) { /* Have in mind that *x points to a reverse sorted array. That is large values will have small indices and small ones will have large indices. */ tardis_error_t ret_val = TARDIS_ERROR_OK; if (x_insert > x[imin] || x_insert < x[imax]) { ret_val = TARDIS_ERROR_BOUNDS_ERROR; } else { int imid = (imin + imax) >> 1; while (imax - imin > 2) { if (x[imid] < x_insert) { imax = imid + 1; } else { imin = imid; } imid = (imin + imax) >> 1; } if (imax - imin == 2 && x_insert < x[imin + 1]) { *result = imin + 1; } else { *result = imin; } } return ret_val; } /** Insert a value in to an array of line frequencies * * @param nu array of line frequencies * @param nu_insert value of nu key * @param number_of_lines number of lines in the line list * * @return index of the next line ot the red. If the key value is redder than the reddest line returns number_of_lines. */ tardis_error_t line_search (const double *nu, double nu_insert, int64_t number_of_lines, int64_t * result) { tardis_error_t ret_val = TARDIS_ERROR_OK; int64_t imin = 0; int64_t imax = number_of_lines - 1; if (nu_insert > nu[imin]) { *result = imin; } else if (nu_insert < nu[imax]) { *result = imax + 1; } else { ret_val = reverse_binary_search (nu, nu_insert, imin, imax, result); *result = *result + 1; } return ret_val; } tardis_error_t binary_search (const double *x, double x_insert, int64_t imin, int64_t imax, int64_t * result) { /* Have in mind that *x points to a sorted array. Like [1,2,3,4,5,...] */ int imid; tardis_error_t ret_val = TARDIS_ERROR_OK; if (x_insert < x[imin] || x_insert > x[imax]) { ret_val = TARDIS_ERROR_BOUNDS_ERROR; } else { while (imax >= imin) { imid = (imin + imax) / 2; if (x[imid] == x_insert) { *result = imid; break; } else if (x[imid] < x_insert) { imin = imid + 1; } else { imax = imid - 1; } } if (imax - imid == 2 && x_insert < x[imin + 1]) { *result = imin; } else { *result = imin; } } return ret_val; } double rpacket_doppler_factor (const rpacket_t *packet, const storage_model_t *storage) { return 1.0 - rpacket_get_mu (packet) * rpacket_get_r (packet) * storage->inverse_time_explosion * INVERSE_C; } double bf_cross_section (const storage_model_t * storage, int64_t continuum_id, double comov_nu) { double bf_xsect; double *x_sect = storage->photo_xsect[continuum_id]->x_sect; double *nu = storage->photo_xsect[continuum_id]->nu; switch (storage->bf_treatment) { case LIN_INTERPOLATION: { int64_t result; tardis_error_t error = binary_search (nu, comov_nu, 0, storage->photo_xsect[continuum_id]->no_of_points - 1, &result); if (error == TARDIS_ERROR_BOUNDS_ERROR) { bf_xsect = 0.0; } else { bf_xsect = x_sect[result-1] + (comov_nu - nu[result-1]) / (nu[result] - nu[result-1]) * (x_sect[result] - x_sect[result-1]); } break; } case HYDROGENIC: { double nu_ratio = nu[0] / comov_nu; bf_xsect = x_sect[0] * nu_ratio * nu_ratio * nu_ratio; break; } default: fprintf (stderr, "(%d) is not a valid bound-free cross section treatment.\n", storage->bf_treatment); exit(1); } return bf_xsect; } void calculate_chi_bf (rpacket_t * packet, storage_model_t * storage) { double doppler_factor = rpacket_doppler_factor (packet, storage); double comov_nu = rpacket_get_nu (packet) * doppler_factor; int64_t no_of_continuum_edges = storage->no_of_edges; int64_t current_continuum_id; line_search(storage->continuum_list_nu, comov_nu, no_of_continuum_edges, &current_continuum_id); rpacket_set_current_continuum_id (packet, current_continuum_id); int64_t shell_id = rpacket_get_current_shell_id (packet); double T = storage->t_electrons[shell_id]; double boltzmann_factor = exp (-(H * comov_nu) / (KB * T)); double bf_helper = 0; for(int64_t i = current_continuum_id; i < no_of_continuum_edges; i++) { // get the level population for the level ijk in the current shell: double l_pop = storage->l_pop[shell_id * no_of_continuum_edges + i]; // get the level population ratio \frac{n_{0,j+1,k}}{n_{i,j,k}} \frac{n_{i,j,k}}{n_{0,j+1,k}}^{*}: double l_pop_r = storage->l_pop_r[shell_id * no_of_continuum_edges + i]; double bf_x_sect = bf_cross_section (storage, i, comov_nu); if (bf_x_sect == 0.0) { break; } bf_helper += l_pop * bf_x_sect * (1.0 - l_pop_r * boltzmann_factor) * doppler_factor; packet->chi_bf_tmp_partial[i] = bf_helper; } rpacket_set_chi_boundfree(packet, bf_helper); } void calculate_chi_ff (rpacket_t * packet, const storage_model_t * storage) { double doppler_factor = rpacket_doppler_factor (packet, storage); double comov_nu = rpacket_get_nu (packet) * doppler_factor; int64_t shell_id = rpacket_get_current_shell_id (packet); double T = storage->t_electrons[shell_id]; double boltzmann_factor = exp (-(H * comov_nu) / KB / T); double chi_ff_factor = storage->chi_ff_factor[shell_id]; double chi_ff = chi_ff_factor * (1 - boltzmann_factor) * pow (comov_nu, -3); rpacket_set_chi_freefree (packet, chi_ff * doppler_factor); } void compute_distance2boundary (rpacket_t * packet, const storage_model_t * storage) { double r = rpacket_get_r (packet); double mu = rpacket_get_mu (packet); double r_outer = storage->r_outer[rpacket_get_current_shell_id (packet)]; double r_inner = storage->r_inner[rpacket_get_current_shell_id (packet)]; double check, distance; if (mu > 0.0) { // direction outward rpacket_set_next_shell_id (packet, 1); distance = sqrt (r_outer * r_outer + ((mu * mu - 1.0) * r * r)) - (r * mu); } else { // going inward if ( (check = r_inner * r_inner + (r * r * (mu * mu - 1.0)) )>= 0.0) { // hit inner boundary rpacket_set_next_shell_id (packet, -1); distance = - r * mu - sqrt (check); } else { // miss inner boundary rpacket_set_next_shell_id (packet, 1); distance = sqrt (r_outer * r_outer + ((mu * mu - 1.0) * r * r)) - (r * mu); } } rpacket_set_d_boundary (packet, distance); } tardis_error_t compute_distance2line (rpacket_t * packet, const storage_model_t * storage) { if (!rpacket_get_last_line (packet)) { double r = rpacket_get_r (packet); double mu = rpacket_get_mu (packet); double nu = rpacket_get_nu (packet); double nu_line = rpacket_get_nu_line (packet); double distance, nu_diff; double t_exp = storage->time_explosion; double inverse_t_exp = storage->inverse_time_explosion; int64_t cur_zone_id = rpacket_get_current_shell_id (packet); double doppler_factor = 1.0 - mu * r * inverse_t_exp * INVERSE_C; double comov_nu = nu * doppler_factor; if ( (nu_diff = comov_nu - nu_line) >= 0) { distance = (nu_diff / nu) * C * t_exp; rpacket_set_d_line (packet, distance); return TARDIS_ERROR_OK; } else { if (rpacket_get_next_line_id (packet) == storage->no_of_lines - 1) { fprintf (stderr, "last_line = %f\n", storage-> line_list_nu[rpacket_get_next_line_id (packet) - 1]); fprintf (stderr, "Last line in line list reached!"); } else if (rpacket_get_next_line_id (packet) == 0) { fprintf (stderr, "First line in line list!"); fprintf (stderr, "next_line = %f\n", storage-> line_list_nu[rpacket_get_next_line_id (packet) + 1]); } else { fprintf (stderr, "last_line = %f\n", storage-> line_list_nu[rpacket_get_next_line_id (packet) - 1]); fprintf (stderr, "next_line = %f\n", storage-> line_list_nu[rpacket_get_next_line_id (packet) + 1]); } fprintf (stderr, "ERROR: Comoving nu less than nu_line!\n"); fprintf (stderr, "comov_nu = %f\n", comov_nu); fprintf (stderr, "nu_line = %f\n", nu_line); fprintf (stderr, "(comov_nu - nu_line) / nu_line = %f\n", (comov_nu - nu_line) / nu_line); fprintf (stderr, "r = %f\n", r); fprintf (stderr, "mu = %f\n", mu); fprintf (stderr, "nu = %f\n", nu); fprintf (stderr, "doppler_factor = %f\n", doppler_factor); fprintf (stderr, "cur_zone_id = %" PRIi64 "\n", cur_zone_id); return TARDIS_ERROR_COMOV_NU_LESS_THAN_NU_LINE; } } else { rpacket_set_d_line (packet, MISS_DISTANCE); return TARDIS_ERROR_OK; } } void compute_distance2continuum (rpacket_t * packet, storage_model_t * storage) { double chi_continuum, d_continuum; double chi_electron = storage->electron_densities[rpacket_get_current_shell_id(packet)] * storage->sigma_thomson; if (storage->cont_status == CONTINUUM_ON) { if (packet->compute_chi_bf) { calculate_chi_bf (packet, storage); calculate_chi_ff (packet, storage); } else { packet->compute_chi_bf=true; } chi_electron *= rpacket_doppler_factor (packet, storage); chi_continuum = rpacket_get_chi_boundfree (packet) + rpacket_get_chi_freefree (packet) + chi_electron; d_continuum = rpacket_get_tau_event (packet) / chi_continuum; } else { chi_continuum = chi_electron; d_continuum = storage->inverse_electron_densities[rpacket_get_current_shell_id (packet)] * storage->inverse_sigma_thomson * rpacket_get_tau_event (packet); } if (rpacket_get_virtual_packet(packet) > 0) { //Set all continuum distances to MISS_DISTANCE in case of an virtual_packet d_continuum = MISS_DISTANCE; packet->compute_chi_bf = false; } else { // fprintf(stderr, "--------\n"); // fprintf(stderr, "nu = %e \n", rpacket_get_nu(packet)); // fprintf(stderr, "chi_electron = %e\n", chi_electron); // fprintf(stderr, "chi_boundfree = %e\n", calculate_chi_bf(packet, storage)); // fprintf(stderr, "chi_line = %e \n", rpacket_get_tau_event(packet) / rpacket_get_d_line(packet)); // fprintf(stderr, "--------\n"); //rpacket_set_chi_freefree(packet, chi_freefree); rpacket_set_chi_electron (packet, chi_electron); } rpacket_set_chi_continuum (packet, chi_continuum); rpacket_set_d_continuum (packet, d_continuum); } void macro_atom (rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state) { int emit = 0, i = 0, offset = -1; uint64_t activate_level = rpacket_get_macro_atom_activation_level (packet); while (emit >= 0) { double event_random = rk_double (mt_state); i = storage->macro_block_references[activate_level] - 1; double p = 0.0; offset = storage->transition_probabilities_nd * rpacket_get_current_shell_id (packet); do { ++i; p += storage->transition_probabilities[offset + i]; } while (p <= event_random); emit = storage->transition_type[i]; activate_level = storage->destination_level_id[i]; } switch (emit) { case BB_EMISSION: line_emission (packet, storage, storage->transition_line_id[i], mt_state); break; case BF_EMISSION: rpacket_set_current_continuum_id (packet, storage->transition_line_id[i]); storage->last_line_interaction_out_id[rpacket_get_id (packet)] = rpacket_get_current_continuum_id (packet); continuum_emission (packet, storage, mt_state, sample_nu_free_bound, 3); break; case FF_EMISSION: continuum_emission (packet, storage, mt_state, sample_nu_free_free, 4); break; case ADIABATIC_COOLING: storage->last_interaction_type[rpacket_get_id (packet)] = 5; rpacket_set_status (packet, TARDIS_PACKET_STATUS_REABSORBED); break; default: fprintf (stderr, "This process for macro-atom deactivation should not exist! (emit = %d)\n", emit); exit(1); } } void move_packet (rpacket_t * packet, storage_model_t * storage, double distance) { double doppler_factor = rpacket_doppler_factor (packet, storage); if (distance > 0.0) { double r = rpacket_get_r (packet); double new_r = sqrt (r * r + distance * distance + 2.0 * r * distance * rpacket_get_mu (packet)); rpacket_set_mu (packet, (rpacket_get_mu (packet) * r + distance) / new_r); rpacket_set_r (packet, new_r); if (rpacket_get_virtual_packet (packet) <= 0) { double comov_energy = rpacket_get_energy (packet) * doppler_factor; double comov_nu = rpacket_get_nu (packet) * doppler_factor; #ifdef WITHOPENMP #pragma omp atomic #endif storage->js[rpacket_get_current_shell_id (packet)] += comov_energy * distance; #ifdef WITHOPENMP #pragma omp atomic #endif storage->nubars[rpacket_get_current_shell_id (packet)] += comov_energy * distance * comov_nu; if (storage->cont_status) { increment_continuum_estimators(packet, storage, distance, comov_nu, comov_energy); } } } } void increment_continuum_estimators (const rpacket_t * packet, storage_model_t * storage, double distance, double comov_nu, double comov_energy) { int64_t current_continuum_id; int64_t no_of_continuum_edges = storage->no_of_edges; int64_t shell_id = rpacket_get_current_shell_id (packet); line_search(storage->continuum_list_nu, comov_nu, no_of_continuum_edges, &current_continuum_id); double T = storage->t_electrons[shell_id]; double boltzmann_factor = exp (-(H * comov_nu) / (KB * T)); #ifdef WITHOPENMP #pragma omp atomic #endif storage->ff_heating_estimator[shell_id] += comov_energy * distance * rpacket_get_chi_freefree (packet); for(int64_t i = current_continuum_id; i < no_of_continuum_edges; i++) { double bf_xsect = bf_cross_section (storage, i, comov_nu); int64_t photo_ion_idx = i * storage->no_of_shells + shell_id; double photo_ion_estimator_helper = comov_energy * distance * bf_xsect / comov_nu; double bf_heating_estimator_helper = comov_energy * distance * bf_xsect * (1. - storage->continuum_list_nu[i] / comov_nu); #ifdef WITHOPENMP #pragma omp atomic #endif storage->photo_ion_estimator[photo_ion_idx] += photo_ion_estimator_helper; #ifdef WITHOPENMP #pragma omp atomic #endif storage->stim_recomb_estimator[photo_ion_idx] += photo_ion_estimator_helper * boltzmann_factor; #ifdef WITHOPENMP #pragma omp atomic #endif storage->bf_heating_estimator[photo_ion_idx] += bf_heating_estimator_helper; #ifdef WITHOPENMP #pragma omp atomic #endif storage->stim_recomb_cooling_estimator[photo_ion_idx] += bf_heating_estimator_helper * boltzmann_factor; if (photo_ion_estimator_helper != 0.0) { #ifdef WITHOPENMP #pragma omp atomic #endif storage->photo_ion_estimator_statistics[photo_ion_idx] += 1; } else { break; } } } void increment_j_blue_estimator (const rpacket_t * packet, storage_model_t * storage, double d_line, int64_t j_blue_idx) { if (storage->line_lists_j_blues != NULL) { double r = rpacket_get_r (packet); double r_interaction = sqrt (r * r + d_line * d_line + 2.0 * r * d_line * rpacket_get_mu (packet)); double mu_interaction = (rpacket_get_mu (packet) * r + d_line) / r_interaction; double doppler_factor = 1.0 - mu_interaction * r_interaction * storage->inverse_time_explosion * INVERSE_C; double comov_energy = rpacket_get_energy (packet) * doppler_factor; #ifdef WITHOPENMP #pragma omp atomic #endif storage->line_lists_j_blues[j_blue_idx] += comov_energy / rpacket_get_nu (packet); } } void increment_Edotlu_estimator (const rpacket_t * packet, storage_model_t * storage, double d_line, int64_t line_idx) { if (storage->line_lists_Edotlu != NULL) { double r = rpacket_get_r (packet); double r_interaction = sqrt (r * r + d_line * d_line + 2.0 * r * d_line * rpacket_get_mu (packet)); double mu_interaction = (rpacket_get_mu (packet) * r + d_line) / r_interaction; double doppler_factor = 1.0 - mu_interaction * r_interaction * storage->inverse_time_explosion * INVERSE_C; double comov_energy = rpacket_get_energy (packet) * doppler_factor; #ifdef WITHOPENMP #pragma omp atomic #endif storage->line_lists_Edotlu[line_idx] += comov_energy; //rpacket_get_energy (packet); } } int64_t montecarlo_one_packet (storage_model_t * storage, rpacket_t * packet, int64_t virtual_mode, rk_state *mt_state) { int64_t reabsorbed=-1; if (virtual_mode == 0) { reabsorbed = montecarlo_one_packet_loop (storage, packet, 0, mt_state); } else { if ((rpacket_get_nu (packet) > storage->spectrum_virt_start_nu) && (rpacket_get_nu(packet) < storage->spectrum_virt_end_nu)) { for (int64_t i = 0; i < rpacket_get_virtual_packet_flag (packet); i++) { double weight; rpacket_t virt_packet = *packet; double mu_min; if (rpacket_get_r(&virt_packet) > storage->r_inner[0]) { mu_min = -1.0 * sqrt (1.0 - (storage->r_inner[0] / rpacket_get_r(&virt_packet)) * (storage->r_inner[0] / rpacket_get_r(&virt_packet))); } else { mu_min = 0.0; } double mu_bin = (1.0 - mu_min) / rpacket_get_virtual_packet_flag (packet); rpacket_set_mu(&virt_packet,mu_min + (i + rk_double (mt_state)) * mu_bin); switch (virtual_mode) { case -2: weight = 1.0 / rpacket_get_virtual_packet_flag (packet); break; case -1: weight = 2.0 * rpacket_get_mu(&virt_packet) / rpacket_get_virtual_packet_flag (packet); break; case 1: weight = (1.0 - mu_min) / 2.0 / rpacket_get_virtual_packet_flag (packet); break; default: fprintf (stderr, "Something has gone horribly wrong!\n"); // FIXME MR: we need to somehow signal an error here // I'm adding an exit() here to inform the compiler about the impossible path exit(1); } double doppler_factor_ratio = rpacket_doppler_factor (packet, storage) / rpacket_doppler_factor (&virt_packet, storage); rpacket_set_energy(&virt_packet, rpacket_get_energy (packet) * doppler_factor_ratio); rpacket_set_nu(&virt_packet,rpacket_get_nu (packet) * doppler_factor_ratio); reabsorbed = montecarlo_one_packet_loop (storage, &virt_packet, 1, mt_state); #ifdef WITH_VPACKET_LOGGING #ifdef WITHOPENMP #pragma omp critical { #endif // WITHOPENMP if (storage->virt_packet_count >= storage->virt_array_size) { storage->virt_array_size *= 2; storage->virt_packet_nus = safe_realloc(storage->virt_packet_nus, sizeof(double) * storage->virt_array_size); storage->virt_packet_energies = safe_realloc(storage->virt_packet_energies, sizeof(double) * storage->virt_array_size); storage->virt_packet_last_interaction_in_nu = safe_realloc(storage->virt_packet_last_interaction_in_nu, sizeof(double) * storage->virt_array_size); storage->virt_packet_last_interaction_type = safe_realloc(storage->virt_packet_last_interaction_type, sizeof(int64_t) * storage->virt_array_size); storage->virt_packet_last_line_interaction_in_id = safe_realloc(storage->virt_packet_last_line_interaction_in_id, sizeof(int64_t) * storage->virt_array_size); storage->virt_packet_last_line_interaction_out_id = safe_realloc(storage->virt_packet_last_line_interaction_out_id, sizeof(int64_t) * storage->virt_array_size); } storage->virt_packet_nus[storage->virt_packet_count] = rpacket_get_nu(&virt_packet); storage->virt_packet_energies[storage->virt_packet_count] = rpacket_get_energy(&virt_packet) * weight; storage->virt_packet_last_interaction_in_nu[storage->virt_packet_count] = storage->last_interaction_in_nu[rpacket_get_id (packet)]; storage->virt_packet_last_interaction_type[storage->virt_packet_count] = storage->last_interaction_type[rpacket_get_id (packet)]; storage->virt_packet_last_line_interaction_in_id[storage->virt_packet_count] = storage->last_line_interaction_in_id[rpacket_get_id (packet)]; storage->virt_packet_last_line_interaction_out_id[storage->virt_packet_count] = storage->last_line_interaction_out_id[rpacket_get_id (packet)]; storage->virt_packet_count += 1; #ifdef WITHOPENMP } #endif // WITHOPENMP #endif // WITH_VPACKET_LOGGING if ((rpacket_get_nu(&virt_packet) < storage->spectrum_end_nu) && (rpacket_get_nu(&virt_packet) > storage->spectrum_start_nu)) { #ifdef WITHOPENMP #pragma omp critical { #endif // WITHOPENMP int64_t virt_id_nu = floor ((rpacket_get_nu(&virt_packet) - storage->spectrum_start_nu) / storage->spectrum_delta_nu); storage->spectrum_virt_nu[virt_id_nu] += rpacket_get_energy(&virt_packet) * weight; #ifdef WITHOPENMP } #endif // WITHOPENMP } } } else { return 1; } } return reabsorbed; } void move_packet_across_shell_boundary (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state) { move_packet (packet, storage, distance); if (rpacket_get_virtual_packet (packet) > 0) { double delta_tau_event = rpacket_get_chi_continuum(packet) * distance; rpacket_set_tau_event (packet, rpacket_get_tau_event (packet) + delta_tau_event); packet->compute_chi_bf = true; } else { rpacket_reset_tau_event (packet, mt_state); } if ((rpacket_get_current_shell_id (packet) < storage->no_of_shells - 1 && rpacket_get_next_shell_id (packet) == 1) || (rpacket_get_current_shell_id (packet) > 0 && rpacket_get_next_shell_id (packet) == -1)) { rpacket_set_current_shell_id (packet, rpacket_get_current_shell_id (packet) + rpacket_get_next_shell_id (packet)); } else if (rpacket_get_next_shell_id (packet) == 1) { rpacket_set_status (packet, TARDIS_PACKET_STATUS_EMITTED); } else if ((storage->reflective_inner_boundary == 0) || (rk_double (mt_state) > storage->inner_boundary_albedo)) { rpacket_set_status (packet, TARDIS_PACKET_STATUS_REABSORBED); } else { double doppler_factor = rpacket_doppler_factor (packet, storage); double comov_nu = rpacket_get_nu (packet) * doppler_factor; double comov_energy = rpacket_get_energy (packet) * doppler_factor; rpacket_set_mu (packet, rk_double (mt_state)); double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); rpacket_set_nu (packet, comov_nu * inverse_doppler_factor); rpacket_set_energy (packet, comov_energy * inverse_doppler_factor); if (rpacket_get_virtual_packet_flag (packet) > 0) { montecarlo_one_packet (storage, packet, -2, mt_state); } } } void montecarlo_thomson_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state) { move_packet (packet, storage, distance); double doppler_factor = rpacket_doppler_factor (packet, storage); double comov_nu = rpacket_get_nu (packet) * doppler_factor; double comov_energy = rpacket_get_energy (packet) * doppler_factor; rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0); double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); rpacket_set_nu (packet, comov_nu * inverse_doppler_factor); rpacket_set_energy (packet, comov_energy * inverse_doppler_factor); rpacket_reset_tau_event (packet, mt_state); storage->last_interaction_type[rpacket_get_id (packet)] = 1; if (rpacket_get_virtual_packet_flag (packet) > 0) { montecarlo_one_packet (storage, packet, 1, mt_state); } } void montecarlo_bound_free_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state) { // current position in list of continuum edges -> indicates which bound-free processes are possible int64_t ccontinuum = rpacket_get_current_continuum_id (packet); // Determine in which continuum the bf-absorption occurs double chi_bf = rpacket_get_chi_boundfree (packet); double zrand = rk_double (mt_state); double zrand_x_chibf = zrand * chi_bf; while ((ccontinuum < storage->no_of_edges - 1) && (packet->chi_bf_tmp_partial[ccontinuum] <= zrand_x_chibf)) { ccontinuum++; } rpacket_set_current_continuum_id (packet, ccontinuum); /* For consistency reasons the branching between ionization and thermal energy is determined using the comoving frequency at the initial position instead of the frequency at the point of interaction */ double comov_nu = rpacket_get_nu (packet) * rpacket_doppler_factor (packet, storage); /* Move the packet to the place of absorption, select a direction for re-emission and impose energy conservation in the co-moving frame. */ move_packet (packet, storage, distance); double old_doppler_factor = rpacket_doppler_factor (packet, storage); rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0); double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); double comov_energy = rpacket_get_energy (packet) * old_doppler_factor; rpacket_set_energy (packet, comov_energy * inverse_doppler_factor); storage->last_interaction_type[rpacket_get_id (packet)] = 3; // last interaction was a bf-absorption storage->last_line_interaction_in_id[rpacket_get_id (packet)] = ccontinuum; // Convert the rpacket to thermal or ionization energy zrand = rk_double (mt_state); int64_t activate_level = (zrand < storage->continuum_list_nu[ccontinuum] / comov_nu) ? storage->cont_edge2macro_level[ccontinuum] : storage->kpacket2macro_level; rpacket_set_macro_atom_activation_level (packet, activate_level); macro_atom (packet, storage, mt_state); } void montecarlo_free_free_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state) { /* Move the packet to the place of absorption, select a direction for re-emission and impose energy conservation in the co-moving frame. */ move_packet (packet, storage, distance); double old_doppler_factor = rpacket_doppler_factor (packet, storage); rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0); double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); double comov_energy = rpacket_get_energy (packet) * old_doppler_factor; rpacket_set_energy (packet, comov_energy * inverse_doppler_factor); storage->last_interaction_type[rpacket_get_id (packet)] = 4; // last interaction was a ff-absorption // Create a k-packet rpacket_set_macro_atom_activation_level (packet, storage->kpacket2macro_level); macro_atom (packet, storage, mt_state); } double sample_nu_free_free (const rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state) { int64_t shell_id = rpacket_get_current_shell_id (packet); double T = storage->t_electrons[shell_id]; double zrand = rk_double (mt_state); return -KB * T / H * log(zrand); // Lucy 2003 MC II Eq.41 } double sample_nu_free_bound (const rpacket_t * packet, const storage_model_t * storage, rk_state *mt_state) { int64_t continuum_id = rpacket_get_current_continuum_id (packet); double th_frequency = storage->continuum_list_nu[continuum_id]; int64_t shell_id = rpacket_get_current_shell_id (packet); double T = storage->t_electrons[shell_id]; double zrand = rk_double (mt_state); return th_frequency * (1 - (KB * T / H / th_frequency * log(zrand))); // Lucy 2003 MC II Eq.26 } void montecarlo_line_scatter (rpacket_t * packet, storage_model_t * storage, double distance, rk_state *mt_state) { uint64_t next_line_id = rpacket_get_next_line_id (packet); uint64_t line2d_idx = next_line_id + storage->no_of_lines * rpacket_get_current_shell_id (packet); if (rpacket_get_virtual_packet (packet) == 0) { increment_j_blue_estimator (packet, storage, distance, line2d_idx); increment_Edotlu_estimator (packet, storage, distance, line2d_idx); } double tau_line = storage->line_lists_tau_sobolevs[line2d_idx]; double tau_continuum = rpacket_get_chi_continuum(packet) * distance; double tau_combined = tau_line + tau_continuum; //rpacket_set_next_line_id (packet, rpacket_get_next_line_id (packet) + 1); if (next_line_id + 1 == storage->no_of_lines) { rpacket_set_last_line (packet, true); } if (rpacket_get_virtual_packet (packet) > 0) { rpacket_set_tau_event (packet, rpacket_get_tau_event (packet) + tau_line); rpacket_set_next_line_id (packet, next_line_id + 1); test_for_close_line (packet, storage); } else if (rpacket_get_tau_event (packet) < tau_combined) { // Line absorption occurs move_packet (packet, storage, distance); double old_doppler_factor = rpacket_doppler_factor (packet, storage); rpacket_set_mu (packet, 2.0 * rk_double (mt_state) - 1.0); double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); double comov_energy = rpacket_get_energy (packet) * old_doppler_factor; rpacket_set_energy (packet, comov_energy * inverse_doppler_factor); storage->last_interaction_in_nu[rpacket_get_id (packet)] = rpacket_get_nu (packet); storage->last_line_interaction_in_id[rpacket_get_id (packet)] = next_line_id; storage->last_line_interaction_shell_id[rpacket_get_id (packet)] = rpacket_get_current_shell_id (packet); storage->last_interaction_type[rpacket_get_id (packet)] = 2; if (storage->line_interaction_id == 0) { line_emission (packet, storage, next_line_id, mt_state); } else if (storage->line_interaction_id >= 1) { rpacket_set_macro_atom_activation_level (packet, storage->line2macro_level_upper[next_line_id]); macro_atom (packet, storage, mt_state); } } else { // Packet passes line without interacting rpacket_set_tau_event (packet, rpacket_get_tau_event (packet) - tau_line); rpacket_set_next_line_id (packet, next_line_id + 1); packet->compute_chi_bf = false; test_for_close_line (packet, storage); } } void line_emission (rpacket_t * packet, storage_model_t * storage, int64_t emission_line_id, rk_state *mt_state) { double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); storage->last_line_interaction_out_id[rpacket_get_id (packet)] = emission_line_id; if (storage->cont_status == CONTINUUM_ON) { storage->last_interaction_out_type[rpacket_get_id (packet)] = 2; } rpacket_set_nu (packet, storage->line_list_nu[emission_line_id] * inverse_doppler_factor); rpacket_set_nu_line (packet, storage->line_list_nu[emission_line_id]); rpacket_set_next_line_id (packet, emission_line_id + 1); rpacket_reset_tau_event (packet, mt_state); if (rpacket_get_virtual_packet_flag (packet) > 0) { bool virtual_close_line = false; if (!rpacket_get_last_line (packet) && fabs (storage->line_list_nu[rpacket_get_next_line_id (packet)] - rpacket_get_nu_line (packet)) < (rpacket_get_nu_line (packet)* 1e-7)) { virtual_close_line = true; } // QUESTIONABLE!!! bool old_close_line = rpacket_get_close_line (packet); rpacket_set_close_line (packet, virtual_close_line); montecarlo_one_packet (storage, packet, 1, mt_state); rpacket_set_close_line (packet, old_close_line); virtual_close_line = false; } test_for_close_line (packet, storage); } void test_for_close_line (rpacket_t * packet, const storage_model_t * storage) { if (!rpacket_get_last_line (packet) && fabs (storage->line_list_nu[rpacket_get_next_line_id (packet)] - rpacket_get_nu_line (packet)) < (rpacket_get_nu_line (packet)* 1e-7)) { rpacket_set_close_line (packet, true); } } void continuum_emission (rpacket_t * packet, storage_model_t * storage, rk_state *mt_state, pt2sample_nu sample_nu_continuum, int64_t emission_type_id) { double inverse_doppler_factor = 1.0 / rpacket_doppler_factor (packet, storage); double nu_comov = sample_nu_continuum (packet, storage, mt_state); rpacket_set_nu (packet, nu_comov * inverse_doppler_factor); rpacket_reset_tau_event (packet, mt_state); storage->last_interaction_out_type[rpacket_get_id (packet)] = emission_type_id; // Have to find current position in line list int64_t current_line_id; line_search (storage->line_list_nu, nu_comov, storage->no_of_lines, &current_line_id); bool last_line = (current_line_id == storage->no_of_lines); rpacket_set_last_line (packet, last_line); rpacket_set_next_line_id (packet, current_line_id); if (rpacket_get_virtual_packet_flag (packet) > 0) { montecarlo_one_packet (storage, packet, 1, mt_state); } } static void montecarlo_compute_distances (rpacket_t * packet, storage_model_t * storage) { // Check if the last line was the same nu as the current line. if (rpacket_get_close_line (packet)) { // If so set the distance to the line to 0.0 rpacket_set_d_line (packet, 0.0); // Reset close_line. rpacket_set_close_line (packet, false); } else { compute_distance2boundary (packet, storage); compute_distance2line (packet, storage); // FIXME MR: return status of compute_distance2line() is ignored compute_distance2continuum (packet, storage); } } montecarlo_event_handler_t get_event_handler (rpacket_t * packet, storage_model_t * storage, double *distance, rk_state *mt_state) { montecarlo_compute_distances (packet, storage); double d_boundary = rpacket_get_d_boundary (packet); double d_continuum = rpacket_get_d_continuum (packet); double d_line = rpacket_get_d_line (packet); montecarlo_event_handler_t handler; if (d_line <= d_boundary && d_line <= d_continuum) { *distance = d_line; handler = &montecarlo_line_scatter; } else if (d_boundary <= d_continuum) { *distance = d_boundary; handler = &move_packet_across_shell_boundary; } else { *distance = d_continuum; handler = montecarlo_continuum_event_handler (packet, storage, mt_state); } return handler; } montecarlo_event_handler_t montecarlo_continuum_event_handler (rpacket_t * packet, storage_model_t * storage, rk_state *mt_state) { if (storage->cont_status) { double zrand_x_chi_cont = rk_double (mt_state) * rpacket_get_chi_continuum (packet); double chi_th = rpacket_get_chi_electron (packet); double chi_bf = rpacket_get_chi_boundfree (packet); if (zrand_x_chi_cont < chi_th) { return &montecarlo_thomson_scatter; } else if (zrand_x_chi_cont < chi_th + chi_bf) { return &montecarlo_bound_free_scatter; } else { return &montecarlo_free_free_scatter; } } else { return &montecarlo_thomson_scatter; } } int64_t montecarlo_one_packet_loop (storage_model_t * storage, rpacket_t * packet, int64_t virtual_packet, rk_state *mt_state) { rpacket_set_tau_event (packet, 0.0); rpacket_set_nu_line (packet, 0.0); rpacket_set_virtual_packet (packet, virtual_packet); rpacket_set_status (packet, TARDIS_PACKET_STATUS_IN_PROCESS); // Initializing tau_event if it's a real packet. if (virtual_packet == 0) { rpacket_reset_tau_event (packet,mt_state); } // For a virtual packet tau_event is the sum of all the tau's that the packet passes. while (rpacket_get_status (packet) == TARDIS_PACKET_STATUS_IN_PROCESS) { // Check if we are at the end of line list. if (!rpacket_get_last_line (packet)) { rpacket_set_nu_line (packet, storage-> line_list_nu[rpacket_get_next_line_id (packet)]); } double distance; get_event_handler (packet, storage, &distance, mt_state) (packet, storage, distance, mt_state); if (virtual_packet > 0 && rpacket_get_tau_event (packet) > 10.0) { rpacket_set_tau_event (packet, 100.0); rpacket_set_status (packet, TARDIS_PACKET_STATUS_EMITTED); } } if (virtual_packet > 0) { rpacket_set_energy (packet, rpacket_get_energy (packet) * exp (-1.0 * rpacket_get_tau_event (packet))); } return rpacket_get_status (packet) == TARDIS_PACKET_STATUS_REABSORBED ? 1 : 0; } void montecarlo_main_loop(storage_model_t * storage, int64_t virtual_packet_flag, int nthreads, unsigned long seed) { int64_t finished_packets = 0; storage->virt_packet_count = 0; #ifdef WITH_VPACKET_LOGGING storage->virt_packet_nus = (double *)safe_malloc(sizeof(double) * storage->no_of_packets); storage->virt_packet_energies = (double *)safe_malloc(sizeof(double) * storage->no_of_packets); storage->virt_packet_last_interaction_in_nu = (double *)safe_malloc(sizeof(double) * storage->no_of_packets); storage->virt_packet_last_interaction_type = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets); storage->virt_packet_last_line_interaction_in_id = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets); storage->virt_packet_last_line_interaction_out_id = (int64_t *)safe_malloc(sizeof(int64_t) * storage->no_of_packets); storage->virt_array_size = storage->no_of_packets; #endif // WITH_VPACKET_LOGGING #ifdef WITHOPENMP omp_set_dynamic(0); if (nthreads > 0) { omp_set_num_threads(nthreads); } #pragma omp parallel firstprivate(finished_packets) { rk_state mt_state; rk_seed (seed + omp_get_thread_num(), &mt_state); #pragma omp master { fprintf(stderr, "Running with OpenMP - %d threads\n", omp_get_num_threads()); print_progress(0, storage->no_of_packets); } #else rk_state mt_state; rk_seed (seed, &mt_state); fprintf(stderr, "Running without OpenMP\n"); #endif int64_t chi_bf_tmp_size = (storage->cont_status) ? storage->no_of_edges : 0; double *chi_bf_tmp_partial = safe_malloc(sizeof(double) * chi_bf_tmp_size); #pragma omp for for (int64_t packet_index = 0; packet_index < storage->no_of_packets; ++packet_index) { int reabsorbed = 0; rpacket_t packet; rpacket_set_id(&packet, packet_index); rpacket_init(&packet, storage, packet_index, virtual_packet_flag, chi_bf_tmp_partial); if (virtual_packet_flag > 0) { reabsorbed = montecarlo_one_packet(storage, &packet, -1, &mt_state); } reabsorbed = montecarlo_one_packet(storage, &packet, 0, &mt_state); storage->output_nus[packet_index] = rpacket_get_nu(&packet); if (reabsorbed == 1) { storage->output_energies[packet_index] = -rpacket_get_energy(&packet); } else { storage->output_energies[packet_index] = rpacket_get_energy(&packet); } if ( ++finished_packets%100 == 0 ) { #ifdef WITHOPENMP // WARNING: This only works with a static sheduler and gives an approximation of progress. // The alternative would be to have a shared variable but that could potentially decrease performance when using many threads. if (omp_get_thread_num() == 0 ) print_progress(finished_packets * omp_get_num_threads(), storage->no_of_packets); #else print_progress(finished_packets, storage->no_of_packets); #endif } } free(chi_bf_tmp_partial); #ifdef WITHOPENMP } #endif print_progress(storage->no_of_packets, storage->no_of_packets); fprintf(stderr,"\n"); }
estimate_time_step.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // // Main authors: Kazem Kamran // Jordi Rubio // #if !defined(KRATOS_ESTIMATE_TIME_STEP ) #define KRATOS_ESTIMATE_TIME_STEP // System includes #include <string> #include <iostream> #include <algorithm> #include <cmath> // Added by Jordi Rubio // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/node.h" #include "utilities/geometry_utilities.h" //#include "geometries/tetrahedra_3d_4.h" #include "geometries/point.h" #include "thermo_mechanical_application.h" #include "includes/c2c_variables.h" // #include "custom_conditions/environment_contact.h" //#include "includes/variables.h" #include "utilities/openmp_utils.h" #include "includes/convection_diffusion_settings.h" namespace Kratos { template<unsigned int TDim> class EstimateTimeStep { public: KRATOS_CLASS_POINTER_DEFINITION(EstimateTimeStep<TDim>); //********************************************************************************************** //********************************************************************************************** // double ComputeDt(ModelPart& ThisModelPart, const double dist_max, const double CFL, const double dt_min ,const double dt_max ) { KRATOS_TRY const unsigned int NumNodes = TDim +1; int NumThreads = OpenMPUtils::GetNumThreads(); OpenMPUtils::PartitionVector ElementPartition; OpenMPUtils::DivideInPartitions(ThisModelPart.NumberOfElements(),NumThreads,ElementPartition); std::vector<double> MaxProj(NumThreads,0.0); // NumThreads = 1; #pragma omp parallel shared(MaxProj) { int k = OpenMPUtils::ThisThread(); ModelPart::ElementIterator ElemBegin = ThisModelPart.ElementsBegin() + ElementPartition[k]; ModelPart::ElementIterator ElemEnd = ThisModelPart.ElementsBegin() + ElementPartition[k+1]; double& rMaxProj = MaxProj[k]; double Area; array_1d<double, NumNodes> N; array_1d<double, NumNodes> dist_vec; BoundedMatrix<double, NumNodes, TDim> DN_DX; for( ModelPart::ElementIterator itElem = ElemBegin; itElem != ElemEnd; ++itElem) { // Get the element's geometric parameters Geometry< Node<3> >& rGeom = itElem->GetGeometry(); double ele_dist = 0.0; for (unsigned int kk = 0; kk < rGeom.size(); kk++){ double dist = rGeom[kk].FastGetSolutionStepValue(DISTANCE); dist_vec[kk] = dist; ele_dist += fabs(dist); } ele_dist /= NumNodes; if(ele_dist <= dist_max) { GeometryUtils::CalculateGeometryData(rGeom, DN_DX, N, Area); // Elemental Velocity array_1d<double,TDim> ElementVel = N[0]*itElem->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY); for (unsigned int i = 1; i < NumNodes; ++i) noalias(ElementVel) += N[i]*rGeom[i].FastGetSolutionStepValue(VELOCITY); //compute normal velocity array_1d<double, TDim> grad_dist = prod(trans(DN_DX),dist_vec); double norm_grad_dist = norm_2(grad_dist); //grad_dist[0]*grad_dist[0] + grad_dist[1]*grad_dist[1] + grad_dist[2]*grad_dist[2]; // norm_grad_dist = sqrt(norm_grad_dist); double normal_speed = inner_prod(ElementVel,grad_dist); if(norm_grad_dist > 0.0) { normal_speed /= norm_grad_dist; noalias(ElementVel) = (normal_speed/norm_grad_dist)*grad_dist; } else noalias(ElementVel) = ZeroVector(3); // // Velocity norm // double VelNorm = ElementVel[0]*ElementVel[0]; // for (unsigned int d = 1; d < TDim; ++d) // VelNorm += ElementVel[d]*ElementVel[d]; // VelNorm = sqrt(VelNorm); // Maximum element size along the direction of velocity for (unsigned int i = 0; i < NumNodes; ++i) { double Proj = 0.0; for (unsigned int d = 0; d < TDim; ++d) Proj += ElementVel[d]*DN_DX(i,d); Proj = fabs(Proj); if (Proj > rMaxProj) rMaxProj = Proj; } } } } // Obtain the maximum projected element size (compare thread results) double Max = 0.0; for (int k = 0; k < NumThreads; ++k) if (Max < MaxProj[k]) Max = MaxProj[k]; // Dt to obtain desired CFL double dt = CFL / Max; if(dt > dt_max) dt = dt_max; else if(dt < dt_min) dt = dt_min; //perform mpi sync if needed double global_dt = dt; ThisModelPart.GetCommunicator().MinAll(global_dt); dt = global_dt; return dt; KRATOS_CATCH("") } /* Compute solidificatio nand cooling DT */ //******************************************************************* //************ COMPUTE SOLIDIFICATION DT ******************* //******************************************************************* double ComputeSolidificationCoolingDt(ModelPart& ThisModelPart, const double solidification_percent, const double max_cooling_delta_temp, const double change_in_shrinkage, const double limit_of_mushy_zone, const bool improve_solidification_tracking, const double dt_min, const double dt_max) { KRATOS_TRY // const int NumNodes = TDim +1; // is_cold = 0; const double current_dt = ThisModelPart.GetProcessInfo()[DELTA_TIME]; const int is_solidified = ThisModelPart.GetProcessInfo()[IS_SOLIDIFIED]; //const bool improve_solidification_tracking = true; const double low_boundary_over_mushy_zone = 5.0; int global_is_solidified = is_solidified; // ThisModelPart.GetCommunicator().MinAll(global_is_solidified); //********************************** //**** NOT ALL NODES ARE LIQUID **** //********************************** if(global_is_solidified == 0) { //********************************************************************** //**** CHECK IF ALL NODES ARE OVER LIQUIDUS TEMPERATURE **** //********************************************************************** //pre solidification Dt int is_hot = CheckMaxTemperature(ThisModelPart); if( is_hot == 1 ) { //************************************** //**** WHEN EVERYTHING IS LIQUID **** //************************************** // if so, then use a maximum cooling objective of 10.0 double max_presolodification_delta_tem = std::min(10.0,max_cooling_delta_temp); int node_size = ThisModelPart.Nodes().size(); double max_delta_temp = 0.0; std::vector<double> mdelta(OpenMPUtils::GetNumThreads(),0.0); #pragma omp parallel for shared(mdelta) for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); double old_temp = it->FastGetSolutionStepValue(TEMPERATURE,1); // Get the Maximum on each thread //max_delta_temp=std::max(-current_temp + old_temp,max_delta_temp); double& md = mdelta[OpenMPUtils::ThisThread()]; md= std::max(-current_temp + old_temp, md); } //workaround because VS does not support omp 4.0 for (int i = 0; i < OpenMPUtils::GetNumThreads(); i++) { max_delta_temp = std::max(max_delta_temp, mdelta[i]); } ThisModelPart.GetCommunicator().MaxAll(max_delta_temp); // Now we can keep on if( max_delta_temp > 0.0 ) { double new_delta_time = std::min(1.5, max_presolodification_delta_tem / max_delta_temp); // new_delta_time *= current_dt; // new_delta_time = 1.5*current_dt; // Previous transformationn if( new_delta_time > dt_max) new_delta_time = dt_max; else if( new_delta_time < dt_min) new_delta_time = dt_min; return new_delta_time; } else { return current_dt; } } else//solidification Dt { //************************************** //**** WHEN NOT EVERYTHING IS LIQUID **** //************************************** double current_solidified_volume = 0.0; double old_solidified_volume = 0.0; double current_over_mushy_zone=0.0 ; double old_over_mushy_zone=0.0; double tot_vol = 0.0; std::vector<double> mdelta(OpenMPUtils::GetNumThreads(),0.0); //double max_delta_temp=0.0; int node_size = ThisModelPart.Nodes().size(); #pragma omp parallel for reduction(+:current_solidified_volume,old_solidified_volume, current_over_mushy_zone, old_over_mushy_zone,tot_vol) for (int ii = 0; ii < node_size; ii++) { // Now we look for the Solidifcation Volume ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double vol = it->GetValue(NODAL_VOLUME); double& md= mdelta[OpenMPUtils::ThisThread()]; if (vol > md) { md = vol; } double current_S = it->FastGetSolutionStepValue(SOLIDFRACTION); double old_S = it->FastGetSolutionStepValue(SOLIDFRACTION,1); if(current_S>=limit_of_mushy_zone) { current_over_mushy_zone+= vol; } if(old_S>=limit_of_mushy_zone) { old_over_mushy_zone+= vol; } current_solidified_volume += vol*current_S; old_solidified_volume += vol*old_S; tot_vol += vol; //filling solidifiacation time //double is_visited = it->FastGetSolutionStepValue(IS_VISITED); //if(is_visited == 0.0 && current_S == 1.0){ // it->FastGetSolutionStepValue(IS_VISITED) = 1.0; //double solid_time = ThisModelPart.GetProcessInfo()[TIME]; //double modulus = ThisModelPart.GetProcessInfo()[K0]; //it->FastGetSolutionStepValue(SOLIDIF_TIME) = solid_time; //it->FastGetSolutionStepValue(SOLIDIF_MODULUS) = modulus*sqrt(solid_time); //} // Now for the maximum change in temperature //double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); //double old_temp = it->FastGetSolutionStepValue(TEMPERATURE,1); // max_delta_temp=std::max(-current_temp + old_temp,max_delta_temp); } //workaround because VS does not support omp 4.0 double max_nodal_volume; for (int i = 0; i < OpenMPUtils::GetNumThreads(); i++) { max_nodal_volume = std::max(max_nodal_volume, mdelta[i]); } ThisModelPart.GetCommunicator().SumAll(current_solidified_volume); ThisModelPart.GetCommunicator().SumAll(old_solidified_volume); ThisModelPart.GetCommunicator().SumAll(tot_vol); ThisModelPart.GetCommunicator().SumAll(current_over_mushy_zone); ThisModelPart.GetCommunicator().SumAll(old_over_mushy_zone); ThisModelPart.GetCommunicator().MaxAll(max_nodal_volume); if(tot_vol == 0.0) KRATOS_THROW_ERROR(std::logic_error, "inside ComputeSolidificationCoolingDt: total volume is zero!", "") if(current_solidified_volume >= tot_vol) { ThisModelPart.GetProcessInfo()[IS_SOLIDIFIED] = 1; return current_dt; } else { double delta_solid = current_solidified_volume - old_solidified_volume; double delta_over_mushy_zone=current_over_mushy_zone-old_over_mushy_zone; if( delta_solid > 0.0 || delta_over_mushy_zone > 0.0 ) { delta_solid /= tot_vol; delta_over_mushy_zone /= tot_vol; if(delta_solid<=0.0){delta_solid=delta_over_mushy_zone*solidification_percent/change_in_shrinkage;} //It sets the value so that in next step we get exactly the same value double solidification_ratio = solidification_percent / delta_solid; double limited_change_in_shrinkage_ratio = 0.0; if (delta_over_mushy_zone <= 0.0) { delta_over_mushy_zone = delta_solid*change_in_shrinkage / solidification_percent; // It sets the value so that in next step we get exactly the same value limited_change_in_shrinkage_ratio = change_in_shrinkage; } else { if (improve_solidification_tracking == true) { double lower_limit = (max_nodal_volume/ tot_vol)*low_boundary_over_mushy_zone; double liquid_percent = 1.00 - (current_over_mushy_zone / tot_vol); limited_change_in_shrinkage_ratio = std::min(change_in_shrinkage, liquid_percent*0.5);//delta_over_mushy_zone*0.8); limited_change_in_shrinkage_ratio = std::max(limited_change_in_shrinkage_ratio, lower_limit); KRATOS_WATCH(lower_limit) KRATOS_WATCH(change_in_shrinkage) KRATOS_WATCH(limited_change_in_shrinkage_ratio) } else { limited_change_in_shrinkage_ratio = change_in_shrinkage; } } double change_in_shrinkage_ratio= limited_change_in_shrinkage_ratio / delta_over_mushy_zone; double K = std::min(solidification_ratio, change_in_shrinkage_ratio); double new_dt = std::min(1.5, K ) * current_dt; if( new_dt > dt_max) new_dt = dt_max; else if( new_dt < dt_min) new_dt = dt_min; return new_dt; } else { return current_dt; } } } } else //coling delta_t { //double cooling_dt_max = dt_max;//30.0*dt_max; int node_size = ThisModelPart.Nodes().size(); double max_delta_temp = 0.0; for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); double old_temp = it->FastGetSolutionStepValue(TEMPERATURE,1); max_delta_temp=std::max(-current_temp+old_temp,max_delta_temp); } ThisModelPart.GetCommunicator().MaxAll(max_delta_temp); if( max_delta_temp > 0.0 ){ double new_delta_time = max_cooling_delta_temp / max_delta_temp; new_delta_time *= current_dt; if( new_delta_time > dt_max) new_delta_time = dt_max; else if( new_delta_time < dt_min) new_delta_time = dt_min; return new_delta_time; } else { // is_cold = 1; return current_dt; } } KRATOS_CATCH("") } //************************************************************************************************ //*************** FIND AN ESTIMATION FOR SOLIDIFICATION TIME. NO VIRTUAL MOLD ******************* //************************************************************************************************ double EstimateSolidificationTimeNoVirtualMould(ModelPart& ThisModelPart) { KRATOS_TRY double solidification_time = 0.0; const double density = ThisModelPart.GetProcessInfo()[DENSITY]; const double cc= ThisModelPart.GetProcessInfo()[SPECIFIC_HEAT]; const double htc= ThisModelPart.GetProcessInfo()[HTC]; const double mould_temperature=ThisModelPart.GetProcessInfo()[MOLD_AVERAGE_TEMPERATURE]; const double TT_solid = ThisModelPart.GetProcessInfo()[SOLID_TEMPERATURE]; const double TT_liquid = ThisModelPart.GetProcessInfo()[FLUID_TEMPERATURE]; const double LL = ThisModelPart.GetProcessInfo()[LATENT_HEAT]; double tot_vol = 0.0; double tot_area = 0.0; int node_size = ThisModelPart.Nodes().size(); for (int ii = 0; ii < node_size; ii++) // Compute Part Volume and Area { ModelPart::NodesContainerType::iterator it_nd = ThisModelPart.NodesBegin() + ii; double vol = it_nd->GetValue(NODAL_VOLUME); tot_vol += vol; double area = it_nd->FastGetSolutionStepValue(NODAL_PAUX); tot_area += area; } // Check Area is not 0 if ( tot_area == 0.0 || tot_vol == 0.0) KRATOS_THROW_ERROR(std::invalid_argument,"AREA or VOLUME is Zero", ""); // Formula for stimating solidification time solidification_time = density * ( cc * ( TT_liquid - TT_solid) + LL) / (htc * 0.5*(TT_solid-mould_temperature)); solidification_time *= pow(tot_vol/tot_area , 0.8); return solidification_time; KRATOS_CATCH("") } //************************************************************************************************ //**************** FIND AN ESTIMATION FOR SOLIDIFICATION TIME. VIRTUAL MOLD ********************* //************************************************************************************************ /* For solving this we are going to suppose that we dissipate all the energy through the mould outer surface. We Estimate the inner Energy of the System as the SUM of 3 contributions. The energy loss needed to cool the mart, the energy loss needed to make the part chage its phase and the energy needed to cool the mould. The contribution of the mould only is considered if positive. All terms are linearized with respect to the temperature, so that. E_1=V_{part}*C_{part}*\rho_{part}*T E_2=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end}))*T E_3=LH*\rho*V_{part}*(T-T_{end})/(T_{ini}-T_{end}) Now we have that, the q (Energy time derivative is) dE/dt=HTC_{env}*Sfact*A_{part}*(T-T_{env}) We can set it as ODE, and solve analytacally (recall this is a linealization, but will be enough for our purpose) dE_1/dT=V_{part}*C_{part}*\rho_{part} dE_2/dT=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end})) dE_3/dT=LH*\rho*V_{part}/(T_{ini}-T_{end}) Solving the ODE,we have that: \Delta t= =( (dE_1/dT+dE_2/dT+dE_2/dT)/ HTC_{env}*Sfact*A_{part} )*ln( ((T_{ini}- T_{env})/(T_{end}- T_{env}) ) As starting temperature we suppose the Average temperature, and as initial mould temperature, we suppose the initial mouls temperature */ double EstimateSolidificationTime(ModelPart& ThisModelPart) { KRATOS_TRY double solidification_time = 0.0; // Auxiliaty variables double dE1=0.0; double dE2=0.0; double dE3=0.0; double DENOM=0.0; // Environment and part variables const double ambient_temperature=ThisModelPart.GetProcessInfo()[AMBIENT_TEMPERATURE]; const double LL = ThisModelPart.GetProcessInfo()[LATENT_HEAT]; const double density = ThisModelPart.GetProcessInfo()[DENSITY]; const double cc= ThisModelPart.GetProcessInfo()[SPECIFIC_HEAT]; const double initial_temperature= ThisModelPart.GetProcessInfo()[AVERAGE_TEMPERATURE]; const double stop_temperature= ThisModelPart.GetProcessInfo()[SOLID_TEMPERATURE]; // Loop Over the nodes - Compute E1 term double tot_vol = 0.0; int node_size = ThisModelPart.Nodes().size(); for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it_nd = ThisModelPart.NodesBegin() + ii; double vol = it_nd->GetValue(NODAL_VOLUME); tot_vol += vol; vol=pow(vol,1.0); // dE1 - First Term //dE_1/dT=V_{part}*C_{part}*\rho_{part} dE1+= vol*density*cc; // dE3 - Third Term //dE_3/dT=LH*\rho*V_{part}/(T_{ini}-T_{end}) dE3+=LL*density*vol/(initial_temperature-stop_temperature); } double tot_area=0.0; double avg_conductivity=0.0; double avg_density=0.0; double avg_sheat=0.0; // Loop over the conditions Compute E2, E3 and Denom term for (ModelPart::ConditionIterator itCond = ThisModelPart.ConditionsBegin(); itCond != ThisModelPart.ConditionsEnd(); itCond++ ) { // Generate the Geometry of the condition Condition::GeometryType& rGeom = itCond->GetGeometry(); const double mould_density= itCond->GetProperties()[MOLD_DENSITY]; const double mould_specific_heat= itCond->GetProperties()[MOLD_SPECIFIC_HEAT]; const double mould_thickness = itCond->GetProperties()[MOLD_THICKNESS]; const double mould_vfact= itCond->GetProperties()[MOLD_VFACT]; const double mould_sfact= itCond->GetProperties()[MOLD_SFACT]; const double mould_htc_env= itCond->GetProperties()[MOLD_HTC_ENVIRONMENT]; const double mould_cond=itCond->GetProperties()[MOLD_CONDUCTIVITY]; //const double mould_conductivity = itCond->GetProperties()[MOLD_CONDUCTIVITY]; const double mould_temperature = itCond->GetProperties()[MOLD_TEMPERATURE]; double tarea=rGeom.DomainSize(); const double condition_area=pow(tarea,1.0); tot_area+=tarea; // dE2 - Second Term //dE_2/dT=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end})) double aux =condition_area*mould_thickness*mould_vfact*mould_density*mould_specific_heat; double aux2=(mould_temperature- stop_temperature)/(initial_temperature-stop_temperature ) ; dE2+=std::max(aux*aux2,0.0); // Denom. // HTC_{env}*Sfact*A_{part} ) DENOM+= mould_htc_env*condition_area*mould_sfact; // To be used by Chorinov Formulation avg_conductivity+=mould_cond*tarea; avg_density+=mould_density*tarea; avg_sheat+=mould_specific_heat*tarea; } solidification_time = ((dE1+dE2+dE3)/DENOM)*log( (initial_temperature-ambient_temperature)/(stop_temperature-ambient_temperature) ); // Now we will compute Chorinov's Rule avg_conductivity/=tot_area; avg_density/=tot_area; avg_sheat/=tot_area; double solidification_time_chorinov=0.0; //const double htc= ThisModelPart.GetProcessInfo()[HTC]; //const double mould_temperature=ThisModelPart.GetProcessInfo()[MOLD_AVERAGE_TEMPERATURE]; solidification_time_chorinov=pow(density*LL/fabs(initial_temperature-stop_temperature),2)*(3.1416/(4*avg_conductivity*avg_density*avg_sheat)); solidification_time_chorinov*=1+(cc*pow((initial_temperature-stop_temperature)/LL,2)); solidification_time_chorinov*=pow(tot_vol/tot_area,1.5); return std::max(solidification_time,solidification_time_chorinov); KRATOS_CATCH("") } double CheckStopTemperature(ModelPart& ThisModelPart,const double stop_temperature) { KRATOS_TRY const double avg_temp = ThisModelPart.GetProcessInfo()[AVERAGE_TEMPERATURE]; double delta_max_temp = avg_temp - stop_temperature; double sum_temp = 0.0; int node_size = ThisModelPart.Nodes().size(); #pragma omp parallel for reduction(+:sum_temp) for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it_nd = ThisModelPart.NodesBegin() + ii; double temp = it_nd->FastGetSolutionStepValue(TEMPERATURE); sum_temp += std::max(temp,0.99999*stop_temperature); // before temp } sum_temp /= double(node_size); sum_temp -= stop_temperature; double cooled_percent = 100.0*(1.0 - sum_temp/delta_max_temp); return cooled_percent; KRATOS_CATCH("") } //********************************************************************************************** //********************************************************************************************** // double ComputeSurfaceWaveDt(ModelPart& ThisModelPart, const double total_volume, const double edge_size,const double max_Dt) { KRATOS_TRY const double cutted_area = ThisModelPart.GetProcessInfo()[CUTTED_AREA]; const double wet_volume = ThisModelPart.GetProcessInfo()[WET_VOLUME]; double compare_percente = 0.01; if( wet_volume < compare_percente * total_volume || cutted_area <= 0.0) return max_Dt; double empty_volume = total_volume - wet_volume; double dist_1 = empty_volume/cutted_area; double dist_2 = cutted_area/dist_1; double dist_3 = sqrt(cutted_area); double max_dist = dist_1; max_dist = (dist_1 > dist_2) ? dist_1 : dist_2; max_dist = (max_dist > dist_3) ? max_dist : dist_3; //max_dist = 5.0*dist_3; double inv_sqrt_gravity = 0.319275428; double wave_dt =inv_sqrt_gravity * edge_size/sqrt(max_dist); return ((wave_dt>max_Dt) ? max_Dt : wave_dt); KRATOS_CATCH("") } int CheckIsInTransition(ModelPart& ThisModelPart) { double const sol_temp = ThisModelPart.GetProcessInfo()[SOLID_TEMPERATURE] ; double const liq_temp = ThisModelPart.GetProcessInfo()[FLUID_TEMPERATURE] ; int is_in_range_point = 0; int node_size = ThisModelPart.Nodes().size(); for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); if( current_temp >sol_temp && current_temp<liq_temp){ is_in_range_point = 1; break; } } ThisModelPart.GetCommunicator().MaxAll(is_in_range_point); return (is_in_range_point==1)? 1 : 0; } //********************************************************************************************** //********************************************************************************************** // double EstimateCoolingTime(ModelPart& ThisModelPart,const double stop_temperature) { /* For solving this we are going to suppose that we dissipate all the energy through the mould outer surface. We Estimate the inner Energy of the System as the SUM of 3 contributions. The energy loss needed to cool the mart, the energy loss needed to make the part chage its phase and the energy needed to cool the mould. The contribution of the mould only is considered if positive. All terms are linearized with respect to the temperature, so that. E_1=V_{part}*C_{part}*\rho_{part}*T E_2=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end}))*T E_3=LH*\rho*V_{part}*(T-T_{end})/(T_{ini}-T_{end}) Now we have that, the q (Energy time derivative is) dE/dt=HTC_{env}*Sfact*A_{part}*(T-T_{env}) We can set it as ODE, and solve analytacally (recall this is a linealization, but will be enough for our purpose) dE_1/dT=V_{part}*C_{part}*\rho_{part} dE_2/dT=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end})) dE_3/dT=LH*\rho*V_{part}/(T_{ini}-T_{end}) Solving the ODE,we have that: \Delta t= =( (dE_1/dT+dE_2/dT+dE_2/dT)/ HTC_{env}*Sfact*A_{part} )*ln( ((T_{ini}- T_{env})/(T_{end}- T_{env}) ) As starting temperature we suppose the Average temperature, and as initial mould temperature, we suppose the initial mouls temperature */ // Auxiliaty variables double CoolingTime; double dE1=0.0; double dE2=0.0; double dE3=0.0; double DENOM=0.0; // Environment and part variables const double ambient_temperature=ThisModelPart.GetProcessInfo()[AMBIENT_TEMPERATURE]; const double LL = ThisModelPart.GetProcessInfo()[LATENT_HEAT]; const double density = ThisModelPart.GetProcessInfo()[DENSITY]; const double cc= ThisModelPart.GetProcessInfo()[SPECIFIC_HEAT]; const double initial_temperature= ThisModelPart.GetProcessInfo()[AVERAGE_TEMPERATURE]; // Loop Over the nodes - Compute E1 term double tot_vol = 0.0; int node_size = ThisModelPart.Nodes().size(); for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it_nd = ThisModelPart.NodesBegin() + ii; double vol = it_nd->GetValue(NODAL_VOLUME); tot_vol += vol; vol=pow(vol,0.8); // dE1 - First Term //dE_1/dT=V_{part}*C_{part}*\rho_{part} dE1+= vol*density*cc; // dE3 - Third Term //dE_3/dT=LH*\rho*V_{part}/(T_{ini}-T_{end}) dE3+=LL*density*vol/(initial_temperature-stop_temperature); } double tot_area=0.0; double avg_conductivity=0.0; double avg_density=0.0; double avg_sheat=0.0; double avg_env_htc=0.0; // Loop over the conditions Compute E2, E3 and Denom term for (ModelPart::ConditionIterator itCond = ThisModelPart.ConditionsBegin(); itCond != ThisModelPart.ConditionsEnd(); itCond++ ) { // Generate the Geometry of the condition Condition::GeometryType& rGeom = itCond->GetGeometry(); const double mould_density= itCond->GetProperties()[MOLD_DENSITY]; const double mould_specific_heat= itCond->GetProperties()[MOLD_SPECIFIC_HEAT]; const double mould_thickness = itCond->GetProperties()[MOLD_THICKNESS]; const double mould_vfact= itCond->GetProperties()[MOLD_VFACT]; const double mould_sfact= itCond->GetProperties()[MOLD_SFACT]; const double mould_htc_env= itCond->GetProperties()[MOLD_HTC_ENVIRONMENT]; const double mould_conductivity = itCond->GetProperties()[MOLD_CONDUCTIVITY]; const double mould_temperature = itCond->GetProperties()[MOLD_TEMPERATURE]; double tarea=rGeom.DomainSize(); tot_area+=tarea; const double condition_area=pow(fabs(rGeom.DomainSize()),1.0); // dE2 - Second Term //dE_2/dT=V_{mould}*V_{fact}*\rho_{mould}*C_{mould}*max(0,(T_{mould}-T_{end})/(T_{ini}-T_{end})) double aux =condition_area*mould_thickness*mould_vfact*mould_density*mould_specific_heat; double aux2=(mould_temperature- stop_temperature)/(initial_temperature-stop_temperature ) ; dE2+=std::max(aux*aux2,0.0); // Denom. // HTC_{env}*Sfact*A_{part} ) DENOM+= mould_htc_env*condition_area*mould_sfact; // To be used by Chorinov Formulation avg_conductivity+=mould_conductivity*tarea; avg_density+=mould_density*tarea; avg_sheat+=mould_specific_heat*tarea; avg_env_htc+=tarea*mould_htc_env*mould_sfact; } CoolingTime = ((dE1+dE2+dE3)/DENOM)*log( (initial_temperature-ambient_temperature)/(stop_temperature-ambient_temperature) ); // Now we will compute Chorinov's Rule avg_conductivity/=tot_area; avg_density/=tot_area; avg_sheat/=tot_area; avg_env_htc/=tot_area; double cooling_time_chorinov=0.0; //const double htc= ThisModelPart.GetProcessInfo()[HTC]; const double solid_temp= ThisModelPart.GetProcessInfo()[SOLID_TEMPERATURE]; //const double mould_temperature=ThisModelPart.GetProcessInfo()[MOLD_AVERAGE_TEMPERATURE]; cooling_time_chorinov=pow(density*LL/fabs(initial_temperature-solid_temp),2)*(3.1416/(4*avg_conductivity*avg_density*avg_sheat)); cooling_time_chorinov*=1+(cc*pow((initial_temperature-solid_temp)/LL,2)); cooling_time_chorinov*=pow(tot_vol/tot_area,2); // Now we compute the time from solidification to cooling double time_to_cool=(tot_vol*cc*density*fabs(solid_temp-stop_temperature))/(avg_env_htc*tot_area*(0.5*initial_temperature+0.5*stop_temperature-ambient_temperature)); cooling_time_chorinov+=time_to_cool; return std::max(CoolingTime,cooling_time_chorinov); } ///////////////////////////////////////////////////////////////////////// int CheckMinTemperature(ModelPart& ThisModelPart) { double last_temp = 1e9; //double is_hot_point = 1.0; int node_size = ThisModelPart.Nodes().size(); for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); if( current_temp < last_temp){last_temp = current_temp; } } ThisModelPart.GetCommunicator().MinAll(last_temp); return last_temp; } //private: // ///////////////////////////////////////////////////////////////////////////// int CheckMaxTemperature(ModelPart& ThisModelPart) { double last_temp = ThisModelPart.GetProcessInfo()[FLUID_TEMPERATURE]; //GetTable(3).Data().back().first; double is_hot_point = 1.0; int node_size = ThisModelPart.Nodes().size(); //KRATOS_WATCH(omp_get_max_threads()) std::vector<double> local_is_hot_point(OpenMPUtils::GetNumThreads(),1.0); // #pragma omp parallel for shared(local_is_hot_point) for (int ii = 0; ii < node_size; ii++) { ModelPart::NodesContainerType::iterator it = ThisModelPart.NodesBegin() + ii; double current_temp = it->FastGetSolutionStepValue(TEMPERATURE); if (current_temp < last_temp) { //is_hot_point = 0.0; local_is_hot_point[OpenMPUtils::ThisThread()]= 0.0; break; } } //Now we finf the minimum is_hot_point among threads for (int ii = 0; ii < OpenMPUtils::GetNumThreads(); ii++) { is_hot_point = std::min(is_hot_point, local_is_hot_point[ii]); } ThisModelPart.GetCommunicator().MinAll(is_hot_point); return (is_hot_point == 1.0) ? 1 : 0; } }; } // namespace Kratos. #endif // ASSIGN_NO_SLIP_CONDITION defined
deconvolution_pack1ton_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void deconvolution_pack1ton_fp16s_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; const int maxk = kernel_w * kernel_h; const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat32m2_t _sum = vfmv_v_f_f32m2(0.f, vl); if (bias_data_ptr) { _sum = vle32_v_f32m2(bias_data_ptr + p * packn, vl); } const __fp16* kptr = (const __fp16*)weight_data_fp16 + maxk * channels * p * packn; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); for (int y = 0; y < kernel_h; y++) { int sys = (i + y * dilation_h - (kernel_extent_h - 1)); if (sys < 0 || sys % stride_h != 0) continue; int sy = sys / stride_h; if (sy >= h) continue; const __fp16* sptr = m.row<const __fp16>(sy); for (int x = 0; x < kernel_w; x++) { int sxs = (j + x * dilation_w - (kernel_extent_w - 1)); if (sxs < 0 || sxs % stride_w != 0) continue; int sx = sxs / stride_w; if (sx >= w) continue; __fp16 val = sptr[sx]; int k = y * kernel_w + x; vfloat16m1_t _w = vle16_v_f16m1(kptr + k * packn, vl); _sum = vfwmacc_vf_f32m2(_sum, val, _w, vl); } } kptr += maxk * packn; } _sum = activation_ps(_sum, activation_type, activation_params, vl); vse16_v_f16m1(outptr + j * packn, vfncvt_f_f_w_f16m1(_sum, vl), vl); } outptr += outw * packn; } } } static void deconvolution_pack1ton_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; const int maxk = kernel_w * kernel_h; const __fp16* bias_data_ptr = bias_data_fp16; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat16m1_t _sum = vfmv_v_f_f16m1(0.f, vl); if (bias_data_ptr) { _sum = vle16_v_f16m1(bias_data_ptr + p * packn, vl); } const __fp16* kptr = (const __fp16*)weight_data_fp16 + maxk * channels * p * packn; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); for (int y = 0; y < kernel_h; y++) { int sys = (i + y * dilation_h - (kernel_extent_h - 1)); if (sys < 0 || sys % stride_h != 0) continue; int sy = sys / stride_h; if (sy >= h) continue; const __fp16* sptr = m.row<const __fp16>(sy); for (int x = 0; x < kernel_w; x++) { int sxs = (j + x * dilation_w - (kernel_extent_w - 1)); if (sxs < 0 || sxs % stride_w != 0) continue; int sx = sxs / stride_w; if (sx >= w) continue; __fp16 val = sptr[sx]; int k = y * kernel_w + x; vfloat16m1_t _w = vle16_v_f16m1(kptr + k * packn, vl); _sum = vfmacc_vf_f16m1(_sum, val, _w, vl); } } kptr += maxk * packn; } _sum = activation_ps(_sum, activation_type, activation_params, vl); vse16_v_f16m1(outptr + j * packn, _sum, vl); } outptr += outw * packn; } } }
ex2-parallel.c
#include <stdio.h> void primeNumbers(int n); int main(){ int n = 100000; primeNumbers(n); } void primeNumbers(int number){ int j, i = 0; int primes[number+1]; //populating array with naturals numbers for(i = 0; i<=number; i++) primes[i] = i; #pragma omp parallel { #pragma omp for schedule(guided, 2000) for(i = number; i > 0; --i){ for(j = 2; j < i; j++){ if (i % j == 0){ primes[i] = 0; break; } } } } int nOfPrimes = 0; for(i = 2; i<=number; i++){ //If number is not 0 then it is prime if (primes[i]!=0){ nOfPrimes++; // printf("%d %d\n",primes[i], nOfPrimes); } } }
dfa8.c
#include <stdio.h> #include <stdint.h> #include <string.h> #include "dfa.h" #ifdef _OPENMP #include "omp.h" #endif void r8_get_diffMC(const int col8, const word32 diff_col, const int col9, word32 diffMC_list[DIFF_MC_MAX], int *len) { int i, c1, c2, diff; int fault_list[255]; int fault_list_len = 0; int row9 = -1; /* if fault position is known */ if (col8 != -1) { row9 = (col8 + 3*col9) % 4; } /* case 1: fault in round 8 is known */ if (diff_col != 0) { diff = (int)TAKEBYTE(diff_col, row9); for (c1 = 1; c1 < 255; c1++) { c2 = diff ^ c1; if (c1 > c2) { continue; } /* fault_list_len = 127 */ fault_list[fault_list_len++] = (int)(sbox[c1] ^ sbox[c2]); } } /* case 2: unknown fault */ else { for (i = 0; i < 255; i++) { fault_list[i] = i + 1; } fault_list_len = 255; } /* construct the MC differences table */ *len = get_diff_MC(row9, fault_list, fault_list_len, diffMC_list); } void r8_find_candidates(const byte ct[16], const byte fct[16], const int row8, const int col8, const int fault, word32 candidates[4][CAND_MAX], int cand_len[4]) { byte tmp[4] = {0, 0, 0, 0}; int col9, len; word32 diffMC_list[DIFF_MC_MAX]; word32 diff_col = 0; /* fault position and value known */ if (row8 != -1 && col8 != -1 && fault != -1) { tmp[row8] = fault; mixColumn(tmp); diff_col = bytes_to_word(tmp); } for (col9 = 0; col9 < 4; col9++) { r8_get_diffMC(col8, diff_col, col9, diffMC_list, &len); cand_len[col9] = k10_cand_from_diffMC(ct, fct, col9, diffMC_list, len, candidates[col9]); } } int r8_exhaustive_search(const byte pt0[16], const byte ct0[16], const byte ct[16], const byte fct[16], const int row8, const int col8, const int fault, const word32 candidates[4][CAND_MAX], const int cand_len[4], byte masterkey[16]) { int i, j, k, l, ii; int found = 0; byte subkey10[16]; byte subkey9[16]; byte subkeys[176]; byte cttmp[16]; byte fcttmp[16]; byte ctcmp[16]; byte diff[4]; #ifdef _OPENMP #pragma omp parallel for private(subkey10,subkey9,cttmp,fcttmp,j,k,l,ii,diff) shared(found) #endif for (i = 0; i < cand_len[0]; i++) { if (found) { continue; } fprintf(stderr, "Progress: %d/%d\n", i + 1, cand_len[0]); subkey10[0] = TAKEBYTE(candidates[0][i], 0); subkey10[13] = TAKEBYTE(candidates[0][i], 1); subkey10[10] = TAKEBYTE(candidates[0][i], 2); subkey10[7] = TAKEBYTE(candidates[0][i], 3); for (j = 0; j < cand_len[1]; j++) { subkey10[4] = TAKEBYTE(candidates[1][j], 0); subkey10[1] = TAKEBYTE(candidates[1][j], 1); subkey10[14] = TAKEBYTE(candidates[1][j], 2); subkey10[11] = TAKEBYTE(candidates[1][j], 3); for (k = 0; k < cand_len[2]; k++) { subkey10[8] = TAKEBYTE(candidates[2][k], 0); subkey10[5] = TAKEBYTE(candidates[2][k], 1); subkey10[2] = TAKEBYTE(candidates[2][k], 2); subkey10[15] = TAKEBYTE(candidates[2][k], 3); for (l = 0; l < cand_len[3]; l++) { subkey10[12] = TAKEBYTE(candidates[3][l], 0); subkey10[9] = TAKEBYTE(candidates[3][l], 1); subkey10[6] = TAKEBYTE(candidates[3][l], 2); subkey10[3] = TAKEBYTE(candidates[3][l], 3); k9_from_k10(subkey10, subkey9); for (ii = 0; ii < 16; ii++) { cttmp[ii] = ct[ii] ^ subkey10[ii]; fcttmp[ii] = fct[ii] ^ subkey10[ii]; } invShiftRows(cttmp); invSubBytes(cttmp); invShiftRows(fcttmp); invSubBytes(fcttmp); for (ii = 0; ii < 16; ii++) { cttmp[ii] ^= subkey9[ii]; fcttmp[ii] ^= subkey9[ii]; } invMixColumns(cttmp); invMixColumns(fcttmp); for (ii = 0; ii < 4; ii++) { diff[ii] = invsbox[cttmp[POSITIONS[col8][ii]]] ^ invsbox[fcttmp[POSITIONS[col8][ii]]]; } invMixColumn(diff); /* tests to validate if key candidate is consistent with the fault */ if (diff[0] != 0) { if (diff[1] != 0 || diff[2] != 0 || diff[3] != 0 || row8 > 0 || (fault != -1 && fault != diff[0])) { continue; } } else if (diff[1] != 0) { if (diff[2] != 0 || diff[3] != 0 || (row8 != -1 && row8 != 1) || (fault != -1 && fault != diff[1])) { continue; } } else if (diff[2] != 0) { if (diff[3] != 0 || (row8 != -1 && row8 != 2) || (fault != -1 && fault != diff[2])) { continue; } } else { if ((row8 != -1 && row8 != 3) || (fault != -1 && fault != diff[3])) { continue; } } /* one final test if previous tests passed */ reverseKeyExpansion(subkey10, subkeys); encrypt_aes(pt0, ctcmp, subkeys, AES_ROUNDS_128); if (memcmp(ct0, ctcmp, 16) == 0) { memcpy(masterkey, subkeys, 16); found = 1; } } /* end for l */ } /* end for k */ } /* end for j */ } /* end for i */ return found; } /* * return value * 0: not found * 1: found * -1: error (nb_cand = 0) */ int r8_key_recovery_single_ct(const byte pt0[16], const byte ct0[16], const byte ct[16], const byte fct[16], const int fault_pos, const int fault, byte masterkey[16]) { int i, col8; int cand_len[4]; int found = -1; int row8 = -1; int col8_start = 0; int col8_end = 4; long int nb_cand; word32 candidates[4][CAND_MAX]; if (fault_pos >= 0 && fault_pos < 16) { row8 = fault_pos % 4; col8_start = fault_pos / 4; col8_end = col8_start + 1; } for (col8 = col8_start; col8 < col8_end; col8++) { r8_find_candidates(ct, fct, row8, col8, fault, candidates, cand_len); nb_cand = 1; for (i = 0; i < 4; i++) { nb_cand *= (long int)cand_len[i]; } printf("Hypothesis: fault in column %d\n" "Number of candidates for positions 0, 13, 10, 7: %d\n" " 4, 1, 14, 11: %d\n" " 8, 5, 2, 15: %d\n" " 12, 9, 6, 3: %d\n" "Number of Master Key candidates: %ld\n", col8, cand_len[0], cand_len[1], cand_len[2], cand_len[3], nb_cand); if (nb_cand > 0) { found = r8_exhaustive_search(pt0, ct0, ct, fct, row8, col8, fault, candidates, cand_len, masterkey); } if (found == 1) { break; } } return found; } /* * In case of several (ct,fct) pairs, we only do intersections * of candidates followed by exhaustive search * return value: * 0: not found * 1: found * -1: error (nb_cand = 0) */ int r8_key_recovery(const byte pt0[16], const byte ct0[16], const byte ct_list[][16], const byte fct_list[][16], const int fault_pos_list[PAIRS_MAX], const int fault_list[PAIRS_MAX], const int fct_len, byte masterkey[16]) { int i, j; int cand_tmp_len[4], cand_len[4]; int found = -1; int row8 = -1; int col8 = -1; long int nb_cand; word32 candidates[4][CAND_MAX]; word32 cand_tmp[4][CAND_MAX]; /* we first get candidates for a faulty ciphertext */ if (fault_pos_list[0] >= 0 && fault_pos_list[0] < 16) { row8 = fault_pos_list[0] % 4; col8 = fault_pos_list[0] / 4; } r8_find_candidates(ct_list[0], fct_list[0], row8, col8, fault_list[0], candidates, cand_len); /* we reduce the candidates with other pairs (ct,fct) */ for (i = 1; i < fct_len; i++) { row8 = -1; col8 = -1; if (fault_pos_list[i] >= 0 && fault_pos_list[i] < 16) { row8 = fault_pos_list[i] % 4; col8 = fault_pos_list[i] / 4; } r8_find_candidates(ct_list[i], fct_list[i], row8, col8, fault_list[i], cand_tmp, cand_tmp_len); /* intersection with previous candidates */ for (j = 0; j < 4; j++) { intersection(candidates[j], &cand_len[j], cand_tmp[j], cand_tmp_len[j]); } } nb_cand = 1; for (i = 0; i < 4; i++) { nb_cand *= (long int)cand_len[i]; } printf("Number of candidates for positions 0, 13, 10, 7: %d\n" " 4, 1, 14, 11: %d\n" " 8, 5, 2, 15: %d\n" " 12, 9, 6, 3: %d\n" "Number of Master Key candidates: %ld\n", cand_len[0], cand_len[1], cand_len[2], cand_len[3], nb_cand); if (nb_cand > 0) { found = exhaustive_search(pt0, ct0, candidates, cand_len, masterkey); } return found; }
modifier_reverse.h
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2010, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: David Weese <[email protected]> // ========================================================================== #ifndef SEQAN_HEADER_MODIFIER_REVERSE_H #define SEQAN_HEADER_MODIFIER_REVERSE_H #ifdef _OPENMP #include <omp.h> #endif namespace SEQAN_NAMESPACE_MAIN { ////////////////////////////////////////////////////////////////////////////// /** .Spec.ModReverse: ..summary:Mirrors the characters from begin to end. ..cat:Modifier ..general:Class.ModifiedIterator ..general:Class.ModifiedString ..signature:ModifiedIterator<THost, ModReverse> ..signature:ModifiedString<THost, ModReverse> ..param.THost:Original string/iterator. ...type:Concept.Iterator ..include:seqan/modifier.h */ struct ModReverse {}; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // reverse iterator ////////////////////////////////////////////////////////////////////////////// template <typename THost> struct Cargo< ModifiedIterator<THost, ModReverse> > { typedef Cargo Type; // to reduce namespace pollution bool _atEnd; Cargo(): _atEnd(false) {} }; template <typename THost> class ModifiedIterator<THost, ModReverse> { public: Holder<THost, Simple> data_host; typename Cargo<ModifiedIterator>::Type data_cargo; ModifiedIterator() {} ModifiedIterator(ModifiedIterator &_origin): data_host(_origin.data_host), data_cargo(_origin.data_cargo) {} ModifiedIterator(ModifiedIterator const &_origin): data_host(_origin.data_host), data_cargo(_origin.data_cargo) {} template <typename T> ModifiedIterator(T & _origin) { assign(*this, _origin); } template <typename T> ModifiedIterator(T const & _origin) { assign(*this, _origin); } //____________________________________________________________________________ template <typename T> inline ModifiedIterator const & operator = (T & _origin) { assign(*this, _origin); return *this; } template <typename T> inline ModifiedIterator const & operator = (T const & _origin) { assign(*this, _origin); return *this; } }; ////////////////////////////////////////////////////////////////////////////// // operator ++ ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline void goNext(ModifiedIterator<THost, ModReverse> & me) { SEQAN_CHECKPOINT if (atBegin(host(me))) cargo(me)._atEnd = true; else goPrevious(host(me)); } ////////////////////////////////////////////////////////////////////////////// // operator -- ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline void goPrevious(ModifiedIterator<THost, ModReverse> & me) { SEQAN_CHECKPOINT if (cargo(me)._atEnd) cargo(me)._atEnd = false; else goNext(host(me)); } ////////////////////////////////////////////////////////////////////////////// // goEnd ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline void goEnd(ModifiedIterator<THost, ModReverse> & me) { SEQAN_CHECKPOINT goBegin(host(me)); cargo(me)._atEnd = true; } ////////////////////////////////////////////////////////////////////////////// // goBegin ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline void goBegin(ModifiedIterator<THost, ModReverse> & me) { SEQAN_CHECKPOINT goEnd(host(me)); if (atBegin(host(me))) cargo(me)._atEnd = true; else { cargo(me)._atEnd = false; goPrevious(host(me)); } } ////////////////////////////////////////////////////////////////////////////// // operator + ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TDelta> inline ModifiedIterator<THost, ModReverse> & operator += (ModifiedIterator<THost, ModReverse> & me, TDelta delta_) { typedef ModifiedIterator<THost, ModReverse> TIterator; typedef typename Position<TIterator>::Type TPosition; TPosition delta = delta_; if (delta == 0) { return me; } if (delta > 0) { if (position(host(me)) < delta) { cargo(me)._atEnd = true; --delta; } host(me) -= delta; } else { if (cargo(me)._atEnd) { cargo(me)._atEnd = false; ++delta; } host(me) -= delta; } return me; } ////////////////////////////////////////////////////////////////////////////// // operator - ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TDelta> inline ModifiedIterator<THost, ModReverse> & operator -= (ModifiedIterator<THost, ModReverse> & me, TDelta delta) { if (delta > 0) { if (cargo(me)._atEnd) { cargo(me)._atEnd = false; --delta; } host(me) += delta; } else { if (position(host(me)) < -delta) { cargo(me)._atEnd = true; ++delta; } host(me) -= -delta; } return me; } template <typename THost> inline typename Difference< ModifiedIterator<THost, ModReverse> >::Type operator - (ModifiedIterator<THost, ModReverse> const & a, ModifiedIterator<THost, ModReverse> const & b) { typename Difference< ModifiedIterator<THost, ModReverse> >::Type diff = host(b) - host(a); if (cargo(a)._atEnd) ++diff; if (cargo(b)._atEnd) --diff; return diff; } ////////////////////////////////////////////////////////////////////////////// // position ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline typename Position<ModifiedIterator<THost, ModReverse> const>::Type position(ModifiedIterator<THost, ModReverse> const & me) { SEQAN_CHECKPOINT if (cargo(me)._atEnd) return length(container(host(me))); else return length(container(host(me))) - 1 - position(host(me)); } template <typename THost, typename TContainer> inline typename Position<ModifiedIterator<THost, ModReverse> const>::Type position(ModifiedIterator<THost, ModReverse> const & me, TContainer const &cont) { SEQAN_CHECKPOINT if (cargo(me)._atEnd) return length(cont); else return length(cont) - 1 - position(host(me), cont); } ////////////////////////////////////////////////////////////////////////////// // setPosition ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TPosition> inline void setPosition(ModifiedIterator<THost, ModReverse> const & me, TPosition pos) { SEQAN_CHECKPOINT setPosition(host(me), length(container(host(me))) - 1 - pos); } ////////////////////////////////////////////////////////////////////////////// // operator == ////////////////////////////////////////////////////////////////////////////// template <typename THost> inline bool operator == (ModifiedIterator<THost, ModReverse> const & a, ModifiedIterator<THost, ModReverse> const & b) { return cargo(a)._atEnd == cargo(b)._atEnd && host(a) == host(b); } ////////////////////////////////////////////////////////////////////////////// // operator < ////////////////////////////////////////////////////////////////////////////// // redefinition candidate template <typename THost> inline bool operator < (ModifiedIterator<THost, ModReverse> const & a, ModifiedIterator<THost, ModReverse> const & b) { return (!cargo(a)._atEnd && cargo(b)._atEnd) || (!cargo(a)._atEnd && !cargo(b)._atEnd && host(a) > host(b)); } ////////////////////////////////////////////////////////////////////////////// // atBegin ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TContainer> inline bool atBegin(ModifiedIterator<THost, ModReverse> const & me, TContainer const & container) { SEQAN_CHECKPOINT return position(me, container) == 0; } template <typename THost> inline bool atBegin(ModifiedIterator<THost, ModReverse> const & me) { SEQAN_CHECKPOINT return position(me) == 0; } ////////////////////////////////////////////////////////////////////////////// // atEnd ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TContainer> inline bool atEnd(ModifiedIterator<THost, ModReverse> const & me, TContainer const & /*container*/) { SEQAN_CHECKPOINT return cargo(me)._atEnd; } template <typename THost> inline bool atEnd(ModifiedIterator<THost, ModReverse> const & me) { SEQAN_CHECKPOINT return cargo(me)._atEnd; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // reverse string ////////////////////////////////////////////////////////////////////////////// template <typename THost> class ModifiedString<THost, ModReverse> { public: Holder<THost> data_host; typename Cargo<ModifiedString>::Type data_cargo; ModifiedString() {} ModifiedString(ModifiedString &_origin): data_host(_origin.data_host), data_cargo(_origin.data_cargo) {} ModifiedString(ModifiedString const &_origin): data_host(_origin.data_host), data_cargo(_origin.data_cargo) {} template <typename THostHost, typename THostSpec> ModifiedString(ModifiedString<THostHost, THostSpec> &_origin): data_host(_origin.data_host) {} ModifiedString(THost &_origin) { setHost(*this, _origin); } template <typename T> ModifiedString(T & _origin) { setValue(*this, _origin); } template <typename T> ModifiedString(T const & _origin) { setValue(*this, _origin); } template <typename T> inline ModifiedString const & operator = (T & _origin) { assign(*this, _origin); return *this; } template <typename TPos> inline typename Reference<ModifiedString>::Type operator [] (TPos pos) { SEQAN_CHECKPOINT return value(*this, pos); } template <typename TPos> inline typename Reference<ModifiedString const>::Type operator [] (TPos pos) const { SEQAN_CHECKPOINT return value(*this, pos); } }; template <typename THost> struct Iterator< ModifiedString<THost, ModReverse>, Standard > { typedef ModifiedIterator<typename Iterator<THost, Rooted>::Type, ModReverse> Type; }; template <typename THost> struct Iterator< ModifiedString<THost, ModReverse> const, Standard > { typedef ModifiedIterator<typename Iterator<THost const, Rooted>::Type, ModReverse> Type; }; template <typename THost> struct DefaultIteratorSpec< ModifiedString<THost, ModReverse> > { typedef Rooted Type; }; ////////////////////////////////////////////////////////////////////////////// // value ////////////////////////////////////////////////////////////////////////////// template <typename THost, typename TPos> inline typename Reference<ModifiedString<THost, ModReverse> >::Type value(ModifiedString<THost, ModReverse> & me, TPos pos) { SEQAN_CHECKPOINT return value(host(me), (length(host(me)) - 1) - pos); } template <typename THost, typename TPos> inline typename Reference<ModifiedString<THost, ModReverse> const>::Type value(ModifiedString<THost, ModReverse> const & me, TPos pos) { SEQAN_CHECKPOINT return value(host(me), (length(host(me)) - 1) - pos); } ////////////////////////////////////////////////////////////////////////////// // begin ////////////////////////////////////////////////////////////////////////////// template < typename THost, typename TTag > inline typename Iterator< ModifiedString<THost, ModReverse> const >::Type begin(ModifiedString<THost, ModReverse> const & me) { typename Iterator< ModifiedString<THost, ModReverse> const >::Type temp_(end(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost > inline typename Iterator< ModifiedString<THost, ModReverse> >::Type begin(ModifiedString<THost, ModReverse> & me) { typename Iterator< ModifiedString<THost, ModReverse> >::Type temp_(end(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost, typename TTagSpec > inline typename Iterator< ModifiedString<THost, ModReverse> const, Tag<TTagSpec> const >::Type begin(ModifiedString<THost, ModReverse> const & me, Tag<TTagSpec> const) { typename Iterator< ModifiedString<THost, ModReverse> const, Tag<TTagSpec> const >::Type temp_(end(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost, typename TTagSpec > inline typename Iterator< ModifiedString<THost, ModReverse>, Tag<TTagSpec> const >::Type begin(ModifiedString<THost, ModReverse> & me, Tag<TTagSpec> const) { typename Iterator< ModifiedString<THost, ModReverse>, Tag<TTagSpec> const >::Type temp_(end(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } ////////////////////////////////////////////////////////////////////////////// // end ////////////////////////////////////////////////////////////////////////////// template < typename THost > inline typename Iterator< ModifiedString<THost, ModReverse> const >::Type end(ModifiedString<THost, ModReverse> const & me) { typename Iterator< ModifiedString<THost, ModReverse> const >::Type temp_(begin(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost > inline typename Iterator< ModifiedString<THost, ModReverse> >::Type end(ModifiedString<THost, ModReverse> & me) { typename Iterator< ModifiedString<THost, ModReverse> >::Type temp_(begin(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost, typename TTagSpec > inline typename Iterator< ModifiedString<THost, ModReverse> const, Tag<TTagSpec> const >::Type end(ModifiedString<THost, ModReverse> const & me, Tag<TTagSpec> const) { typename Iterator< ModifiedString<THost, ModReverse> const, Tag<TTagSpec> const >::Type temp_(begin(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } template < typename THost, typename TTagSpec > inline typename Iterator< ModifiedString<THost, ModReverse>, Tag<TTagSpec> const >::Type end(ModifiedString<THost, ModReverse> & me, Tag<TTagSpec> const) { typename Iterator< ModifiedString<THost, ModReverse>, Tag<TTagSpec> const >::Type temp_(begin(host(me), Rooted())); _copyCargo(temp_, me); goNext(temp_); return temp_; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // reverse ////////////////////////////////////////////////////////////////////////////// /** .Function.reverse ..summary:Reverse an object/container in-place. ..cat:Modifiers ..signature:reverse(object) ..param.object:The object/container whose elements to reverse. ...type:Concept.Container ...type:Adaption.std::list ..include:seqan/modifier.h */ template < typename TSequence > inline void reverse(TSequence & sequence) { typedef typename Value<TSequence>::Type TValue; #if defined (_OPENMP) && defined (SEQAN_PARALLEL) // OpenMP does not support for loop with iterators. Therefore use index variables. typedef typename Position<TSequence>::Type TPos; typedef typename MakeSigned_<TPos>::Type TSignedPos; TSignedPos pMid = length(sequence) / 2; #pragma omp parallel for if(length(sequence) > 1000000) for(TSignedPos p1 = 0; p1 < pMid; ++p1) { TPos p2 = length(sequence) - 1 - p1; TValue tmp = sequence[p1]; sequence[p1] = sequence[p2]; sequence[p2] = tmp; } #else typedef typename Iterator<TSequence, Standard>::Type TIter; TIter it1 = begin(sequence, Standard()); TIter it2 = it1 + length(sequence) - 1; TIter itMid = it1 + length(sequence) / 2; for(; it1 != itMid; ++it1, --it2) { TValue tmp = *it1; *it1 = *it2; *it2 = tmp; } #endif } template < typename TSequence, typename TSpec > inline void reverse(StringSet<TSequence, TSpec> & stringSet) { unsigned seqCount = length(stringSet); for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo) reverse(stringSet[seqNo]); } template < typename TSequence, typename TSpec > inline void reverse(StringSet<TSequence, TSpec> const & stringSet) { unsigned seqCount = length(stringSet); for(unsigned seqNo = 0; seqNo < seqCount; ++seqNo) reverse(stringSet[seqNo]); } template <typename TValue> inline void reverse(std::list<TValue> & list) { SEQAN_CHECKPOINT; list.reverse(); } ////////////////////////////////////////////////////////////////////////////// // shortcut template <typename THost> inline ModifiedString<THost, ModReverse> reverseString(THost const & host) { return ModifiedString<THost, ModReverse>(host); } ////////////////////////////////////////////////////////////////////////////// } #endif
nvptx_target_printf_codegen.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _ // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -x c -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -x c -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics extern int printf(const char *, ...); // Check a simple call to printf end-to-end. int CheckSimple() { #pragma omp target { // printf in master-only basic block. const char* fmt = "%d %lld %f"; printf(fmt, 1, 2ll, 3.0); } return 0; } void CheckNoArgs() { #pragma omp target { // printf in master-only basic block. printf("hello, world!"); } } // Check that printf's alloca happens in the entry block, not inside the if // statement. int foo; void CheckAllocaIsInEntryBlock() { #pragma omp target { if (foo) { printf("%d", 42); } } } // // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-64-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FMT:%.*]] = alloca i8*, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i64 0, i64 0), i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 8 // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-64-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-64-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-64-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-64-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP6:%.*]] = call i32 @vprintf(i8* [[TMP1]], i8* [[TMP5]]) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-64-SAME: () #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = call i32 @vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i64 0, i64 0), i8* null) // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // // // CHECK-64-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-64-SAME: (i64 [[FOO:%.*]]) #[[ATTR0]] { // CHECK-64-NEXT: entry: // CHECK-64-NEXT: [[FOO_ADDR:%.*]] = alloca i64, align 8 // CHECK-64-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-64-NEXT: store i64 [[FOO]], i64* [[FOO_ADDR]], align 8 // CHECK-64-NEXT: [[CONV:%.*]] = bitcast i64* [[FOO_ADDR]] to i32* // CHECK-64-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-64-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-64-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-64: user_code.entry: // CHECK-64-NEXT: [[TMP1:%.*]] = load i32, i32* [[CONV]], align 8 // CHECK-64-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-64-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-64: if.then: // CHECK-64-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-64-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-64-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-64-NEXT: [[TMP4:%.*]] = call i32 @vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i64 0, i64 0), i8* [[TMP3]]) // CHECK-64-NEXT: br label [[IF_END]] // CHECK-64: worker.exit: // CHECK-64-NEXT: ret void // CHECK-64: if.end: // CHECK-64-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-64-NEXT: ret void // // // // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckSimple_l13 // CHECK-32-SAME: () #[[ATTR0:[0-9]+]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FMT:%.*]] = alloca i8*, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS:%.*]], align 8 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1:[0-9]+]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: store i8* getelementptr inbounds ([11 x i8], [11 x i8]* @.str, i32 0, i32 0), i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP1:%.*]] = load i8*, i8** [[FMT]], align 4 // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 1, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 1 // CHECK-32-NEXT: store i64 2, i64* [[TMP3]], align 8 // CHECK-32-NEXT: [[TMP4:%.*]] = getelementptr inbounds [[PRINTF_ARGS]], %printf_args* [[TMP]], i32 0, i32 2 // CHECK-32-NEXT: store double 3.000000e+00, double* [[TMP4]], align 8 // CHECK-32-NEXT: [[TMP5:%.*]] = bitcast %printf_args* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP6:%.*]] = call i32 @vprintf(i8* [[TMP1]], i8* [[TMP5]]) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckNoArgs_l25 // CHECK-32-SAME: () #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = call i32 @vprintf(i8* getelementptr inbounds ([14 x i8], [14 x i8]* @.str1, i32 0, i32 0), i8* null) // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // // // CHECK-32-LABEL: define {{[^@]+}}@{{__omp_offloading_[0-9a-z]+_[0-9a-z]+}}_CheckAllocaIsInEntryBlock_l36 // CHECK-32-SAME: (i32 [[FOO:%.*]]) #[[ATTR0]] { // CHECK-32-NEXT: entry: // CHECK-32-NEXT: [[FOO_ADDR:%.*]] = alloca i32, align 4 // CHECK-32-NEXT: [[TMP:%.*]] = alloca [[PRINTF_ARGS_0:%.*]], align 8 // CHECK-32-NEXT: store i32 [[FOO]], i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TMP0:%.*]] = call i32 @__kmpc_target_init(%struct.ident_t* @[[GLOB1]], i8 1, i1 true, i1 true) // CHECK-32-NEXT: [[EXEC_USER_CODE:%.*]] = icmp eq i32 [[TMP0]], -1 // CHECK-32-NEXT: br i1 [[EXEC_USER_CODE]], label [[USER_CODE_ENTRY:%.*]], label [[WORKER_EXIT:%.*]] // CHECK-32: user_code.entry: // CHECK-32-NEXT: [[TMP1:%.*]] = load i32, i32* [[FOO_ADDR]], align 4 // CHECK-32-NEXT: [[TOBOOL:%.*]] = icmp ne i32 [[TMP1]], 0 // CHECK-32-NEXT: br i1 [[TOBOOL]], label [[IF_THEN:%.*]], label [[IF_END:%.*]] // CHECK-32: if.then: // CHECK-32-NEXT: [[TMP2:%.*]] = getelementptr inbounds [[PRINTF_ARGS_0]], %printf_args.0* [[TMP]], i32 0, i32 0 // CHECK-32-NEXT: store i32 42, i32* [[TMP2]], align 4 // CHECK-32-NEXT: [[TMP3:%.*]] = bitcast %printf_args.0* [[TMP]] to i8* // CHECK-32-NEXT: [[TMP4:%.*]] = call i32 @vprintf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str2, i32 0, i32 0), i8* [[TMP3]]) // CHECK-32-NEXT: br label [[IF_END]] // CHECK-32: worker.exit: // CHECK-32-NEXT: ret void // CHECK-32: if.end: // CHECK-32-NEXT: call void @__kmpc_target_deinit(%struct.ident_t* @[[GLOB1]], i8 1, i1 true) // CHECK-32-NEXT: ret void //
PeptideIndexing.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h> #include <OpenMS/CHEMISTRY/ProteaseDigestion.h> #include <OpenMS/CHEMISTRY/ProteaseDB.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/FASTAContainer.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/StringUtilsSimple.h> #include <OpenMS/DATASTRUCTURES/SeqanIncludeWrapper.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/METADATA/PeptideEvidence.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/SYSTEM/StopWatch.h> #include <OpenMS/SYSTEM/SysInfo.h> #include <atomic> #include <algorithm> #include <fstream> namespace OpenMS { /** @brief Refreshes the protein references for all peptide hits in a vector of PeptideIdentifications and adds target/decoy information. All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy". For proteins the possible values are "target" and "decoy", depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string) as a suffix or prefix, respectively (see parameter @p prefix). For peptides, the possible values are "target", "decoy" and "target+decoy", depending on whether the peptide sequence is found only in target proteins, only in decoy proteins, or in both. The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool. (For FDR calculations, "target+decoy" peptide hits count as target hits.) @note Make sure that your protein names in the database contain a correctly formatted decoy string. This can be ensured by using @ref UTILS_DecoyDatabase. If the decoy identifier is not recognized successfully all proteins will be assumed to stem from the target-part of the query.<br> E.g., "sw|P33354_DECOY|YEHR_ECOLI Uncharacterized lipop..." is <b>invalid</b>, since the tool has no knowledge of how SwissProt entries are build up. A correct identifier could be "DECOY_sw|P33354|YEHR_ECOLI Uncharacterized li ..." or "sw|P33354|YEHR_ECOLI_DECOY Uncharacterized li", depending on whether you are using prefix or suffix annotation.<br> Some helpful target/decoy statistics will be reported when done. By default this tool will fail if an unmatched peptide occurs, i.e. if the database does not contain the corresponding protein. You can force it to return successfully in this case by setting @p '-unmatched_action' to accept or even remove those hits. Search engines (such as Mascot) will replace ambiguous amino acids ('B', 'J', 'Z' and 'X') in the protein database with unambiguous amino acids in the reported peptides, e.g. exchange 'X' with 'H'. This will cause such peptides to not be found by exactly matching their sequences to the protein database. However, we can recover these cases by using tolerant search for ambiguous amino acids in the protein sequence. This is done by default with up to four amino acids per peptide hit. If you only want exact matches, set @p aaa_max to zero (but expect that unmatched peptides might occur)! Leucine/Isoleucine: Further complications can arise due to the presence of the isobaric amino acids isoleucine ('I') and leucine ('L') in protein sequences. Since the two have the exact same chemical composition and mass, they generally cannot be distinguished by mass spectrometry. If a peptide containing 'I' was reported as a match for a spectrum, a peptide containing 'L' instead would be an equally good match (and vice versa). To account for this inherent ambiguity, setting the flag @p IL_equivalent causes 'I' and 'L' to be considered as indistinguishable.@n For example, if the sequence "PEPTIDE" (matching "Protein1") was identified as a search hit, but the database additionally contained "PEPTLDE" (matching "Protein2"), running PeptideIndexer with the @p IL_equivalent option would report both "Protein1" and "Protein2" as accessions for "PEPTIDE". (This is independent of ambiguous matching via @p aaa_max.) Additionally, setting this flag will convert all 'J's in any protein sequence to 'I'. This way, no tolerant search is required for 'J' (but is still possible for all the other ambiguous amino acids). If @p write_protein_sequences is requested and @p IL_equivalent is set as well, both the I/L-version and unmodified protein sequences need to be stored internally. This requires some extra memory, roughly equivalent to the size of the FASTA database file itself. Enzyme specificity: Once a peptide sequence is found in a protein sequence, this does <b>not</b> imply that the hit is valid! This is where enzyme specificity comes into play. By default, the enzyme and the specificity used during search is derived from metadata in the idXML files ('auto' setting). We make two exceptions to any specificity constraints: 1) for peptides starting at the second or third position of a protein are still considered N-terminally specific, since the residues can be cleaved off in vivo; X!Tandem reports these peptides. For example, the two peptides ABAR and LABAR would both match a protein starting with MLABAR. 2) adventitious cleavage at Asp|Pro (Aspartate/D | Proline/P) is allowed for all enzymes (as supported by X!Tandem), i.e. counts as a proper cleavage site (see http://www.thegpm.org/tandem/release.html). You can relax the requirements further by choosing <tt>semi-tryptic</tt> (only one of two "internal" termini must match requirements) or <tt>none</tt> (essentially allowing all hits, no matter their context). These settings should not be used (due to high risk of reporting false positives), unless the search engine was instructed to search peptides in the same way (but then the default 'auto' setting will do the correct thing). X!Tandem treats any occurrence of 'X' as stop codon (and thus as cleavage site). The resulting peptide will be non- or semi-tryptic. Those hits will not be matched and need to be removed using @p '-unmatched_action' (do not use termini specificity to cheat around it! It adds more false hits!). The FASTA file should not contain duplicate protein accessions (since accessions are not validated) if a correct unique-matching annotation is important (target/decoy annotation is still correct). Threading: This tool support multiple threads (@p threads option) to speed up computation, at the cost of little extra memory. */ class OPENMS_DLLAPI PeptideIndexing : public DefaultParamHandler, public ProgressLogger { public: /// name of enzyme/specificity which signals that the enzyme/specificity should be taken from meta information static char const* const AUTO_MODE; /* = 'auto' */ /// Exit codes enum ExitCodes { EXECUTION_OK, DATABASE_EMPTY, PEPTIDE_IDS_EMPTY, ILLEGAL_PARAMETERS, UNEXPECTED_RESULT }; /// Action to take when peptide hits could not be matched enum class Unmatched { IS_ERROR, ///< throws an error (and returns no results) WARN, ///< skips annotation with target/decoy but returns with 'success' REMOVE, ///< removes unmatched hits entirely and returns with 'success' SIZE_OF_UNMATCHED }; static const std::array<std::string, (Size)Unmatched::SIZE_OF_UNMATCHED> names_of_unmatched; enum class MissingDecoy { IS_ERROR, WARN, SILENT, SIZE_OF_MISSING_DECOY }; static const std::array<std::string, (Size)MissingDecoy::SIZE_OF_MISSING_DECOY> names_of_missing_decoy; /// Default constructor PeptideIndexing(); /// Default destructor ~PeptideIndexing() override; /// forward for old interface and pyOpenMS; use run<T>() for more control inline ExitCodes run(std::vector<FASTAFile::FASTAEntry>& proteins, std::vector<ProteinIdentification>& prot_ids, std::vector<PeptideIdentification>& pep_ids) { FASTAContainer<TFI_Vector> protein_container(proteins); return run<TFI_Vector>(protein_container, prot_ids, pep_ids); } /** @brief Re-index peptide identifications honoring enzyme cutting rules, ambiguous amino acids and target/decoy hits. Template parameter 'T' can be either TFI_File or TFI_Vector. If the data is already available, use TFI_Vector and pass the vector. If the data is still in a FASTA file and its not needed afterwards for additional processing, use TFI_File and pass the filename. PeptideIndexer refreshes target/decoy information and mapping of peptides to proteins. The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool. (For FDR calculations, "target+decoy" peptide hits count as target hits.) PeptideIndexer allows for ambiguous amino acids (B|J|Z|X) in the protein database, but not in the peptide sequences. For the latter only I/L can be treated as equivalent (see 'IL_equivalent' flag), but 'J' is not allowed. Enzyme cutting rules and partial specificity can be specified. Resulting protein hits appear in the order of the FASTA file, except for orphaned proteins, which will appear first with an empty target_decoy metavalue. Duplicate protein accessions & sequences will not raise a warning, but create multiple hits (PeptideIndexer scans over the FASTA file once for efficiency reasons, and thus might not see all accessions & sequences at once). All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy". For proteins the possible values are "target" and "decoy", depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string) as a suffix or prefix, respectively (see parameter @p prefix). Peptide hits are annotated with metavalue 'protein_references', and if matched to at least one protein also with metavalue 'target_decoy'. The possible values for 'target_decoy' are "target", "decoy" and "target+decoy", depending on whether the peptide sequence is found only in target proteins, only in decoy proteins, or in both. The metavalue is not present, if the peptide is unmatched. Runtime: PeptideIndexer is usually very fast (loading and storing the data takes the most time) and search speed can be further improved (linearly), but using more threads. Avoid allowing too many (>=4) ambiguous amino acids if your database contains long stretches of 'X' (exponential search space). @param proteins A list of proteins -- either read piecewise from a FASTA file or as existing vector of FASTAEntries. @param prot_ids Resulting protein identifications associated to pep_ids (will be re-written completely) @param pep_ids Peptide identifications which should be search within @p proteins and then linked to @p prot_ids @return Exit status codes. */ template<typename T> ExitCodes run(FASTAContainer<T>& proteins, std::vector<ProteinIdentification>& prot_ids, std::vector<PeptideIdentification>& pep_ids) { if ((enzyme_name_ == "Chymotrypsin" || enzyme_name_ == "Chymotrypsin/P" || enzyme_name_ == "TrypChymo") && IL_equivalent_) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The used enzyme " + enzyme_name_ + "differentiates between I and L, therefore the IL_equivalent option cannot be used."); } // no decoy string provided? try to deduce from data if (decoy_string_.empty()) { auto r = DecoyHelper::findDecoyString(proteins); proteins.reset(); if (!r.success) { r.is_prefix = true; r.name = "DECOY_"; OPENMS_LOG_WARN << "Unable to determine decoy string automatically (not enough decoys were detected)! Using default " << (r.is_prefix ? "prefix" : "suffix") << " decoy string '" << r.name << "'\n" << "If you think that this is incorrect, please provide a decoy_string and its position manually!" << std::endl; } prefix_ = r.is_prefix; decoy_string_ = r.name; // decoy string and position was extracted successfully OPENMS_LOG_INFO << "Using " << (prefix_ ? "prefix" : "suffix") << " decoy string '" << decoy_string_ << "'" << std::endl; } //--------------------------------------------------------------- // parsing parameters, correcting xtandem and MSGFPlus parameters //--------------------------------------------------------------- ProteaseDigestion enzyme; if (!enzyme_name_.empty() && (enzyme_name_.compare(AUTO_MODE) != 0)) { // use param (not empty, not 'auto') enzyme.setEnzyme(enzyme_name_); } else if (!prot_ids.empty() && prot_ids[0].getSearchParameters().digestion_enzyme.getName() != "unknown_enzyme") { // take from meta (this assumes all runs used the same enzyme) OPENMS_LOG_INFO << "Info: using '" << prot_ids[0].getSearchParameters().digestion_enzyme.getName() << "' as enzyme (obtained from idXML) for digestion." << std::endl; enzyme.setEnzyme(&prot_ids[0].getSearchParameters().digestion_enzyme); } else { // fallback OPENMS_LOG_WARN << "Warning: Enzyme name neither given nor deduceable from input. Defaulting to Trypsin!" << std::endl; enzyme.setEnzyme("Trypsin"); } bool xtandem_fix_parameters = false; bool msgfplus_fix_parameters = false; // determine if at least one search engine was xtandem or MSGFPlus to enable special rules for (const auto& prot_id : prot_ids) { String search_engine = prot_id.getOriginalSearchEngineName(); StringUtils::toUpper(search_engine); OPENMS_LOG_INFO << "Peptide identification engine: " << search_engine << std::endl; if (search_engine == "XTANDEM" || prot_id.getSearchParameters().metaValueExists("SE:XTandem")) { xtandem_fix_parameters = true; } if (search_engine == "MS-GF+" || search_engine == "MSGFPLUS" || prot_id.getSearchParameters().metaValueExists("SE:MS-GF+")) { msgfplus_fix_parameters = true; } } // including MSGFPlus -> Trypsin/P as enzyme if (msgfplus_fix_parameters && enzyme.getEnzymeName() == "Trypsin") { OPENMS_LOG_WARN << "MSGFPlus detected but enzyme cutting rules were set to Trypsin. Correcting to Trypsin/P to cope with special cutting rule in MSGFPlus." << std::endl; enzyme.setEnzyme("Trypsin/P"); } OPENMS_LOG_INFO << "Enzyme: " << enzyme.getEnzymeName() << std::endl; if (!enzyme_specificity_.empty() && (enzyme_specificity_.compare(AUTO_MODE) != 0)) { // use param (not empty and not 'auto') enzyme.setSpecificity(ProteaseDigestion::getSpecificityByName(enzyme_specificity_)); } else if (!prot_ids.empty() && prot_ids[0].getSearchParameters().enzyme_term_specificity != ProteaseDigestion::SPEC_UNKNOWN) { // deduce from data ('auto') enzyme.setSpecificity(prot_ids[0].getSearchParameters().enzyme_term_specificity); OPENMS_LOG_INFO << "Info: using '" << EnzymaticDigestion::NamesOfSpecificity[prot_ids[0].getSearchParameters().enzyme_term_specificity] << "' as enzyme specificity (obtained from idXML) for digestion." << std::endl; } else { // fallback OPENMS_LOG_WARN << "Warning: Enzyme specificity neither given nor present in the input file. Defaulting to 'full'!" << std::endl; enzyme.setSpecificity(ProteaseDigestion::SPEC_FULL); } //------------------------------------------------------------- // calculations //------------------------------------------------------------- // cache the first proteins const size_t PROTEIN_CACHE_SIZE = 4e5; // 400k should be enough for most DB's and is not too hard on memory either (~200 MB FASTA) this->startProgress(0, 1, "Load first DB chunk"); proteins.cacheChunk(PROTEIN_CACHE_SIZE); this->endProgress(); if (proteins.empty()) // we do not allow an empty database { OPENMS_LOG_ERROR << "Error: An empty database was provided. Mapping makes no sense. Aborting..." << std::endl; return DATABASE_EMPTY; } if (pep_ids.empty()) // Aho-Corasick requires non-empty input; but we allow this case, since the TOPP tool should not crash when encountering a bad raw file (with no PSMs) { OPENMS_LOG_WARN << "Warning: An empty set of peptide identifications was provided. Output will be empty as well." << std::endl; if (!keep_unreferenced_proteins_) { // delete only protein hits, not whole ID runs incl. meta data: for (std::vector<ProteinIdentification>::iterator it = prot_ids.begin(); it != prot_ids.end(); ++it) { it->getHits().clear(); } } return PEPTIDE_IDS_EMPTY; } FoundProteinFunctor func(enzyme, xtandem_fix_parameters); // store the matches Map<String, Size> acc_to_prot; // map: accessions --> FASTA protein index std::vector<bool> protein_is_decoy; // protein index -> is decoy? std::vector<std::string> protein_accessions; // protein index -> accession bool invalid_protein_sequence = false; // check for proteins with modifications, i.e. '[' or '(', and throw an exception { // new scope - forget data after search /* BUILD Peptide DB */ bool has_illegal_AAs(false); AhoCorasickAmbiguous::PeptideDB pep_DB; for (std::vector<PeptideIdentification>::const_iterator it1 = pep_ids.begin(); it1 != pep_ids.end(); ++it1) { //String run_id = it1->getIdentifier(); const std::vector<PeptideHit>& hits = it1->getHits(); for (std::vector<PeptideHit>::const_iterator it2 = hits.begin(); it2 != hits.end(); ++it2) { // // Warning: // do not skip over peptides here, since the results are iterated in the same way // String seq = it2->getSequence().toUnmodifiedString().remove('*'); // make a copy, i.e. do NOT change the peptide sequence! if (seqan::isAmbiguous(seqan::AAString(seq.c_str()))) { // do not quit here, to show the user all sequences .. only quit after loop OPENMS_LOG_ERROR << "Peptide sequence '" << it2->getSequence() << "' contains one or more ambiguous amino acids (B|J|Z|X).\n"; has_illegal_AAs = true; } if (IL_equivalent_) // convert L to I; { seq.substitute('L', 'I'); } appendValue(pep_DB, seq.c_str()); } } if (has_illegal_AAs) { OPENMS_LOG_ERROR << "One or more peptides contained illegal amino acids. This is not allowed!" << "\nPlease either remove the peptide or replace it with one of the unambiguous ones (while allowing for ambiguous AA's to match the protein)." << std::endl;; } OPENMS_LOG_INFO << "Mapping " << length(pep_DB) << " peptides to " << (proteins.size() == PROTEIN_CACHE_SIZE ? "? (unknown number of)" : String(proteins.size())) << " proteins." << std::endl; if (length(pep_DB) == 0) { // Aho-Corasick will crash if given empty needles as input OPENMS_LOG_WARN << "Warning: Peptide identifications have no hits inside! Output will be empty as well." << std::endl; return PEPTIDE_IDS_EMPTY; } /* Aho Corasick (fast) */ OPENMS_LOG_INFO << "Searching with up to " << aaa_max_ << " ambiguous amino acid(s) and " << mm_max_ << " mismatch(es)!" << std::endl; SysInfo::MemUsage mu; OPENMS_LOG_INFO << "Building trie ..."; StopWatch s; s.start(); AhoCorasickAmbiguous::FuzzyACPattern pattern; AhoCorasickAmbiguous::initPattern(pep_DB, aaa_max_, mm_max_, pattern); s.stop(); OPENMS_LOG_INFO << " done (" << int(s.getClockTime()) << "s)" << std::endl; s.reset(); uint16_t count_j_proteins(0); bool has_active_data = true; // becomes false if end of FASTA file is reached const std::string jumpX(aaa_max_ + mm_max_ + 1, 'X'); // jump over stretches of 'X' which cost a lot of time; +1 because AXXA is a valid hit for aaa_max == 2 (cannot split it) // use very large target value for progress if DB size is unknown (did not fit into first chunk) this->startProgress(0, proteins.size() == PROTEIN_CACHE_SIZE ? std::numeric_limits<SignedSize>::max() : proteins.size(), "Aho-Corasick"); std::atomic<int> progress_prots(0); #ifdef _OPENMP #pragma omp parallel #endif { FoundProteinFunctor func_threads(enzyme, xtandem_fix_parameters); Map<String, Size> acc_to_prot_thread; // map: accessions --> FASTA protein index AhoCorasickAmbiguous fuzzyAC; String prot; while (true) { #pragma omp barrier // all threads need to be here, since we are about to swap protein data #pragma omp single { DEBUG_ONLY std::cerr << " activating cache ...\n"; has_active_data = proteins.activateCache(); // swap in last cache protein_accessions.resize(proteins.getChunkOffset() + proteins.chunkSize()); } // implicit barrier here if (!has_active_data) break; // leave while-loop SignedSize prot_count = (SignedSize)proteins.chunkSize(); #pragma omp master { DEBUG_ONLY std::cerr << "Filling Protein Cache ..."; proteins.cacheChunk(PROTEIN_CACHE_SIZE); protein_is_decoy.resize(proteins.getChunkOffset() + prot_count); for (SignedSize i = 0; i < prot_count; ++i) { // do this in master only, to avoid false sharing const String& seq = proteins.chunkAt(i).identifier; protein_is_decoy[i + proteins.getChunkOffset()] = (prefix_ ? seq.hasPrefix(decoy_string_) : seq.hasSuffix(decoy_string_)); } DEBUG_ONLY std::cerr << " done" << std::endl; } DEBUG_ONLY std::cerr << " starting for loop \n"; // search all peptides in each protein #pragma omp for schedule(dynamic, 100) nowait for (SignedSize i = 0; i < prot_count; ++i) { ++progress_prots; // atomic if (omp_get_thread_num() == 0) { this->setProgress(progress_prots); } prot = proteins.chunkAt(i).sequence; prot.remove('*'); // check for invalid sequences with modifications if (prot.has('[') || prot.has('(')) { invalid_protein_sequence = true; // not omp-critical because its write-only // we cannot throw an exception here, since we'd need to catch it within the parallel region } // convert L/J to I; also replace 'J' in proteins if (IL_equivalent_) { prot.substitute('L', 'I'); prot.substitute('J', 'I'); } else { // warn if 'J' is found (it eats into aaa_max) if (prot.has('J')) { #pragma omp atomic ++count_j_proteins; } } Size prot_idx = i + proteins.getChunkOffset(); // test if protein was a hit Size hits_total = func_threads.filter_passed + func_threads.filter_rejected; // check if there are stretches of 'X' if (prot.has('X')) { // create chunks of the protein (splitting it at stretches of 'X..X') and feed them to AC one by one size_t offset = -1, start = 0; while ((offset = prot.find(jumpX, offset + 1)) != std::string::npos) { //std::cout << "found X..X at " << offset << " in protein " << proteins[i].identifier << "\n"; addHits_(fuzzyAC, pattern, pep_DB, prot.substr(start, offset + jumpX.size() - start), prot, prot_idx, (int)start, func_threads); // skip ahead while we encounter more X... while (offset + jumpX.size() < prot.size() && prot[offset + jumpX.size()] == 'X') ++offset; start = offset; //std::cout << " new start: " << start << "\n"; } // last chunk if (start < prot.size()) { addHits_(fuzzyAC, pattern, pep_DB, prot.substr(start), prot, prot_idx, (int)start, func_threads); } } else { addHits_(fuzzyAC, pattern, pep_DB, prot, prot, prot_idx, 0, func_threads); } // was protein found? if (hits_total < func_threads.filter_passed + func_threads.filter_rejected) { protein_accessions[prot_idx] = proteins.chunkAt(i).identifier; acc_to_prot_thread[protein_accessions[prot_idx]] = prot_idx; } } // end parallel FOR // join results again DEBUG_ONLY std::cerr << " critical now \n"; #ifdef _OPENMP #pragma omp critical(PeptideIndexer_joinAC) #endif { s.start(); // hits func.merge(func_threads); // accession -> index acc_to_prot.insert(acc_to_prot_thread.begin(), acc_to_prot_thread.end()); acc_to_prot_thread.clear(); s.stop(); } // OMP end critical } // end readChunk } // OMP end parallel this->endProgress(); std::cout << "Merge took: " << s.toString() << "\n"; mu.after(); std::cout << mu.delta("Aho-Corasick") << "\n\n"; OPENMS_LOG_INFO << "\nAho-Corasick done:\n found " << func.filter_passed << " hits for " << func.pep_to_prot.size() << " of " << length(pep_DB) << " peptides.\n"; // write some stats OPENMS_LOG_INFO << "Peptide hits passing enzyme filter: " << func.filter_passed << "\n" << " ... rejected by enzyme filter: " << func.filter_rejected << std::endl; if (count_j_proteins) { OPENMS_LOG_WARN << "PeptideIndexer found " << count_j_proteins << " protein sequences in your database containing the amino acid 'J'." << "To match 'J' in a protein, an ambiguous amino acid placeholder for I/L will be used.\n" << "This costs runtime and eats into the 'aaa_max' limit, leaving less opportunity for B/Z/X matches.\n" << "If you want 'J' to be treated as unambiguous, enable '-IL_equivalent'!" << std::endl; } } // end local scope // // do mapping // // index existing proteins Map<String, Size> runid_to_runidx; // identifier to index for (Size run_idx = 0; run_idx < prot_ids.size(); ++run_idx) { runid_to_runidx[prot_ids[run_idx].getIdentifier()] = run_idx; } // for peptides --> proteins Size stats_matched_unique(0); Size stats_matched_multi(0); Size stats_unmatched(0); // no match to DB Size stats_count_m_t(0); // match to Target DB Size stats_count_m_d(0); // match to Decoy DB Size stats_count_m_td(0); // match to T+D DB Map<Size, std::set<Size> > runidx_to_protidx; // in which protID do appear which proteins (according to mapped peptides) Size pep_idx(0); for (std::vector<PeptideIdentification>::iterator it1 = pep_ids.begin(); it1 != pep_ids.end(); ++it1) { // which ProteinIdentification does the peptide belong to? Size run_idx = runid_to_runidx[it1->getIdentifier()]; std::vector<PeptideHit>& hits = it1->getHits(); for (std::vector<PeptideHit>::iterator it_hit = hits.begin(); it_hit != hits.end(); /* no increase here! we might need to skip it; see below */) { // clear protein accessions it_hit->setPeptideEvidences(std::vector<PeptideEvidence>()); // // is this a decoy hit? // bool matches_target(false); bool matches_decoy(false); std::set<Size> prot_indices; /// protein hits of this peptide // add new protein references for (std::set<PeptideProteinMatchInformation>::const_iterator it_i = func.pep_to_prot[pep_idx].begin(); it_i != func.pep_to_prot[pep_idx].end(); ++it_i) { prot_indices.insert(it_i->protein_index); const String& accession = protein_accessions[it_i->protein_index]; PeptideEvidence pe(accession, it_i->position, it_i->position + (int)it_hit->getSequence().size() - 1, it_i->AABefore, it_i->AAAfter); it_hit->addPeptideEvidence(pe); runidx_to_protidx[run_idx].insert(it_i->protein_index); // fill protein hits if (protein_is_decoy[it_i->protein_index]) { matches_decoy = true; } else { matches_target = true; } } ++pep_idx; // next hit if (matches_decoy && matches_target) { it_hit->setMetaValue("target_decoy", "target+decoy"); ++stats_count_m_td; } else if (matches_target) { it_hit->setMetaValue("target_decoy", "target"); ++stats_count_m_t; } else if (matches_decoy) { it_hit->setMetaValue("target_decoy", "decoy"); ++stats_count_m_d; } // else: could match to no protein (i.e. both are false) //else ... // not required (handled below; see stats_unmatched); if (prot_indices.size() == 1) { it_hit->setMetaValue("protein_references", "unique"); ++stats_matched_unique; } else if (prot_indices.size() > 1) { it_hit->setMetaValue("protein_references", "non-unique"); ++stats_matched_multi; } else { ++stats_unmatched; if (stats_unmatched < 15) OPENMS_LOG_INFO << "Unmatched peptide: " << it_hit->getSequence() << "\n"; else if (stats_unmatched == 15) OPENMS_LOG_INFO << "Unmatched peptide: ...\n"; if (unmatched_action_ == Unmatched::REMOVE) { it_hit = hits.erase(it_hit); continue; // already points to the next hit } else { it_hit->setMetaValue("protein_references", "unmatched"); } } ++it_hit; // next hit } // all hits } // next PepID Size total_peptides = stats_count_m_t + stats_count_m_d + stats_count_m_td + stats_unmatched; OPENMS_LOG_INFO << "-----------------------------------\n"; OPENMS_LOG_INFO << "Peptide statistics\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " unmatched : " << stats_unmatched << " (" << stats_unmatched * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " target/decoy:\n"; OPENMS_LOG_INFO << " match to target DB only: " << stats_count_m_t << " (" << stats_count_m_t * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " match to decoy DB only : " << stats_count_m_d << " (" << stats_count_m_d * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " match to both : " << stats_count_m_td << " (" << stats_count_m_td * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " mapping to proteins:\n"; OPENMS_LOG_INFO << " no match (to 0 protein) : " << stats_unmatched << "\n"; OPENMS_LOG_INFO << " unique match (to 1 protein) : " << stats_matched_unique << "\n"; OPENMS_LOG_INFO << " non-unique match (to >1 protein): " << stats_matched_multi << std::endl; /// for proteins --> peptides Size stats_matched_proteins(0), stats_matched_new_proteins(0), stats_orphaned_proteins(0), stats_proteins_target(0), stats_proteins_decoy(0); // all peptides contain the correct protein hit references, now update the protein hits for (Size run_idx = 0; run_idx < prot_ids.size(); ++run_idx) { std::set<Size> masterset = runidx_to_protidx[run_idx]; // all protein matches from above std::vector<ProteinHit>& phits = prot_ids[run_idx].getHits(); { // go through existing protein hits and count orphaned proteins (with no peptide hits) std::vector<ProteinHit> orphaned_hits; for (std::vector<ProteinHit>::iterator p_hit = phits.begin(); p_hit != phits.end(); ++p_hit) { const String& acc = p_hit->getAccession(); if (!acc_to_prot.has(acc)) // acc_to_prot only contains found proteins from current run { // old hit is orphaned ++stats_orphaned_proteins; if (keep_unreferenced_proteins_) { p_hit->setMetaValue("target_decoy", ""); orphaned_hits.push_back(*p_hit); } } } // only keep orphaned hits (if any) phits = orphaned_hits; } // add new protein hits FASTAFile::FASTAEntry fe; phits.reserve(phits.size() + masterset.size()); for (std::set<Size>::const_iterator it = masterset.begin(); it != masterset.end(); ++it) { ProteinHit hit; hit.setAccession(protein_accessions[*it]); if (write_protein_sequence_ || write_protein_description_) { proteins.readAt(fe, *it); if (write_protein_sequence_) { hit.setSequence(fe.sequence); } // no else, since sequence is empty by default if (write_protein_description_) { hit.setDescription(fe.description); } // no else, since description is empty by default } if (protein_is_decoy[*it]) { hit.setMetaValue("target_decoy", "decoy"); ++stats_proteins_decoy; } else { hit.setMetaValue("target_decoy", "target"); ++stats_proteins_target; } phits.push_back(hit); ++stats_matched_new_proteins; } stats_matched_proteins += phits.size(); } OPENMS_LOG_INFO << "-----------------------------------\n"; OPENMS_LOG_INFO << "Protein statistics\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " total proteins searched: " << proteins.size() << "\n"; OPENMS_LOG_INFO << " matched proteins : " << stats_matched_proteins << " (" << stats_matched_new_proteins << " new)\n"; if (stats_matched_proteins) { // prevent Division-by-0 Exception OPENMS_LOG_INFO << " matched target proteins: " << stats_proteins_target << " (" << stats_proteins_target * 100 / stats_matched_proteins << " %)\n"; OPENMS_LOG_INFO << " matched decoy proteins : " << stats_proteins_decoy << " (" << stats_proteins_decoy * 100 / stats_matched_proteins << " %)\n"; } OPENMS_LOG_INFO << " orphaned proteins : " << stats_orphaned_proteins << (keep_unreferenced_proteins_ ? " (all kept)" : " (all removed)\n"); OPENMS_LOG_INFO << "-----------------------------------" << std::endl; /// exit if no peptides were matched to decoy bool has_error = false; if (invalid_protein_sequence) { OPENMS_LOG_ERROR << "Error: One or more protein sequences contained the characters '[' or '(', which are illegal in protein sequences." << "\nPeptide hits might be masked by these characters (which usually indicate presence of modifications).\n"; has_error = true; } if ((stats_count_m_d + stats_count_m_td) == 0) { String msg("No peptides were matched to the decoy portion of the database! Did you provide the correct concatenated database? Are your 'decoy_string' (=" + decoy_string_ + ") and 'decoy_string_position' (=" + std::string(param_.getValue("decoy_string_position")) + ") settings correct?"); if (missing_decoy_action_ == MissingDecoy::IS_ERROR) { OPENMS_LOG_ERROR << "Error: " << msg << "\nSet 'missing_decoy_action' to 'warn' if you are sure this is ok!\nAborting ..." << std::endl; has_error = true; } else if (missing_decoy_action_ == MissingDecoy::WARN) { OPENMS_LOG_WARN << "Warn: " << msg << "\nSet 'missing_decoy_action' to 'error' if you want to elevate this to an error!" << std::endl; } else // silent { } } if (stats_unmatched > 0) { OPENMS_LOG_ERROR << "PeptideIndexer found unmatched peptides, which could not be associated to a protein.\n"; if (unmatched_action_ == Unmatched::IS_ERROR) { OPENMS_LOG_ERROR << "Potential solutions:\n" << " - check your FASTA database is identical to the search DB (or use 'auto')\n" << " - set 'enzyme:specificity' and 'enzyme:name' to 'auto' to match the parameters of the search engine\n" << " - increase 'aaa_max' to allow more ambiguous amino acids\n" << " - as a last resort: use the 'unmatched_action' option to accept or even remove unmatched peptides\n" << " (note that unmatched peptides cannot be used for FDR calculation or quantification)\n"; has_error = true; } else if (unmatched_action_ == Unmatched::WARN) { OPENMS_LOG_ERROR << " Warning: " << stats_unmatched << " unmatched hits have been found, but were not removed!\n" << "These are not annotated with target/decoy information and might lead to issues with downstream tools (such as FDR).\n" << "Switch to '" << names_of_unmatched[(Size)Unmatched::REMOVE] << "' if you want to avoid these problems.\n"; } else if (unmatched_action_ == Unmatched::REMOVE) { OPENMS_LOG_ERROR << " Warning: " << stats_unmatched <<" unmatched hits have been removed!\n" << "Make sure that these hits are actually a violation of the cutting rules by inspecting the database!\n"; if (xtandem_fix_parameters) OPENMS_LOG_ERROR << "Since the results are from X!Tandem, this is probably ok (check anyways).\n"; } else { throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } } if (has_error) { OPENMS_LOG_ERROR << "Result files will be written, but PeptideIndexer will exit with an error code." << std::endl; return UNEXPECTED_RESULT; } return EXECUTION_OK; } const String& getDecoyString() const; bool isPrefix() const; protected: struct PeptideProteinMatchInformation { OpenMS::Size protein_index; //< index of the protein the peptide is contained in OpenMS::Int position; //< the position of the peptide in the protein char AABefore; //< the amino acid after the peptide in the protein char AAAfter; //< the amino acid before the peptide in the protein const std::tuple<const Size&, const Int&, const char&, const char&> tie() const { return std::tie(protein_index, position, AABefore, AAAfter); } bool operator<(const PeptideProteinMatchInformation& other) const { return tie() < other.tie(); } bool operator==(const PeptideProteinMatchInformation& other) const { return tie() == other.tie(); } }; struct FoundProteinFunctor { public: typedef std::map<OpenMS::Size, std::set<PeptideProteinMatchInformation> > MapType; MapType pep_to_prot; //< peptide index --> protein indices OpenMS::Size filter_passed; //< number of accepted hits (passing addHit() constraints) OpenMS::Size filter_rejected; //< number of rejected hits (not passing addHit()) private: ProteaseDigestion enzyme_; bool xtandem_; //< are we checking xtandem cleavage rules? public: explicit FoundProteinFunctor(const ProteaseDigestion& enzyme, bool xtandem) : pep_to_prot(), filter_passed(0), filter_rejected(0), enzyme_(enzyme), xtandem_(xtandem) { } void merge(FoundProteinFunctor& other) { if (pep_to_prot.empty()) { // first merge is easy pep_to_prot.swap(other.pep_to_prot); } else { for (FoundProteinFunctor::MapType::const_iterator it = other.pep_to_prot.begin(); it != other.pep_to_prot.end(); ++it) { // augment set this->pep_to_prot[it->first].insert(other.pep_to_prot[it->first].begin(), other.pep_to_prot[it->first].end()); } other.pep_to_prot.clear(); } // cheap members this->filter_passed += other.filter_passed; other.filter_passed = 0; this->filter_rejected += other.filter_rejected; other.filter_rejected = 0; } void addHit(const OpenMS::Size idx_pep, const OpenMS::Size idx_prot, const OpenMS::Size len_pep, const OpenMS::String& seq_prot, OpenMS::Int position) { //TODO we could read and double-check missed cleavages as well if (enzyme_.isValidProduct(seq_prot, position, len_pep, true, true, xtandem_)) { PeptideProteinMatchInformation match { idx_prot, position, (position == 0) ? PeptideEvidence::N_TERMINAL_AA : seq_prot[position - 1], (position + len_pep >= seq_prot.size()) ? PeptideEvidence::C_TERMINAL_AA : seq_prot[position + len_pep] }; pep_to_prot[idx_pep].insert(match); ++filter_passed; } else { //std::cerr << "REJECTED Peptide " << seq_pep << " with hit to protein " // << seq_prot << " at position " << position << std::endl; ++filter_rejected; } } }; inline void addHits_(AhoCorasickAmbiguous& fuzzyAC, const AhoCorasickAmbiguous::FuzzyACPattern& pattern, const AhoCorasickAmbiguous::PeptideDB& pep_DB, const String& prot, const String& full_prot, SignedSize idx_prot, Int offset, FoundProteinFunctor& func_threads) const { fuzzyAC.setProtein(prot); while (fuzzyAC.findNext(pattern)) { const seqan::Peptide& tmp_pep = pep_DB[fuzzyAC.getHitDBIndex()]; func_threads.addHit(fuzzyAC.getHitDBIndex(), idx_prot, length(tmp_pep), full_prot, fuzzyAC.getHitProteinPosition() + offset); } } void updateMembers_() override; String decoy_string_{}; bool prefix_{ false }; MissingDecoy missing_decoy_action_ = MissingDecoy::IS_ERROR; String enzyme_name_{}; String enzyme_specificity_{}; bool write_protein_sequence_{ false }; bool write_protein_description_{ false }; bool keep_unreferenced_proteins_{ false }; Unmatched unmatched_action_ = Unmatched::IS_ERROR; bool IL_equivalent_{ false }; Int aaa_max_{0}; Int mm_max_{0}; }; }
nt2_fmt_plug.c
/* * NT-ng format, using intrinsics. * * This software is Copyright 2011, 2012 magnum, and it is hereby released to * the general public under the following terms: Redistribution and use in * source and binary forms, with or without modification, are permitted. * * Losely based on rawSHA1, by bartavelle * and is also using his mmx/sse2/simd-intrinsics functions * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_NT2; #elif FMT_REGISTERS_H john_register_one(&fmt_NT2); #else #include <string.h> #include "arch.h" //#undef SIMD_COEF_32 //#undef SIMD_PARA_MD4 /* * Only effective for SIMD. * Undef to disable reversing steps for benchmarking. */ #define REVERSE_STEPS #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_MD4) #endif #include "md4.h" #include "misc.h" #include "common.h" #include "formats.h" #include "options.h" #include "unicode.h" #include "memory.h" #include "johnswap.h" #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "NT" #define FORMAT_NAME "" #define ALGORITHM_NAME "MD4 " MD4_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define CIPHERTEXT_LENGTH 32 #define FORMAT_TAG "$NT$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define DIGEST_SIZE 16 #define BINARY_SIZE DIGEST_SIZE #define BINARY_ALIGN 4 #define SALT_SIZE 0 #define SALT_ALIGN 1 #if !FAST_FORMATS_OMP #undef _OPENMP #endif #ifdef SIMD_COEF_32 #if defined(_OPENMP) #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 512 // tuned for i7 w/o HT #endif #endif #define PLAINTEXT_LENGTH 27 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + ((i)&3) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32*4 ) #else #define PLAINTEXT_LENGTH 125 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static char *source(char *source, void *binary) { static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1] = FORMAT_TAG; ARCH_WORD_32 b[4]; char *p; int i, j; memcpy(b, binary, sizeof(b)); #if SIMD_COEF_32 && defined(REVERSE_STEPS) md4_unreverse(b); #endif #if ARCH_LITTLE_ENDIAN==0 alter_endianity(b, 16); #endif p = &out[TAG_LENGTH]; for (i = 0; i < 4; i++) for (j = 0; j < 8; j++) *p++ = itoa16[(b[i] >> ((j ^ 1) * 4)) & 0xf]; return out; } #ifdef SIMD_COEF_32 static unsigned char (*saved_key); static unsigned char (*crypt_key); static unsigned int (**buf_ptr); #else static MD4_CTX ctx; static int saved_len; static UTF16 saved_key[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 crypt_key[DIGEST_SIZE / 4]; #endif // Note: the ISO-8859-1 plaintexts will be replaced in init() if running UTF-8 static struct fmt_tests tests[] = { {"b7e4b9022cd45f275334bbdb83bb5be5", "John the Ripper"}, {"$NT$31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"$NT$31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"$NT$31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"$NT$31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"$NT$31d6cfe0d16ae931b73c59d7e0c089c0", ""}, {"$NT$7a21990fcd3d759941e45c490f143d5f", "12345"}, {"$NT$f9e37e83b83c47a93c2f09f66408631b", "abc123"}, {"$NT$8846f7eaee8fb117ad06bdd830b7586c", "password"}, {"$NT$2b2ac2d1c7c8fda6cea80b5fad7563aa", "computer"}, {"$NT$32ed87bdb5fdc5e9cba88547376818d4", "123456"}, {"$NT$b7e0ea9fbffcf6dd83086e905089effd", "tigger"}, {"$NT$7ce21f17c0aee7fb9ceba532d0546ad6", "1234"}, {"$NT$b23a90d0aad9da3615fafc27a1b8baeb", "a1b2c3"}, {"$NT$2d20d252a479f485cdf5e171d93985bf", "qwerty"}, {"$NT$3dbde697d71690a769204beb12283678", "123"}, {"$NT$c889c75b7c1aae1f7150c5681136e70e", "xxx"}, {"$NT$d5173c778e0f56d9fc47e3b3c829aca7", "money"}, {"$NT$0cb6948805f797bf2a82807973b89537", "test"}, {"$NT$0569fcf2b14b9c7f3d3b5f080cbd85e5", "carmen"}, {"$NT$f09ab1733a528f430353834152c8a90e", "mickey"}, {"$NT$878d8014606cda29677a44efa1353fc7", "secret"}, {"$NT$85ac333bbfcbaa62ba9f8afb76f06268", "summer"}, {"$NT$5962cc080506d90be8943118f968e164", "internet"}, {"$NT$f07206c3869bda5acd38a3d923a95d2a", "service"}, {"$NT$d0dfc65e8f286ef82f6b172789a0ae1c", "canada"}, {"$NT$066ddfd4ef0e9cd7c256fe77191ef43c", "hello"}, {"$NT$39b8620e745b8aa4d1108e22f74f29e2", "ranger"}, {"$NT$8d4ef8654a9adc66d4f628e94f66e31b", "shadow"}, {"$NT$320a78179516c385e35a93ffa0b1c4ac", "baseball"}, {"$NT$e533d171ac592a4e70498a58b854717c", "donald"}, {"$NT$5eee54ce19b97c11fd02e531dd268b4c", "harley"}, {"$NT$6241f038703cbfb7cc837e3ee04f0f6b", "hockey"}, {"$NT$becedb42ec3c5c7f965255338be4453c", "letmein"}, {"$NT$ec2c9f3346af1fb8e4ee94f286bac5ad", "maggie"}, {"$NT$f5794cbd75cf43d1eb21fad565c7e21c", "mike"}, {"$NT$74ed32086b1317b742c3a92148df1019", "mustang"}, {"$NT$63af6e1f1dd9ecd82f17d37881cb92e6", "snoopy"}, {"$NT$58def5844fe58e8f26a65fff9deb3827", "buster"}, {"$NT$f7eb9c06fafaa23c4bcf22ba6781c1e2", "dragon"}, {"$NT$dd555241a4321657e8b827a40b67dd4a", "jordan"}, {"$NT$bb53a477af18526ada697ce2e51f76b3", "michael"}, {"$NT$92b7b06bb313bf666640c5a1e75e0c18", "michelle"}, {NULL} }; static void set_key_utf8(char *_key, int index); static void set_key_CP(char *_key, int index); static void init(struct fmt_main *self) { #if SIMD_COEF_32 int i; #endif #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif if (options.target_enc == UTF_8) { /* This avoids an if clause for every set_key */ self->methods.set_key = set_key_utf8; #if SIMD_COEF_32 /* kick it up from 27. We will truncate in setkey_utf8() */ self->params.plaintext_length = 3 * PLAINTEXT_LENGTH; #endif tests[1].plaintext = "\xC3\xBC"; // German u-umlaut in UTF-8 tests[1].ciphertext = "$NT$8bd6e4fb88e01009818749c5443ea712"; tests[2].plaintext = "\xC3\xBC\xC3\xBC"; // two of them tests[2].ciphertext = "$NT$cc1260adb6985ca749f150c7e0b22063"; tests[3].plaintext = "\xE2\x82\xAC"; // euro sign tests[3].ciphertext = "$NT$030926b781938db4365d46adc7cfbcb8"; tests[4].plaintext = "\xE2\x82\xAC\xE2\x82\xAC"; tests[4].ciphertext = "$NT$682467b963bb4e61943e170a04f7db46"; } else { if (options.target_enc != ASCII && options.target_enc != ISO_8859_1) { /* This avoids an if clause for every set_key */ self->methods.set_key = set_key_CP; } if (CP_to_Unicode[0xfc] == 0x00fc) { tests[1].plaintext = "\xFC"; // German u-umlaut in UTF-8 tests[1].ciphertext = "$NT$8bd6e4fb88e01009818749c5443ea712"; tests[2].plaintext = "\xFC\xFC"; // two of them tests[2].ciphertext = "$NT$cc1260adb6985ca749f150c7e0b22063"; tests[3].plaintext = "\xFC\xFC\xFC"; // 3 of them tests[3].ciphertext = "$NT$2e583e8c210fb101994c19877ac53b89"; tests[4].plaintext = "\xFC\xFC\xFC\xFC"; tests[4].ciphertext = "$NT$243bb98e7704797f92b1dd7ded6da0d0"; } } #if SIMD_COEF_32 saved_key = mem_calloc_align(64 * self->params.max_keys_per_crypt, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(DIGEST_SIZE * self->params.max_keys_per_crypt, sizeof(*crypt_key), MEM_ALIGN_SIMD); buf_ptr = mem_calloc(self->params.max_keys_per_crypt, sizeof(*buf_ptr)); for (i=0; i<self->params.max_keys_per_crypt; i++) buf_ptr[i] = (unsigned int*)&saved_key[GETPOS(0, i)]; #endif } static void done(void) { #if SIMD_COEF_32 MEM_FREE(buf_ptr); MEM_FREE(crypt_key); MEM_FREE(saved_key); #endif } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[37]; if (!strncmp(ciphertext, "$NT$", 4)) ciphertext += 4; out[0] = '$'; out[1] = 'N'; out[2] = 'T'; out[3] = '$'; memcpy(&out[4], ciphertext, 32); out[36] = 0; strlwr(&out[4]); return out; } static int valid(char *ciphertext, struct fmt_main *self) { char *pos; if (!strncmp(ciphertext, "$NT$", 4)) ciphertext += 4; for (pos = ciphertext; atoi16[ARCH_INDEX(*pos)] != 0x7F; pos++); if (!*pos && pos - ciphertext == CIPHERTEXT_LENGTH) return 1; else return 0; } // here to 'handle' the pwdump files: user:uid:lmhash:ntlmhash::: // Note, we address the user id inside loader. static char *prepare(char *split_fields[10], struct fmt_main *self) { static char out[33+5]; if (!valid(split_fields[1], self)) { if (split_fields[3] && strlen(split_fields[3]) == 32) { sprintf(out, "$NT$%s", split_fields[3]); if (valid(out,self)) return out; } } return split_fields[1]; } static void *get_binary(char *ciphertext) { static union { unsigned long dummy; unsigned int i[DIGEST_SIZE/sizeof(unsigned int)]; } _out; unsigned int *out = _out.i; unsigned int i; unsigned int temp; ciphertext+=4; for (i=0; i<4; i++) { temp = ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+0])]))<<4; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+1])])); temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+2])]))<<12; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+3])]))<<8; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+4])]))<<20; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+5])]))<<16; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+6])]))<<28; temp |= ((unsigned int)(atoi16[ARCH_INDEX(ciphertext[i*8+7])]))<<24; #if ARCH_LITTLE_ENDIAN out[i]=temp; #else out[i]=JOHNSWAP(temp); #endif } #if SIMD_COEF_32 && defined(REVERSE_STEPS) md4_reverse(out); #endif //dump_stuff_msg("\nbinary", out, 16); return out; } // ISO-8859-1 to UCS-2, directly into vector key buffer static void set_key(char *_key, int index) { #ifdef SIMD_COEF_32 const unsigned char *key = (unsigned char*)_key; unsigned int *keybuf_word = buf_ptr[index]; unsigned int len, temp2; len = 0; while((temp2 = *key++)) { unsigned int temp; if ((temp = *key++) && len < PLAINTEXT_LENGTH - 1) { temp2 |= (temp << 16); *keybuf_word = temp2; } else { temp2 |= (0x80 << 16); *keybuf_word = temp2; len++; goto key_cleaning; } len += 2; keybuf_word += SIMD_COEF_32; } *keybuf_word = 0x80; key_cleaning: keybuf_word += SIMD_COEF_32; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else #if ARCH_LITTLE_ENDIAN UTF8 *s = (UTF8*)_key; UTF16 *d = saved_key; while (*s) *d++ = *s++; *d = 0; saved_len = (int)((char*)d - (char*)saved_key); #else UTF8 *s = (UTF8*)_key; UTF8 *d = (UTF8*)saved_key; while (*s) { *d++ = *s++; ++d; } *d = 0; saved_len = (int)((char*)d - (char*)saved_key); #endif // dump_stuff_msg(_key, saved_key, 24); #endif } // Legacy codepage to UCS-2, directly into vector key buffer static void set_key_CP(char *_key, int index) { #ifdef SIMD_COEF_32 const unsigned char *key = (unsigned char*)_key; unsigned int *keybuf_word = buf_ptr[index]; unsigned int len, temp2; len = 0; while((temp2 = *key++)) { unsigned int temp; temp2 = CP_to_Unicode[temp2]; if ((temp = *key++) && len < PLAINTEXT_LENGTH - 1) { temp = CP_to_Unicode[temp]; temp2 |= (temp << 16); *keybuf_word = temp2; } else { temp2 |= (0x80 << 16); *keybuf_word = temp2; len++; goto key_cleaning_enc; } len += 2; keybuf_word += SIMD_COEF_32; } *keybuf_word = 0x80; key_cleaning_enc: keybuf_word += SIMD_COEF_32; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else saved_len = enc_to_utf16((UTF16*)&saved_key, PLAINTEXT_LENGTH + 1, (unsigned char*)_key, strlen(_key)) << 1; if (saved_len < 0) saved_len = strlen16(saved_key); #endif } // UTF-8 to UCS-2, directly into vector key buffer static void set_key_utf8(char *_key, int index) { #ifdef SIMD_COEF_32 const UTF8 *source = (UTF8*)_key; unsigned int *keybuf_word = buf_ptr[index]; UTF32 chl, chh = 0x80; unsigned int len = 0; while (*source) { chl = *source; if (chl >= 0xC0) { unsigned int extraBytesToRead = opt_trailingBytesUTF8[chl & 0x3f]; switch (extraBytesToRead) { #if NT_FULL_UNICODE case 3: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; #endif case 2: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 1: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; case 0: break; default: goto bailout; } chl -= offsetsFromUTF8[extraBytesToRead]; } source++; len++; #if NT_FULL_UNICODE if (chl > UNI_MAX_BMP) { if (len == PLAINTEXT_LENGTH) { chh = 0x80; *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; break; } #define halfBase 0x0010000UL #define halfShift 10 #define halfMask 0x3FFUL #define UNI_SUR_HIGH_START (UTF32)0xD800 #define UNI_SUR_LOW_START (UTF32)0xDC00 chl -= halfBase; chh = (UTF16)((chl & halfMask) + UNI_SUR_LOW_START);; chl = (UTF16)((chl >> halfShift) + UNI_SUR_HIGH_START); len++; } else #endif if (*source && len < PLAINTEXT_LENGTH) { chh = *source; if (chh >= 0xC0) { unsigned int extraBytesToRead = opt_trailingBytesUTF8[chh & 0x3f]; switch (extraBytesToRead) { #if NT_FULL_UNICODE case 3: ++source; if (*source) { chl <<= 6; chl += *source; } else goto bailout; #endif case 2: ++source; if (*source) { chh <<= 6; chh += *source; } else goto bailout; case 1: ++source; if (*source) { chh <<= 6; chh += *source; } else goto bailout; case 0: break; default: goto bailout; } chh -= offsetsFromUTF8[extraBytesToRead]; } source++; len++; } else { chh = 0x80; *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; break; } *keybuf_word = (chh << 16) | chl; keybuf_word += SIMD_COEF_32; } if (chh != 0x80 || len == 0) { *keybuf_word = 0x80; keybuf_word += SIMD_COEF_32; } bailout: while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_32; } ((unsigned int *)saved_key)[14*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*16*SIMD_COEF_32] = len << 4; #else saved_len = utf8_to_utf16((UTF16*)&saved_key, PLAINTEXT_LENGTH + 1, (unsigned char*)_key, strlen(_key)) << 1; if (saved_len < 0) saved_len = strlen16(saved_key); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_32 // Get the key back from the key buffer, from UCS-2 unsigned int *keybuffer = (unsigned int*)&saved_key[GETPOS(0, index)]; static UTF16 key[PLAINTEXT_LENGTH + 1]; unsigned int md4_size=0; unsigned int i=0; for(; md4_size < PLAINTEXT_LENGTH; i += SIMD_COEF_32, md4_size++) { key[md4_size] = keybuffer[i]; key[md4_size+1] = keybuffer[i] >> 16; if (key[md4_size] == 0x80 && key[md4_size+1] == 0) { key[md4_size] = 0; break; } ++md4_size; if (key[md4_size] == 0x80 && ((keybuffer[i+SIMD_COEF_32]&0xFFFF) == 0 || md4_size == PLAINTEXT_LENGTH)) { key[md4_size] = 0; break; } } return (char*)utf16_to_enc(key); #else return (char*)utf16_to_enc(saved_key); #endif } #ifndef REVERSE_STEPS #undef SSEi_REVERSE_STEPS #define SSEi_REVERSE_STEPS 0 #endif static int crypt_all(int *pcount, struct db_salt *salt) { #ifdef SIMD_COEF_32 int i = 0; #ifdef _OPENMP const unsigned int count = (*pcount + NBKEYS - 1) / NBKEYS; #pragma omp parallel for for (i = 0; i < count; i++) #endif SIMDmd4body(&saved_key[i*NBKEYS*64], (unsigned int*)&crypt_key[i*NBKEYS*DIGEST_SIZE], NULL, SSEi_REVERSE_STEPS | SSEi_MIXED_IN); #else MD4_Init( &ctx ); MD4_Update(&ctx, (unsigned char*)saved_key, saved_len); MD4_Final((unsigned char*) crypt_key, &ctx); #endif return *pcount; } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x, y; #ifdef _OPENMP const unsigned int c = (count + SIMD_COEF_32 - 1) / SIMD_COEF_32; #else const unsigned int c = SIMD_PARA_MD4; #endif for(y = 0; y < c; y++) for(x = 0; x < SIMD_COEF_32; x++) { if( ((ARCH_WORD_32*)binary)[1] == ((ARCH_WORD_32*)crypt_key)[y*SIMD_COEF_32*4+x+SIMD_COEF_32] ) return 1; } return 0; #else return !memcmp(binary, crypt_key, BINARY_SIZE); #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 unsigned int x = index&(SIMD_COEF_32-1); unsigned int y = (unsigned int)index/SIMD_COEF_32; return ((ARCH_WORD_32*)binary)[1] == ((ARCH_WORD_32*)crypt_key)[x+y*SIMD_COEF_32*4+SIMD_COEF_32]; #else return !memcmp(binary, crypt_key, BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { #ifdef SIMD_COEF_32 ARCH_WORD_32 crypt_key[DIGEST_SIZE / 4]; UTF16 u16[PLAINTEXT_LENGTH + 1]; MD4_CTX ctx; UTF8 *key = (UTF8*)get_key(index); int len = enc_to_utf16(u16, PLAINTEXT_LENGTH, key, strlen((char*)key)); if (len <= 0) len = strlen16(u16); MD4_Init(&ctx); MD4_Update(&ctx, u16, len << 1); MD4_Final((void*)crypt_key, &ctx); #ifdef REVERSE_STEPS md4_reverse(crypt_key); #endif return !memcmp(get_binary(source), crypt_key, DIGEST_SIZE); #else return 1; #endif } #ifdef SIMD_COEF_32 #define SIMD_INDEX (index&(SIMD_COEF_32-1))+(unsigned int)index/SIMD_COEF_32*SIMD_COEF_32*4+SIMD_COEF_32 static int get_hash_0(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_0; } static int get_hash_1(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_1; } static int get_hash_2(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_2; } static int get_hash_3(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_3; } static int get_hash_4(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_4; } static int get_hash_5(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_5; } static int get_hash_6(int index) { return ((ARCH_WORD_32*)crypt_key)[SIMD_INDEX] & PH_MASK_6; } #else static int get_hash_0(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_0; } static int get_hash_1(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_1; } static int get_hash_2(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_2; } static int get_hash_3(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_3; } static int get_hash_4(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_4; } static int get_hash_5(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_5; } static int get_hash_6(int index) { return ((ARCH_WORD_32*)crypt_key)[1] & PH_MASK_6; } #endif static int binary_hash_0(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_0; } static int binary_hash_1(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_1; } static int binary_hash_2(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_2; } static int binary_hash_3(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_3; } static int binary_hash_4(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_4; } static int binary_hash_5(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_5; } static int binary_hash_6(void * binary) { return ((ARCH_WORD_32*)binary)[1] & PH_MASK_6; } struct fmt_main fmt_NT2 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_UNICODE | FMT_UTF8, { NULL }, tests }, { init, done, fmt_default_reset, prepare, valid, split, get_binary, fmt_default_salt, { NULL }, source, { binary_hash_0, binary_hash_1, binary_hash_2, binary_hash_3, binary_hash_4, binary_hash_5, binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
par_mod_lr_interp.c
/****************************************************************************** * Copyright (c) 1998 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildModExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtInterpHost(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle = NULL; HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt total_global_cpts; /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* Intermediate matrices */ hypre_ParCSRMatrix *As_FF, *As_FC, *W; HYPRE_Real *D_q, *D_w; hypre_CSRMatrix *As_FF_diag; hypre_CSRMatrix *As_FF_offd; hypre_CSRMatrix *As_FC_diag; hypre_CSRMatrix *As_FC_offd; hypre_CSRMatrix *W_diag; hypre_CSRMatrix *W_offd; HYPRE_Int *As_FF_diag_i; HYPRE_Int *As_FF_offd_i; HYPRE_Int *As_FC_diag_i; HYPRE_Int *As_FC_offd_i; HYPRE_Int *W_diag_i; HYPRE_Int *W_offd_i; HYPRE_Int *W_diag_j; HYPRE_Int *W_offd_j; HYPRE_Real *As_FF_diag_data; HYPRE_Real *As_FF_offd_data; HYPRE_Real *As_FC_diag_data; HYPRE_Real *As_FC_offd_data; HYPRE_Real *W_diag_data; HYPRE_Real *W_offd_data; HYPRE_BigInt *col_map_offd_P = NULL; HYPRE_BigInt *new_col_map_offd = NULL; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int new_ncols_P_offd; HYPRE_Int num_cols_P_offd; HYPRE_Int *P_marker = NULL; HYPRE_Int *dof_func_offd = NULL; /* Loop variables */ HYPRE_Int index; HYPRE_Int i, j; HYPRE_Int *cpt_array; HYPRE_Int *start_array; HYPRE_Int *startf_array; HYPRE_Int start, stop, startf, stopf; HYPRE_Int cnt_diag, cnt_offd, row, c_pt; /* Definitions */ //HYPRE_Real wall_time; HYPRE_Int n_Cpts, n_Fpts; HYPRE_Int num_threads = hypre_NumThreads(); //if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); n_Cpts = num_cpts_global[1] - num_cpts_global[0]; hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF); As_FC_diag = hypre_ParCSRMatrixDiag(As_FC); As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag); As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag); As_FC_offd = hypre_ParCSRMatrixOffd(As_FC); As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd); As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd); As_FF_diag = hypre_ParCSRMatrixDiag(As_FF); As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag); As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag); As_FF_offd = hypre_ParCSRMatrixOffd(As_FF); As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd); As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd); n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag); D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); start_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); startf_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,row) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Real beta, gamma; start = (n_fine / num_threads) * my_thread_num; if (my_thread_num == num_threads - 1) { stop = n_fine; } else { stop = (n_fine / num_threads) * (my_thread_num + 1); } start_array[my_thread_num + 1] = stop; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i = 1; i < num_threads; i++) { cpt_array[i] += cpt_array[i - 1]; } if (num_functions > 1) { HYPRE_Int *int_buf_data = NULL; HYPRE_Int num_sends, startc; HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) { int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { startf = start - cpt_array[my_thread_num - 1]; } else { startf = 0; } if (my_thread_num < num_threads - 1) { stopf = stop - cpt_array[my_thread_num]; } else { stopf = n_Fpts; } startf_array[my_thread_num + 1] = stopf; /* Create D_q = D_beta */ for (i = startf; i < stopf; i++) { for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i + 1]; j++) { D_q[i] += As_FC_diag_data[j]; } for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i + 1]; j++) { D_q[i] += As_FC_offd_data[j]; } } /* Create D_w = D_alpha + D_gamma */ row = startf; for (i = start; i < stop; i++) { if (CF_marker[i] < 0) { if (num_functions > 1) { HYPRE_Int jA, jS, jC; jC = A_diag_i[i]; for (j = S_diag_i[i]; j < S_diag_i[i + 1]; j++) { jS = S_diag_j[j]; jA = A_diag_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func[jA]) { D_w[row] += A_diag_data[jC++]; } else { jC++; } jA = A_diag_j[jC]; } jC++; } for (j = jC; j < A_diag_i[i + 1]; j++) { if (dof_func[i] == dof_func[A_diag_j[j]]) { D_w[row] += A_diag_data[j]; } } jC = A_offd_i[i]; for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++) { jS = S_offd_j[j]; jA = A_offd_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func_offd[jA]) { D_w[row] += A_offd_data[jC++]; } else { jC++; } jA = A_offd_j[jC]; } jC++; } for (j = jC; j < A_offd_i[i + 1]; j++) { if (dof_func[i] == dof_func_offd[A_offd_j[j]]) { D_w[row] += A_offd_data[j]; } } row++; } else { for (j = A_diag_i[i]; j < A_diag_i[i + 1]; j++) { D_w[row] += A_diag_data[j]; } for (j = A_offd_i[i]; j < A_offd_i[i + 1]; j++) { D_w[row] += A_offd_data[j]; } for (j = As_FF_diag_i[row] + 1; j < As_FF_diag_i[row + 1]; j++) { D_w[row] -= As_FF_diag_data[j]; } for (j = As_FF_offd_i[row]; j < As_FF_offd_i[row + 1]; j++) { D_w[row] -= As_FF_offd_data[j]; } D_w[row] -= D_q[row]; row++; } } } for (i = startf; i < stopf; i++) { j = As_FF_diag_i[i]; if (D_w[i]) { beta = 1.0 / D_w[i]; } else { beta = 1.0; } As_FF_diag_data[j] = beta * D_q[i]; if (D_q[i]) { gamma = -1.0 / D_q[i]; } else { gamma = 1.0; } for (j = As_FF_diag_i[i] + 1; j < As_FF_diag_i[i + 1]; j++) { As_FF_diag_data[j] *= beta; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { As_FF_offd_data[j] *= beta; } for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i + 1]; j++) { As_FC_diag_data[j] *= gamma; } for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i + 1]; j++) { As_FC_offd_data[j] *= gamma; } } } /* end parallel region */ W = hypre_ParMatmul(As_FF, As_FC); W_diag = hypre_ParCSRMatrixDiag(W); W_offd = hypre_ParCSRMatrixOffd(W); W_diag_i = hypre_CSRMatrixI(W_diag); W_diag_j = hypre_CSRMatrixJ(W_diag); W_diag_data = hypre_CSRMatrixData(W_diag); W_offd_i = hypre_CSRMatrixI(W_offd); W_offd_j = hypre_CSRMatrixJ(W_offd); W_offd_data = hypre_CSRMatrixData(W_offd); num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd); /*----------------------------------------------------------------------- * Intialize data for P *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts]; P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); startf = startf_array[my_thread_num]; stopf = startf_array[my_thread_num + 1]; start = start_array[my_thread_num]; stop = start_array[my_thread_num + 1]; if (my_thread_num > 0) { c_pt = cpt_array[my_thread_num - 1]; } else { c_pt = 0; } cnt_diag = W_diag_i[startf] + c_pt; cnt_offd = W_offd_i[startf]; row = startf; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { P_diag_j[cnt_diag] = c_pt++; P_diag_data[cnt_diag++] = 1.0; } else { for (j = W_diag_i[row]; j < W_diag_i[row + 1]; j++) { P_diag_j[cnt_diag] = W_diag_j[j]; P_diag_data[cnt_diag++] = W_diag_data[j]; } for (j = W_offd_i[row]; j < W_offd_i[row + 1]; j++) { P_offd_j[cnt_offd] = W_offd_j[j]; P_offd_data[cnt_offd++] = W_offd_data[j]; } row++; } P_diag_i[i + 1] = cnt_diag; P_offd_i[i + 1] = cnt_offd; } } /* end parallel region */ /*----------------------------------------------------------------------- * Create matrix *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, num_cols_P_offd, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W); hypre_ParCSRMatrixColMapOffd(W) = NULL; hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { HYPRE_Int *map; hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); if (num_cols_P_offd) { P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i = 0; i < P_offd_size; i++) { P_marker[P_offd_j[i]] = 1; } new_ncols_P_offd = 0; for (i = 0; i < num_cols_P_offd; i++) { if (P_marker[i]) { new_ncols_P_offd++; } } new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST); map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_col_map_offd[index] = col_map_offd_P[i]; map[index++] = i; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) { P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i], new_ncols_P_offd); } hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd; hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd; hypre_TFree(map, HYPRE_MEMORY_HOST); } } hypre_MatvecCommPkgCreate(P); *P_ptr = P; /* Deallocate memory */ hypre_TFree(D_q, HYPRE_MEMORY_HOST); hypre_TFree(D_w, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(start_array, HYPRE_MEMORY_HOST); hypre_TFree(startf_array, HYPRE_MEMORY_HOST); hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDestroy(As_FF); hypre_ParCSRMatrixDestroy(As_FC); hypre_ParCSRMatrixDestroy(W); return hypre_error_flag; } /*-----------------------------------------------------------------------* * Modularized Extended Interpolation *-----------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ModExtInterp"); #endif HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { ierr = hypre_BoomerAMGBuildExtInterpDevice(A, CF_marker, S, num_cpts_global, 1, NULL, debug_flag, trunc_factor, max_elmts, P_ptr); } else #endif { ierr = hypre_BoomerAMGBuildModExtInterpHost(A, CF_marker, S, num_cpts_global, num_functions, dof_func, debug_flag, trunc_factor, max_elmts, P_ptr); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildModExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtPIInterpHost(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int debug_flag, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle = NULL; HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt total_global_cpts; hypre_CSRMatrix *As_FF_ext = NULL; HYPRE_Real *As_FF_ext_data = NULL; HYPRE_Int *As_FF_ext_i = NULL; HYPRE_BigInt *As_FF_ext_j = NULL; /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* Intermediate matrices */ hypre_ParCSRMatrix *As_FF, *As_FC, *W; HYPRE_Real *D_q, *D_w, *D_theta, *D_q_offd = NULL; hypre_CSRMatrix *As_FF_diag; hypre_CSRMatrix *As_FF_offd; hypre_CSRMatrix *As_FC_diag; hypre_CSRMatrix *As_FC_offd; hypre_CSRMatrix *W_diag; hypre_CSRMatrix *W_offd; HYPRE_Int *As_FF_diag_i; HYPRE_Int *As_FF_diag_j; HYPRE_Int *As_FF_offd_i; HYPRE_Int *As_FF_offd_j = NULL; HYPRE_Int *As_FC_diag_i; HYPRE_Int *As_FC_offd_i; HYPRE_Int *W_diag_i; HYPRE_Int *W_offd_i; HYPRE_Int *W_diag_j; HYPRE_Int *W_offd_j = NULL; HYPRE_Real *As_FF_diag_data; HYPRE_Real *As_FF_offd_data = NULL; HYPRE_Real *As_FC_diag_data; HYPRE_Real *As_FC_offd_data = NULL; HYPRE_Real *W_diag_data; HYPRE_Real *W_offd_data = NULL; HYPRE_Real *buf_data = NULL; HYPRE_Real *tmp_FF_diag_data = NULL; HYPRE_BigInt *col_map_offd_P = NULL; HYPRE_BigInt *new_col_map_offd = NULL; HYPRE_BigInt first_index; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int new_ncols_P_offd; HYPRE_Int num_cols_P_offd; HYPRE_Int *P_marker = NULL; HYPRE_Int *dof_func_offd = NULL; /* Loop variables */ HYPRE_Int index, startc, num_sends; HYPRE_Int i, j, jj, k, kk; HYPRE_Int *cpt_array; HYPRE_Int *start_array; HYPRE_Int *startf_array; HYPRE_Int start, stop, startf, stopf; HYPRE_Int cnt_diag, cnt_offd, row, c_pt; HYPRE_Int num_cols_A_FF_offd; HYPRE_Real value, value1, theta; /* Definitions */ //HYPRE_Real wall_time; HYPRE_Int n_Cpts, n_Fpts; HYPRE_Int num_threads = hypre_NumThreads(); //if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); n_Cpts = num_cpts_global[1] - num_cpts_global[0]; hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF); if (num_procs > 1) { As_FF_ext = hypre_ParCSRMatrixExtractBExt(As_FF, As_FF, 1); As_FF_ext_i = hypre_CSRMatrixI(As_FF_ext); As_FF_ext_j = hypre_CSRMatrixBigJ(As_FF_ext); As_FF_ext_data = hypre_CSRMatrixData(As_FF_ext); } As_FC_diag = hypre_ParCSRMatrixDiag(As_FC); As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag); As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag); As_FC_offd = hypre_ParCSRMatrixOffd(As_FC); As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd); As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd); As_FF_diag = hypre_ParCSRMatrixDiag(As_FF); As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag); As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag); As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag); As_FF_offd = hypre_ParCSRMatrixOffd(As_FF); As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd); As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd); As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd); n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag); num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd); first_index = hypre_ParCSRMatrixRowStarts(As_FF)[0]; tmp_FF_diag_data = hypre_CTAlloc(HYPRE_Real, As_FF_diag_i[n_Fpts], HYPRE_MEMORY_HOST); D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_theta = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); start_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); startf_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,jj,k,kk,start,stop,startf,stopf,row,theta,value,value1) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = (n_fine / num_threads) * my_thread_num; if (my_thread_num == num_threads - 1) { stop = n_fine; } else { stop = (n_fine / num_threads) * (my_thread_num + 1); } start_array[my_thread_num + 1] = stop; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i = 1; i < num_threads; i++) { cpt_array[i] += cpt_array[i - 1]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { startf = start - cpt_array[my_thread_num - 1]; } else { startf = 0; } if (my_thread_num < num_threads - 1) { stopf = stop - cpt_array[my_thread_num]; } else { stopf = n_Fpts; } startf_array[my_thread_num + 1] = stopf; for (i = startf; i < stopf; i++) { for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i + 1]; j++) { D_q[i] += As_FC_diag_data[j]; } for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i + 1]; j++) { D_q[i] += As_FC_offd_data[j]; } } for (j = As_FF_diag_i[startf]; j < As_FF_diag_i[stopf]; j++) { tmp_FF_diag_data[j] = As_FF_diag_data[j]; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_FF_offd) { D_q_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, HYPRE_MEMORY_HOST); } index = 0; comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); if (!comm_pkg) { hypre_MatvecCommPkgCreate(As_FF); comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) { buf_data[index++] = D_q[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_q_offd); hypre_ParCSRCommHandleDestroy(comm_handle); if (num_functions > 1) { HYPRE_Int *int_buf_data = NULL; HYPRE_Int num_sends, startc; HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) { int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif row = startf; for (i = start; i < stop; i++) { HYPRE_Int jA, jC, jS; if (CF_marker[i] < 0) { if (num_functions > 1) { jC = A_diag_i[i]; for (j = S_diag_i[i]; j < S_diag_i[i + 1]; j++) { jS = S_diag_j[j]; jA = A_diag_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func[jA]) { D_w[row] += A_diag_data[jC++]; } else { jC++; } jA = A_diag_j[jC]; } jC++; } for (j = jC; j < A_diag_i[i + 1]; j++) { if (dof_func[i] == dof_func[A_diag_j[j]]) { D_w[row] += A_diag_data[j]; } } jC = A_offd_i[i]; for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++) { jS = S_offd_j[j]; jA = A_offd_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func_offd[jA]) { D_w[row] += A_offd_data[jC++]; } else { jC++; } jA = A_offd_j[jC]; } jC++; } for (j = jC; j < A_offd_i[i + 1]; j++) { if (dof_func[i] == dof_func_offd[A_offd_j[j]]) { D_w[row] += A_offd_data[j]; } } row++; } else { for (j = A_diag_i[i]; j < A_diag_i[i + 1]; j++) { D_w[row] += A_diag_data[j]; } for (j = A_offd_i[i]; j < A_offd_i[i + 1]; j++) { D_w[row] += A_offd_data[j]; } for (j = As_FF_diag_i[row] + 1; j < As_FF_diag_i[row + 1]; j++) { D_w[row] -= As_FF_diag_data[j]; } for (j = As_FF_offd_i[row]; j < As_FF_offd_i[row + 1]; j++) { D_w[row] -= As_FF_offd_data[j]; } D_w[row] -= D_q[row]; row++; } } } for (i = startf; i < stopf; i++) { for (j = As_FF_diag_i[i] + 1; j < As_FF_diag_i[i + 1]; j++) { jj = As_FF_diag_j[j]; value = D_q[jj]; for (k = As_FF_diag_i[jj] + 1; k < As_FF_diag_i[jj + 1]; k++) { kk = As_FF_diag_j[k]; if (kk == i) { value1 = tmp_FF_diag_data[k]; value += value1; D_theta[i] += As_FF_diag_data[j] * value1 / value; break; } } As_FF_diag_data[j] /= value; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { jj = As_FF_offd_j[j]; value = D_q_offd[jj]; for (k = As_FF_ext_i[jj]; k < As_FF_ext_i[jj + 1]; k++) { kk = (HYPRE_Int)(As_FF_ext_j[k] - first_index); if (kk == i) { value1 = As_FF_ext_data[k]; value += value1; D_theta[i] += As_FF_offd_data[j] * value1 / value; break; } } As_FF_offd_data[j] /= value; } As_FF_diag_data[As_FF_diag_i[i]] = 1.0; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = startf; i < stopf; i++) { theta = (D_theta[i] + D_w[i]); if (theta) { theta = -1.0 / theta; for (j = As_FF_diag_i[i]; j < As_FF_diag_i[i + 1]; j++) { As_FF_diag_data[j] *= theta; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { As_FF_offd_data[j] *= theta; } } } } /* end parallel region */ W = hypre_ParMatmul(As_FF, As_FC); W_diag = hypre_ParCSRMatrixDiag(W); W_offd = hypre_ParCSRMatrixOffd(W); W_diag_i = hypre_CSRMatrixI(W_diag); W_diag_j = hypre_CSRMatrixJ(W_diag); W_diag_data = hypre_CSRMatrixData(W_diag); W_offd_i = hypre_CSRMatrixI(W_offd); W_offd_j = hypre_CSRMatrixJ(W_offd); W_offd_data = hypre_CSRMatrixData(W_offd); num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd); /*----------------------------------------------------------------------- * Intialize data for P *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts]; P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); startf = startf_array[my_thread_num]; stopf = startf_array[my_thread_num + 1]; start = start_array[my_thread_num]; stop = start_array[my_thread_num + 1]; if (my_thread_num > 0) { c_pt = cpt_array[my_thread_num - 1]; } else { c_pt = 0; } cnt_diag = W_diag_i[startf] + c_pt; cnt_offd = W_offd_i[startf]; row = startf; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { P_diag_j[cnt_diag] = c_pt++; P_diag_data[cnt_diag++] = 1.0; } else { for (j = W_diag_i[row]; j < W_diag_i[row + 1]; j++) { P_diag_j[cnt_diag] = W_diag_j[j]; P_diag_data[cnt_diag++] = W_diag_data[j]; } for (j = W_offd_i[row]; j < W_offd_i[row + 1]; j++) { P_offd_j[cnt_offd] = W_offd_j[j]; P_offd_data[cnt_offd++] = W_offd_data[j]; } row++; } P_diag_i[i + 1] = cnt_diag; P_offd_i[i + 1] = cnt_offd; } } /* end parallel region */ /*----------------------------------------------------------------------- * Create matrix *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, num_cols_P_offd, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W); hypre_ParCSRMatrixColMapOffd(W) = NULL; hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { HYPRE_Int *map; hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); if (num_cols_P_offd) { P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i = 0; i < P_offd_size; i++) { P_marker[P_offd_j[i]] = 1; } new_ncols_P_offd = 0; for (i = 0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_ncols_P_offd++; } new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST); map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_col_map_offd[index] = col_map_offd_P[i]; map[index++] = i; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) { P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i], new_ncols_P_offd); } hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd; hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd; hypre_TFree(map, HYPRE_MEMORY_HOST); } } hypre_MatvecCommPkgCreate(P); *P_ptr = P; /* Deallocate memory */ hypre_TFree(D_q, HYPRE_MEMORY_HOST); hypre_TFree(D_q_offd, HYPRE_MEMORY_HOST); hypre_TFree(D_w, HYPRE_MEMORY_HOST); hypre_TFree(D_theta, HYPRE_MEMORY_HOST); hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(start_array, HYPRE_MEMORY_HOST); hypre_TFree(startf_array, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(tmp_FF_diag_data, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDestroy(As_FF); hypre_ParCSRMatrixDestroy(As_FC); hypre_ParCSRMatrixDestroy(W); hypre_CSRMatrixDestroy(As_FF_ext); return hypre_error_flag; } /*-----------------------------------------------------------------------* * Modularized Extended+i Interpolation *-----------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ModExtPIInterp"); #endif HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { ierr = hypre_BoomerAMGBuildExtPIInterpDevice(A, CF_marker, S, num_cpts_global, 1, NULL, debug_flag, trunc_factor, max_elmts, P_ptr); } else #endif { ierr = hypre_BoomerAMGBuildModExtPIInterpHost(A, CF_marker, S, num_cpts_global, debug_flag, num_functions, dof_func, trunc_factor, max_elmts, P_ptr); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildModExtPEInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtPEInterpHost(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle = NULL; HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt total_global_cpts; /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /* Intermediate matrices */ hypre_ParCSRMatrix *As_FF, *As_FC, *W; HYPRE_Real *D_beta, *D_w, *D_lambda, *D_tmp, *D_tau, *D_tmp_offd = NULL; hypre_CSRMatrix *As_FF_diag; hypre_CSRMatrix *As_FF_offd; hypre_CSRMatrix *As_FC_diag; hypre_CSRMatrix *As_FC_offd; hypre_CSRMatrix *W_diag; hypre_CSRMatrix *W_offd; HYPRE_Int *As_FF_diag_i; HYPRE_Int *As_FF_diag_j; HYPRE_Int *As_FF_offd_i; HYPRE_Int *As_FF_offd_j; HYPRE_Int *As_FC_diag_i; HYPRE_Int *As_FC_offd_i; HYPRE_Int *W_diag_i; HYPRE_Int *W_offd_i; HYPRE_Int *W_diag_j; HYPRE_Int *W_offd_j = NULL; HYPRE_Real *As_FF_diag_data; HYPRE_Real *As_FF_offd_data = NULL; HYPRE_Real *As_FC_diag_data; HYPRE_Real *As_FC_offd_data = NULL; HYPRE_Real *W_diag_data; HYPRE_Real *W_offd_data = NULL; HYPRE_Real *buf_data = NULL; HYPRE_BigInt *col_map_offd_P = NULL; HYPRE_BigInt *new_col_map_offd = NULL; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int new_ncols_P_offd; HYPRE_Int num_cols_P_offd; HYPRE_Int *P_marker = NULL; HYPRE_Int *dof_func_offd = NULL; /* Loop variables */ HYPRE_Int index, startc, num_sends; HYPRE_Int i, j; HYPRE_Int *cpt_array; HYPRE_Int *start_array; HYPRE_Int *startf_array; HYPRE_Int start, stop, startf, stopf; HYPRE_Int cnt_diag, cnt_offd, row, c_pt; HYPRE_Int num_cols_A_FF_offd; HYPRE_Real value, theta; /* Definitions */ //HYPRE_Real wall_time; HYPRE_Int n_Cpts, n_Fpts; HYPRE_Int num_threads = hypre_NumThreads(); //if (debug_flag==4) wall_time = time_getWallclockSeconds(); /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); n_Cpts = num_cpts_global[1] - num_cpts_global[0]; hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF); As_FC_diag = hypre_ParCSRMatrixDiag(As_FC); As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag); As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag); As_FC_offd = hypre_ParCSRMatrixOffd(As_FC); As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd); As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd); As_FF_diag = hypre_ParCSRMatrixDiag(As_FF); As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag); As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag); As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag); As_FF_offd = hypre_ParCSRMatrixOffd(As_FF); As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd); As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd); As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd); n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag); num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd); D_beta = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_lambda = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_tmp = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_tau = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST); cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); start_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); startf_array = hypre_CTAlloc(HYPRE_Int, num_threads + 1, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,row,theta,value) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); start = (n_fine / num_threads) * my_thread_num; if (my_thread_num == num_threads - 1) { stop = n_fine; } else { stop = (n_fine / num_threads) * (my_thread_num + 1); } start_array[my_thread_num + 1] = stop; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { cpt_array[my_thread_num]++; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { for (i = 1; i < num_threads; i++) { cpt_array[i] += cpt_array[i - 1]; } if (num_functions > 1) { HYPRE_Int *int_buf_data = NULL; HYPRE_Int num_sends, startc; HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST); index = 0; num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) { int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { startf = start - cpt_array[my_thread_num - 1]; } else { startf = 0; } if (my_thread_num < num_threads - 1) { stopf = stop - cpt_array[my_thread_num]; } else { stopf = n_Fpts; } startf_array[my_thread_num + 1] = stopf; for (i = startf; i < stopf; i++) { HYPRE_Real number; for (j = As_FF_diag_i[i] + 1; j < As_FF_diag_i[i + 1]; j++) { D_lambda[i] += As_FF_diag_data[j]; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { D_lambda[i] += As_FF_offd_data[j]; } number = (HYPRE_Real)(As_FF_diag_i[i + 1] - As_FF_diag_i[i] - 1 + As_FF_offd_i[i + 1] - As_FF_offd_i[i]); if (number) { D_lambda[i] /= number; } for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i + 1]; j++) { D_beta[i] += As_FC_diag_data[j]; } for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i + 1]; j++) { D_beta[i] += As_FC_offd_data[j]; } if (D_lambda[i] + D_beta[i]) { D_tmp[i] = D_lambda[i] / (D_beta[i] + D_lambda[i]); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (num_cols_A_FF_offd) { D_tmp_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, HYPRE_MEMORY_HOST); } index = 0; comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); if (!comm_pkg) { hypre_MatvecCommPkgCreate(As_FF); comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); for (i = 0; i < num_sends; i++) { startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) { buf_data[index++] = D_tmp[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_tmp_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif row = startf; for (i = start; i < stop; i++) { if (CF_marker[i] < 0) { if (num_functions > 1) { HYPRE_Int jA, jC, jS; jC = A_diag_i[i]; for (j = S_diag_i[i]; j < S_diag_i[i + 1]; j++) { jS = S_diag_j[j]; jA = A_diag_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func[jA]) { D_w[row] += A_diag_data[jC++]; } else { jC++; } jA = A_diag_j[jC]; } jC++; } for (j = jC; j < A_diag_i[i + 1]; j++) { if (dof_func[i] == dof_func[A_diag_j[j]]) { D_w[row] += A_diag_data[j]; } } jC = A_offd_i[i]; for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++) { jS = S_offd_j[j]; jA = A_offd_j[jC]; while (jA != jS) { if (dof_func[i] == dof_func_offd[jA]) { D_w[row] += A_offd_data[jC++]; } else { jC++; } jA = A_offd_j[jC]; } jC++; } for (j = jC; j < A_offd_i[i + 1]; j++) { if (dof_func[i] == dof_func_offd[A_offd_j[j]]) { D_w[row] += A_offd_data[j]; } } row++; } else { for (j = A_diag_i[i]; j < A_diag_i[i + 1]; j++) { D_w[row] += A_diag_data[j]; } for (j = A_offd_i[i]; j < A_offd_i[i + 1]; j++) { D_w[row] += A_offd_data[j]; } for (j = As_FF_diag_i[row] + 1; j < As_FF_diag_i[row + 1]; j++) { D_w[row] -= As_FF_diag_data[j]; } for (j = As_FF_offd_i[row]; j < As_FF_offd_i[row + 1]; j++) { D_w[row] -= As_FF_offd_data[j]; } D_w[row] -= D_beta[row]; row++; } } } for (i = startf; i < stopf; i++) { for (j = As_FF_diag_i[i] + 1; j < As_FF_diag_i[i + 1]; j++) { index = As_FF_diag_j[j]; D_tau[i] += As_FF_diag_data[j] * D_tmp[index]; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { index = As_FF_offd_j[j]; D_tau[i] += As_FF_offd_data[j] * D_tmp_offd[index]; } } for (i = startf; i < stopf; i++) { value = D_w[i] + D_tau[i]; if (value) { value = -1.0 / value; } theta = D_beta[i] + D_lambda[i]; As_FF_diag_data[As_FF_diag_i[i]] = value * theta; if (theta) { theta = 1.0 / theta; } for (j = As_FF_diag_i[i] + 1; j < As_FF_diag_i[i + 1]; j++) { As_FF_diag_data[j] *= value; } for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i + 1]; j++) { As_FF_offd_data[j] *= value; } for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i + 1]; j++) { As_FC_diag_data[j] *= theta; } for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i + 1]; j++) { As_FC_offd_data[j] *= theta; } } } /* end parallel region */ W = hypre_ParMatmul(As_FF, As_FC); W_diag = hypre_ParCSRMatrixDiag(W); W_offd = hypre_ParCSRMatrixOffd(W); W_diag_i = hypre_CSRMatrixI(W_diag); W_diag_j = hypre_CSRMatrixJ(W_diag); W_diag_data = hypre_CSRMatrixData(W_diag); W_offd_i = hypre_CSRMatrixI(W_offd); W_offd_j = hypre_CSRMatrixJ(W_offd); W_offd_data = hypre_CSRMatrixData(W_offd); num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd); /*----------------------------------------------------------------------- * Intialize data for P *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, memory_location_P); P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts]; P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P); } #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd) #endif { HYPRE_Int my_thread_num = hypre_GetThreadNum(); startf = startf_array[my_thread_num]; stopf = startf_array[my_thread_num + 1]; start = start_array[my_thread_num]; stop = start_array[my_thread_num + 1]; if (my_thread_num > 0) { c_pt = cpt_array[my_thread_num - 1]; } else { c_pt = 0; } cnt_diag = W_diag_i[startf] + c_pt; cnt_offd = W_offd_i[startf]; row = startf; for (i = start; i < stop; i++) { if (CF_marker[i] > 0) { P_diag_j[cnt_diag] = c_pt++; P_diag_data[cnt_diag++] = 1.0; } else { for (j = W_diag_i[row]; j < W_diag_i[row + 1]; j++) { P_diag_j[cnt_diag] = W_diag_j[j]; P_diag_data[cnt_diag++] = W_diag_data[j]; } for (j = W_offd_i[row]; j < W_offd_i[row + 1]; j++) { P_offd_j[cnt_offd] = W_offd_j[j]; P_offd_data[cnt_offd++] = W_offd_data[j]; } row++; } P_diag_i[i + 1] = cnt_diag; P_offd_i[i + 1] = cnt_offd; } } /* end parallel region */ /*----------------------------------------------------------------------- * Create matrix *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(A), total_global_cpts, hypre_ParCSRMatrixColStarts(A), num_cpts_global, num_cols_P_offd, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W); hypre_ParCSRMatrixColMapOffd(W) = NULL; hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P; hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { HYPRE_Int *map; hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P); if (num_cols_P_offd) { P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i = 0; i < P_offd_size; i++) { P_marker[P_offd_j[i]] = 1; } new_ncols_P_offd = 0; for (i = 0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_ncols_P_offd++; } new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST); map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_cols_P_offd; i++) if (P_marker[i]) { new_col_map_offd[index] = col_map_offd_P[i]; map[index++] = i; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) { P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i], new_ncols_P_offd); } hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd; hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd; hypre_TFree(map, HYPRE_MEMORY_HOST); } } hypre_MatvecCommPkgCreate(P); *P_ptr = P; /* Deallocate memory */ hypre_TFree(D_tmp, HYPRE_MEMORY_HOST); hypre_TFree(D_tmp_offd, HYPRE_MEMORY_HOST); hypre_TFree(D_w, HYPRE_MEMORY_HOST); hypre_TFree(D_tau, HYPRE_MEMORY_HOST); hypre_TFree(D_beta, HYPRE_MEMORY_HOST); hypre_TFree(D_lambda, HYPRE_MEMORY_HOST); hypre_TFree(cpt_array, HYPRE_MEMORY_HOST); hypre_TFree(start_array, HYPRE_MEMORY_HOST); hypre_TFree(startf_array, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_ParCSRMatrixDestroy(As_FF); hypre_ParCSRMatrixDestroy(As_FC); hypre_ParCSRMatrixDestroy(W); return hypre_error_flag; } /*-----------------------------------------------------------------------* * Modularized Extended+e Interpolation *-----------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildModExtPEInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPushRange("ModExtPEInterp"); #endif HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { ierr = hypre_BoomerAMGBuildExtPEInterpDevice(A, CF_marker, S, num_cpts_global, 1, NULL, debug_flag, trunc_factor, max_elmts, P_ptr); } else #endif { ierr = hypre_BoomerAMGBuildModExtPEInterpHost(A, CF_marker, S, num_cpts_global, num_functions, dof_func, debug_flag, trunc_factor, max_elmts, P_ptr); } #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_GpuProfilingPopRange(); #endif return ierr; }
flexProxDualHuber.h
#ifndef flexProxDualHuber_H #define flexProxDualHuber_H #include "flexProx.h" //! represents prox for a Huber term /*! \f$ \alpha \|\cdot\|_{H_\epsilon} \f$ */ template<typename T> class flexProxDualHuber : public flexProx<T> { #ifdef __CUDACC__ typedef thrust::device_vector<T> Tdata; #else typedef std::vector<T> Tdata; #endif private: T huberEpsilon; public: //! initializes the Huber prox /*! \param aHuberEpsilon represents the parameter of the Huber norm (equals \f$ H_\epsilon \f$) */ flexProxDualHuber(T aHuberEpsilon) : flexProx<T>(dualHuberProx) { huberEpsilon = aHuberEpsilon; } ~flexProxDualHuber() { if (VERBOSE > 0) printf("Destructor prox\n!"); } #ifdef __CUDACC__ struct flexProxDualHuberDim2Functor { __host__ __device__ flexProxDualHuberDim2Functor(T _epsi, T _alpha) : epsi(_epsi), alpha(_alpha), epsiAlpha(epsi / alpha){} template <typename Tuple> __host__ __device__ void operator()(Tuple t) { T huberFactor1 = (T)1 / ((T)1 + thrust::get<4>(t) * epsiAlpha); T huberFactor2 = (T)1 / ((T)1 + thrust::get<5>(t) * epsiAlpha); T norm = max((T)1, sqrt( pow(thrust::get<2>(t)*huberFactor1,(int)2) + pow(thrust::get<3>(t)*huberFactor2,(int)2)) / alpha); thrust::get<0>(t) = thrust::get<2>(t) * huberFactor1 / norm; thrust::get<1>(t) = thrust::get<3>(t) * huberFactor2 / norm; } const T epsi; const T alpha; const T epsiAlpha; }; struct flexProxDualHuberDim3Functor { __host__ __device__ flexProxDualHuberDim3Functor(T _epsi, T _alpha) : epsi(_epsi), alpha(_alpha), epsiAlpha(epsi / alpha){} template <typename Tuple> __host__ __device__ void operator()(Tuple t) { T huberFactor1 = (T)1 / ((T)1 + thrust::get<6>(t) * epsiAlpha); T huberFactor2 = (T)1 / ((T)1 + thrust::get<7>(t) * epsiAlpha); T huberFactor3 = (T)1 / ((T)1 + thrust::get<8>(t) * epsiAlpha); T norm = max((T)1, sqrt( pow(thrust::get<3>(t)*huberFactor1,(int)2) + pow(thrust::get<4>(t)*huberFactor2,(int)2) + pow(thrust::get<5>(t)*huberFactor3,(int)2)) / alpha); thrust::get<0>(t) = thrust::get<3>(t) * huberFactor1 / norm; thrust::get<1>(t) = thrust::get<4>(t) * huberFactor2 / norm; thrust::get<2>(t) = thrust::get<5>(t) * huberFactor3 / norm; } const T epsi; const T alpha; const T epsiAlpha; }; #endif void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers) { #ifdef __CUDACC__ if (dualNumbers.size() == 2) { auto startIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[0]].begin(), data->y[dualNumbers[1]].begin(), data->yTilde[dualNumbers[0]].begin(), data->yTilde[dualNumbers[1]].begin(), data->sigmaElt[dualNumbers[0]].begin(), data->sigmaElt[dualNumbers[1]].begin())); auto endIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[0]].end(), data->y[dualNumbers[1]].end(), data->yTilde[dualNumbers[0]].end(), data->yTilde[dualNumbers[1]].end(), data->sigmaElt[dualNumbers[0]].end(), data->sigmaElt[dualNumbers[1]].end())); thrust::for_each(startIterator,endIterator,flexProxDualHuberDim2Functor(this->huberEpsilon,alpha)); } else if (dualNumbers.size() == 3) { auto startIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[0]].begin(), data->y[dualNumbers[1]].begin(), data->y[dualNumbers[2]].begin(), data->yTilde[dualNumbers[0]].begin(), data->yTilde[dualNumbers[1]].begin(), data->yTilde[dualNumbers[2]].begin(), data->sigmaElt[dualNumbers[0]].begin(), data->sigmaElt[dualNumbers[1]].begin(), data->sigmaElt[dualNumbers[2]].begin())); auto endIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[0]].end(), data->y[dualNumbers[1]].end(), data->y[dualNumbers[2]].end(), data->yTilde[dualNumbers[0]].end(), data->yTilde[dualNumbers[1]].end(), data->yTilde[dualNumbers[2]].end(), data->sigmaElt[dualNumbers[0]].end(), data->sigmaElt[dualNumbers[1]].end(), data->sigmaElt[dualNumbers[2]].end())); thrust::for_each(startIterator, endIterator, flexProxDualHuberDim3Functor(this->huberEpsilon, alpha)); } else { printf("Alert! Huber prox not implemented in CUDA for dim!={2,3}\n"); } #else if (dualNumbers.size() == 1) { T* ptrY0 = data->y[dualNumbers[0]].data(); T* ptrYtilde0 = data->yTilde[dualNumbers[0]].data(); T* ptrSigma = data->sigmaElt[dualNumbers[0]].data(); int numElements = (int)data->yTilde[dualNumbers[0]].size(); #pragma omp parallel for for (int i = 0; i < numElements; i++) { T huberFactor = alpha / (alpha + ptrSigma[i] * this->huberEpsilon); T yTmp = huberFactor / myMax<T>((T)1, huberFactor*std::abs(ptrYtilde0[i]) / alpha); ptrY0[i] = ptrYtilde0[i] * yTmp; } } else if (dualNumbers.size() == 2) { T* ptrY0 = data->y[dualNumbers[0]].data(); T* ptrY1 = data->y[dualNumbers[1]].data(); T* ptrYtilde0 = data->yTilde[dualNumbers[0]].data(); T* ptrYtilde1 = data->yTilde[dualNumbers[1]].data(); T* ptrSigma = data->sigmaElt[dualNumbers[0]].data(); int numElements = (int)data->yTilde[dualNumbers[0]].size(); #pragma omp parallel for for (int i = 0; i < numElements; i++) { T huberFactor = alpha / (alpha + ptrSigma[i] * this->huberEpsilon); T yTmp = huberFactor / myMax<T>((T)1, huberFactor*std::sqrt(pow2(ptrYtilde0[i]) + pow2(ptrYtilde1[i])) / alpha); ptrY0[i] = ptrYtilde0[i] * yTmp; ptrY1[i] = ptrYtilde1[i] * yTmp; } } else if (dualNumbers.size() == 3) { T* ptrY0 = data->y[dualNumbers[0]].data(); T* ptrY1 = data->y[dualNumbers[1]].data(); T* ptrY2 = data->y[dualNumbers[2]].data(); T* ptrYtilde0 = data->yTilde[dualNumbers[0]].data(); T* ptrYtilde1 = data->yTilde[dualNumbers[1]].data(); T* ptrYtilde2 = data->yTilde[dualNumbers[2]].data(); T* ptrSigma = data->sigmaElt[dualNumbers[0]].data(); int numElements = (int)data->yTilde[dualNumbers[0]].size(); #pragma omp parallel for for (int i = 0; i < numElements; i++) { T huberFactor = alpha / (alpha + ptrSigma[i] * this->huberEpsilon); T yTmp = huberFactor / std::max((T)1, huberFactor * std::sqrt(pow2(ptrYtilde0[i]) + pow2(ptrYtilde1[i]) + pow2(ptrYtilde2[i])) / alpha); ptrY0[i] = ptrYtilde0[i] * yTmp; ptrY1[i] = ptrYtilde1[i] * yTmp; ptrY2[i] = ptrYtilde2[i] * yTmp; } } else { printf("Alert! Huber prox not implemented for dim>3"); } #endif } void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers, std::vector<Tdata> &fList) { } }; #endif
teams_notarget_get_num_teams.c
#include <stdlib.h> #include <stdio.h> #include <omp.h> #define N 10000 int main() { int n = N; int team_id, cur_teams; int teams_sizes[10] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; int *a = (int *)malloc(n*sizeof(int)); int err = 0; for (int j = 0; j < 10; j++) { cur_teams = 0; #pragma omp teams distribute num_teams(teams_sizes[j]) for (int i = 0; i < n; i++) { cur_teams = omp_get_num_teams(); a[i] = i; } err = 0; for (int i = 0; i < n; i++) { if (a[i] != i) { printf("Error at %d: a = %d, should be %d\n", i, a[i], i); err++; if (err > 10) break; } } // omp_get_num_teams() will always return value less than or equal to // value passed in num_teams() clause. if ( cur_teams > teams_sizes[j] ) { printf("Error : omp_get_num_teams() : %d but we tried to set" " num_teams(%d)\n", cur_teams, teams_sizes[j]); err++; } } cur_teams = omp_get_num_teams(); // omp_get_num_teams() value should be 1 when outside of teams region. if ( cur_teams != 1 ) { printf("Error : omp_get_num_teams() : %d but should return 1 when" " outside of teams region.\n", cur_teams); err++; } return err; }
GB_unop__bnot_uint8_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__bnot_uint8_uint8 // op(A') function: GB_unop_tran__bnot_uint8_uint8 // C type: uint8_t // A type: uint8_t // cast: uint8_t cij = aij // unaryop: cij = ~(aij) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ~(x) ; // casting #define GB_CAST(z, aij) \ uint8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = aij ; \ Cx [pC] = ~(z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BNOT || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__bnot_uint8_uint8 ( uint8_t *Cx, // Cx and Ax may be aliased const uint8_t *Ax, const int8_t *GB_RESTRICT Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint8_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = ~(z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = ~(z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__bnot_uint8_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
reorder.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "base.h" #include "reorder.h" #include "sptensor.h" #include "ftensor.h" #include "io.h" #include "sort.h" #include "timer.h" #include "util.h" /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ static void p_reorder_slices( sptensor_t * const tt, ftensor_t const * const ft, idx_t const * const parts, idx_t const nparts, idx_t const * const uncut, idx_t const nuncut, permutation_t * const perm, idx_t const mode) { /* build map of fiber -> slice */ idx_t const nslices = ft->dims[mode]; idx_t const nfibs = ft->nfibs; idx_t * slice = (idx_t *) splatt_malloc(nfibs * sizeof(idx_t)); idx_t * const sliceperm = perm->perms[mode]; idx_t * const sliceiperm = perm->iperms[mode]; idx_t const * const sptr = ft->sptr; for(idx_t s=0; s < nslices; ++s) { for(idx_t f=sptr[s]; f < sptr[s+1]; ++f) { slice[f] = s; } /* mark perm as incomplete */ sliceperm[s] = nslices; sliceiperm[s] = nslices; } idx_t * pptr = NULL; idx_t * plookup = NULL; build_pptr(parts, nparts, nfibs, &pptr, &plookup); idx_t sliceptr = 0; idx_t uncutptr = 0; /* order all uncut slices first */ for(idx_t p=0; p < nparts; ++p) { uncutptr = 0; /* for each fiber in partition */ for(idx_t j=pptr[p]; j < pptr[p+1]; ++j) { idx_t const fib = plookup[j]; idx_t const s = slice[fib]; if(sliceperm[s] == nslices) { sliceiperm[sliceptr] = s; sliceperm[s] = sliceptr++; } continue; /* move to uncut slice (or past it) */ while(uncutptr < nuncut && uncut[uncutptr] < s) { ++uncutptr; } if(uncutptr == nuncut) { break; } /* mark s if it is uncut and not already marked */ if(uncut[uncutptr] == s && sliceperm[s] == nslices) { sliceiperm[sliceptr] = s; sliceperm[s] = sliceptr++; } } } printf("placed: %"SPLATT_PF_IDX"\n", sliceptr); /* place untouched slices at end of permutation */ for(idx_t s=0; s < nslices; ++s) { if(sliceperm[s] == nslices) { sliceiperm[sliceptr] = s; sliceperm[s] = sliceptr++; } } assert(sliceptr == nslices); free(pptr); free(plookup); free(slice); } static void p_reorder_fibs( sptensor_t * const tt, ftensor_t const * const ft, idx_t const * const parts, idx_t const nparts, idx_t const * const uncut, idx_t const nuncut, permutation_t * const perm, idx_t const mode) { idx_t const pm = ft->dim_perm[1]; idx_t const nslices = ft->dims[mode]; idx_t const nfids = ft->dims[pm]; idx_t const nfibs = ft->nfibs; idx_t const * const fids = ft->fids; idx_t * const fidperm = perm->perms[pm]; idx_t * const fidiperm = perm->iperms[pm]; idx_t const * const sptr = ft->sptr; for(idx_t f=0; f < nfids; ++f) { /* mark perm as incomplete */ fidperm[f] = nfids; fidiperm[f] = nfids; } idx_t * pptr = NULL; idx_t * plookup = NULL; build_pptr(parts, nparts, nfibs, &pptr, &plookup); idx_t fidptr = 0; idx_t uncutptr = 0; idx_t uncutstart = 0; while(uncut[uncutstart] < nslices) { ++uncutstart; } /* order all uncut fids first */ for(idx_t p=0; p < nparts; ++p) { /* for each fiber in partition */ for(idx_t j=pptr[p]; j < pptr[p+1]; ++j) { uncutptr = uncutstart; idx_t const fib = plookup[j]; idx_t const s = fids[fib]; if(fidperm[s] == nfids) { fidiperm[fidptr] = s; fidperm[s] = fidptr++; } continue; /* move to uncut slice (or past it) */ while(uncutptr < nuncut && uncut[uncutptr] < (s + nslices)) { ++uncutptr; } if(uncutptr == nuncut) { break; } /* mark s if it is uncut and not already marked */ if(uncut[uncutptr] == (s + nslices) && fidperm[s] == nfids) { fidiperm[fidptr] = s; fidperm[s] = fidptr++; } } } /* place untouched slices at end of permutation */ printf("placed: %"SPLATT_PF_IDX"\n", fidptr); for(idx_t s=0; s < nfids; ++s) { if(fidperm[s] == nfids) { fidiperm[fidptr] = s; fidperm[s] = fidptr++; } } assert(fidptr == nfids); free(pptr); free(plookup); } static void p_reorder_inds( sptensor_t * const tt, ftensor_t const * const ft, idx_t const * const parts, idx_t const nparts, idx_t const * const uncut, idx_t const nuncut, permutation_t * const perm, idx_t const mode) { idx_t const pm = ft->dim_perm[2]; idx_t * const indperm = perm->perms[pm]; idx_t * const indiperm = perm->iperms[pm]; idx_t const nslices = ft->dims[mode]; idx_t const nfids = ft->dims[ft->dim_perm[1]]; idx_t const ninds = ft->dims[pm]; idx_t const nfibs = ft->nfibs; idx_t const * const fptr = ft->fptr; idx_t const * const inds = ft->inds; /* mark perm as incomplete */ for(idx_t f=0; f < ninds; ++f) { indperm[f] = ninds; indiperm[f] = ninds; } idx_t * pptr = NULL; idx_t * plookup = NULL; build_pptr(parts, nparts, nfibs, &pptr, &plookup); idx_t fidptr = 0; idx_t uncutptr = 0; idx_t uncutstart = 0; while(uncut[uncutstart] < nslices + nfids) { ++uncutstart; } idx_t indptr = 0; /* order all uncut fids first */ for(idx_t p=0; p < nparts; ++p) { /* for each fiber in partition */ for(idx_t j=pptr[p]; j < pptr[p+1]; ++j) { uncutptr = uncutstart; /* traverse fiber and mark inds */ idx_t const fib = plookup[j]; for(idx_t j=fptr[fib]; j < fptr[fib+1]; ++j) { idx_t const s = inds[j]; if(indperm[s] == ninds) { indiperm[indptr] = s; indperm[s] = indptr++; } continue; while(uncutptr < nuncut && uncut[uncutptr] < (s + nslices + nfids)) { ++uncutptr; } if(uncutptr == nuncut) { break; } /* mark s if it is uncut and not already marked */ if(uncut[uncutptr] == (s + nslices + nfids) && indperm[s] == ninds) { indiperm[indptr] = s; indperm[s] = indptr++; } } } } /* place untouched slices at end of permutation */ printf("placed: %"SPLATT_PF_IDX"\n", indptr); for(idx_t s=0; s < ninds; ++s) { if(indperm[s] == ninds) { indiperm[indptr] = s; indperm[s] = indptr++; } } assert(indptr == ninds); free(pptr); free(plookup); } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ permutation_t * tt_perm( sptensor_t * const tt, splatt_perm_type const type, idx_t const mode, char const * const pfile) { timer_start(&timers[TIMER_REORDER]); if(type != PERM_RAND && type != PERM_BFS && type != PERM_RCM && type != PERM_MATCHING && pfile == NULL) { fprintf(stderr, "SPLATT: permutation file must be supplied for now.\n"); exit(1); } idx_t nvtxs = 0; idx_t * parts = NULL; idx_t nparts = 0; ftensor_t ft; permutation_t * perm = NULL; switch(type) { case PERM_RAND: perm = perm_rand(tt); break; case PERM_GRAPH: for(idx_t m=0; m < tt->nmodes; ++m) { nvtxs += tt->dims[m]; } parts = part_read(pfile, nvtxs, &nparts); perm = perm_graph(tt, parts, nparts); break; case PERM_HGRAPH: ften_alloc(&ft, tt, mode, 0); parts = part_read(pfile, ft.nfibs, &nparts); perm = perm_hgraph(tt, &ft, parts, nparts, mode); ften_free(&ft); break; case PERM_BFS: perm = perm_bfs(tt); break; case PERM_RCM: perm = perm_rcm(tt); break; case PERM_MATCHING: perm = perm_matching(tt); break; default: break; } free(parts); timer_stop(&timers[TIMER_REORDER]); return perm; } void build_pptr( idx_t const * const parts, idx_t const nparts, idx_t const nvtxs, idx_t ** ret_pptr, idx_t ** ret_plookup) { /* pptr marks the size of each partition (in vtxs, not nnz) */ idx_t * pptr = (idx_t *) calloc(nparts+1, sizeof(idx_t)); for(idx_t v=0; v < nvtxs; ++v) { pptr[1+parts[v]]++; } /* prefix sum of pptr */ idx_t saved = pptr[1]; pptr[1] = 0; for(idx_t p=2; p <= nparts; ++p) { idx_t tmp = pptr[p]; pptr[p] = pptr[p-1] + saved; saved = tmp; } idx_t * plookup = (idx_t *) splatt_malloc(nvtxs * sizeof(idx_t)); for(idx_t f=0; f < nvtxs; ++f) { idx_t const index = pptr[1+parts[f]]++; plookup[index] = f; } *ret_pptr = pptr; *ret_plookup = plookup; } void perm_apply( sptensor_t * const tt, idx_t ** perm) { idx_t const nnz = tt->nnz; for(idx_t m=0; m < tt->nmodes; ++m) { fidx_t * const ind = tt->ind[m]; idx_t const * const p = perm[m]; #pragma omp parallel for for(idx_t n=0; n < nnz; ++n) { ind[n] = p[ind[n]]; } } } permutation_t * perm_hgraph( sptensor_t * const tt, ftensor_t const * const ft, idx_t const * const parts, idx_t const nparts, idx_t const mode) { permutation_t * perm = perm_alloc(tt->dims, tt->nmodes); hgraph_t * hg = hgraph_fib_alloc(ft, mode); idx_t const nvtxs = ft->nfibs; idx_t nhedges = 0; for(idx_t m=0; m < ft->nmodes; ++m) { nhedges += ft->dims[m]; } printf("nvtxs: %"SPLATT_PF_IDX" nhedges: %"SPLATT_PF_IDX" nparts: %"SPLATT_PF_IDX"\n", nvtxs, nhedges, nparts); idx_t ncut = 0; idx_t * uncuts = hgraph_uncut(hg, parts, &ncut); hgraph_free(hg); printf("cut: %"SPLATT_PF_IDX" notcut: %"SPLATT_PF_IDX"\n", nhedges - ncut, ncut); idx_t nslices = 0; idx_t nfibs = 0; idx_t ninds = 0; for(idx_t n=0; n < ncut; ++n) { if(uncuts[n] < ft->dims[mode]) { ++nslices; } else if(uncuts[n] < ft->dims[mode] + ft->dims[ft->dim_perm[1]]) { ++nfibs; } else { ++ninds; } } printf("slices: %"SPLATT_PF_IDX" fibs: %"SPLATT_PF_IDX" inds: %"SPLATT_PF_IDX"\n", nslices, nfibs, ninds); p_reorder_slices(tt, ft, parts, nparts, uncuts, ncut, perm, mode); p_reorder_fibs(tt, ft, parts, nparts, uncuts, ncut, perm, mode); p_reorder_inds(tt, ft, parts, nparts, uncuts, ncut, perm, mode); /* actually apply permutation */ perm_apply(tt, perm->perms); free(uncuts); return perm; } permutation_t * perm_graph( sptensor_t * const tt, idx_t const * const parts, idx_t const nparts) { idx_t const nmodes = tt->nmodes; idx_t const * const dims = tt->dims; permutation_t * perm = perm_alloc(dims, nmodes); idx_t mkrs[MAX_NMODES]; idx_t nvtxs = 0; for(idx_t m=0; m < nmodes; ++m) { nvtxs += dims[m]; mkrs[m] = 0; for(idx_t n=0; n < dims[m]; ++n) { perm->perms[m][n] = dims[m]; perm->iperms[m][n] = dims[m]; } } printf("nvtxs: %"SPLATT_PF_IDX" nparts: %"SPLATT_PF_IDX"\n", nvtxs, nparts); idx_t * pptr = NULL; idx_t * plookup = NULL; build_pptr(parts, nparts, nvtxs, &pptr, &plookup); for(idx_t p=0; p < nparts; ++p) { for(idx_t j=pptr[p]; j < pptr[p+1]; ++j) { idx_t v = plookup[j]; /* figure out which mode vtx belongs in */ for(idx_t m=0; m < nmodes; ++m) { if(v < dims[m]) { /* reorder v! each vtx can only appear once per partition, so don't * check for previous assignment */ perm->iperms[m][mkrs[m]] = v; perm->perms[m][v] = mkrs[m]++; break; } /* not found in this mode, try next one */ v -= dims[m]; } } } perm_apply(tt, perm->perms); free(pptr); free(plookup); return perm; } permutation_t * perm_identity( idx_t const * const dims, idx_t const nmodes) { permutation_t * perm = perm_alloc(dims, nmodes); for(idx_t m=0; m < nmodes; ++m) { #pragma omp parallel for for(idx_t i=0; i < dims[m]; ++i) { perm->perms[m][i] = i; perm->iperms[m][i] = i; } } return perm; } permutation_t * perm_alloc( idx_t const * const dims, idx_t const nmodes) { permutation_t * perm = (permutation_t *) splatt_malloc(sizeof(permutation_t)); for(idx_t m=0; m < nmodes; ++m) { perm->perms[m] = (idx_t *) splatt_malloc(dims[m] * sizeof(idx_t)); perm->iperms[m] = (idx_t *) splatt_malloc(dims[m] * sizeof(idx_t)); } for(idx_t m=nmodes; m < MAX_NMODES; ++m ) { perm->perms[m] = NULL; perm->iperms[m] = NULL; } return perm; } permutation_t * perm_rand( sptensor_t * const tt) { idx_t const nmodes = tt->nmodes; idx_t const * const dims = tt->dims; permutation_t * perm = perm_alloc(dims, nmodes); for(idx_t m=0; m < nmodes; ++m) { /* initialize perm */ for(idx_t n=0; n < dims[m]; ++n){ perm->perms[m][n] = n; } /* shuffle perm */ for(idx_t n=0; n < dims[m]; ++n) { /* random idx in range [n, dims[m]) */ idx_t j = (rand_idx() % dims[m] - n) + n; /* swap n and j */ idx_t tmp = perm->perms[m][n]; perm->perms[m][n] = j; perm->perms[m][j] = tmp; } /* now fill in iperms */ for(idx_t n=0; n < dims[m]; ++n) { perm->iperms[m][perm->perms[m][n]] = n; } } perm_apply(tt, perm->perms); return perm; } void perm_free( permutation_t * perm) { for(idx_t m=0; m < MAX_NMODES; ++m) { free(perm->perms[m]); free(perm->iperms[m]); } free(perm); } /****************************************************************************** * MATRIX REORDER FUNCTIONS *****************************************************************************/ matrix_t * perm_matrix( matrix_t const * const mat, idx_t const * const perm, matrix_t * retmat) { timer_start(&timers[TIMER_REORDER]); idx_t const I = mat->I; idx_t const J = mat->J; /* allocate retmat if it isn't supplied */ if(retmat == NULL) { retmat = mat_alloc(I, J); retmat->rowmajor = mat->rowmajor; } /* support rowmajor and colmajor */ if(mat->rowmajor) { for(idx_t i=0; i < I; ++i) { for(idx_t j=0; j < J; ++j) { retmat->vals[j + (perm[i]*J)] = mat->vals[j + (i * J)]; } } } else { for(idx_t i=0; i < I; ++i) { for(idx_t j=0; j < J; ++j) { retmat->vals[perm[i] + (j*I)] = mat->vals[i + (j * I)]; } } } timer_stop(&timers[TIMER_REORDER]); return retmat; }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ComplexImages) #endif proceed=SetImageProgress(images,ComplexImageTag,progress++, images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) CopyMagickMemory(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) ResetMagickMemory(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) ResetMagickMemory(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); ResetMagickMemory(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) CopyMagickMemory(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) CopyMagickMemory(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
alloc_benchmark.c
// SPDX-License-Identifier: BSD-2-Clause /* Copyright (C) 2016 - 2020 Intel Corporation. */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <unistd.h> #include <stdint.h> #include <limits.h> #ifdef _OPENMP #include <omp.h> #endif #if defined(HBWMALLOC) #include <hbwmalloc.h> #define MALLOC_FN hbw_malloc #define FREE_FN hbw_free #elif defined (TBBMALLOC) #include "tbbmalloc.h" void *(*scalable_malloc)(size_t); void *(*scalable_realloc)(void *, size_t); void *(*scalable_calloc)(size_t, size_t); void (*scalable_free)(void *); #define MALLOC_FN scalable_malloc #define FREE_FN scalable_free #elif defined (PMEMMALLOC) #include <sys/stat.h> #include "memkind.h" #define MALLOC_FN(x) memkind_malloc(pmem_bench_kind, (x)) #define FREE_FN(x) memkind_free(pmem_bench_kind, (x)) static const size_t PMEM_PART_SIZE = 0; static const char *PMEM_DIR = "/tmp/"; static memkind_t pmem_bench_kind; #else #define MALLOC_FN malloc #define FREE_FN free #endif double ctimer(void); void usage(char *name); int main(int argc, char *argv[]) { #ifdef _OPENMP int nthr = omp_get_max_threads(); #else int nthr = 1; #endif long n, size; size_t alloc_size; unsigned long i; double dt, t_start, t_end, t_malloc, t_free, t_first_malloc, t_first_free, malloc_time = 0.0, free_time = 0.0, first_malloc_time, first_free_time; void *ptr; #ifdef TBBMALLOC int ret; ret = load_tbbmalloc_symbols(); if (ret) { printf("Error: TBB symbols not loaded (ret: %d)\n", ret); return EXIT_FAILURE; } #endif #ifdef PMEMMALLOC struct stat st; /* Handle command line arguments */ if (argc == 3 || argc == 4) { n = atol(argv[1]); size = atol(argv[2]); if (argc == 4) { if (stat(argv[3], &st) != 0 || !S_ISDIR(st.st_mode)) { usage(argv[0]); return EXIT_FAILURE; } else { PMEM_DIR = argv[3]; } } } if ((argc != 3 && argc != 4) || n < 0 || size < 0 || size > (LONG_MAX >> 10)) { usage(argv[0]); return EXIT_FAILURE; } int err = memkind_create_pmem(PMEM_DIR, PMEM_PART_SIZE, &pmem_bench_kind); if (err) { printf("Error: memkind_create_pmem failed %d\n", err); return EXIT_FAILURE; } #else /* Handle command line arguments */ if (argc == 3) { n = atol(argv[1]); size = atol(argv[2]); } if (argc != 3 || n < 0 || size < 0 || size > (LONG_MAX >> 10)) { usage(argv[0]); return EXIT_FAILURE; } #endif alloc_size = (size_t) size * 1024; /* Get pagesize and compute page_mask */ const size_t page_size = sysconf(_SC_PAGESIZE); const size_t page_mask = ~(page_size-1); /* Warm up */ t_first_malloc = ctimer(); ptr = MALLOC_FN(alloc_size); first_malloc_time = ctimer() - t_first_malloc; if (ptr == NULL) { printf("Error: first allocation failed\n"); return EXIT_FAILURE; } t_first_free = ctimer(); FREE_FN(ptr); first_free_time = ctimer() - t_first_free; ptr = NULL; t_start = ctimer(); #pragma omp parallel private(i,t_malloc,t_free,ptr) reduction(max:malloc_time,free_time) { malloc_time = 0.0; free_time = 0.0; for (i=0; i<n; i++) { t_malloc = ctimer(); ptr = (void *) MALLOC_FN(alloc_size); malloc_time += ctimer() - t_malloc; #pragma omp critical { if (ptr == NULL) { printf("Error: allocation failed\n"); exit(EXIT_FAILURE); } } /* Make sure to touch every page */ char *end = ptr + alloc_size; char *aligned_beg = (char *)((uintptr_t)ptr & page_mask); while(aligned_beg < end) { char *temp_ptr = (char *) aligned_beg; char value = temp_ptr[0]; temp_ptr[0] = value; aligned_beg += page_size; } t_free = ctimer(); FREE_FN(ptr); free_time += ctimer() - t_free; ptr = NULL; } } t_end = ctimer(); dt = t_end - t_start; printf("%d %lu %8.6f %8.6f %8.6f %8.6f %8.6f\n", nthr, size, dt/n, malloc_time/n, free_time/n, first_malloc_time, first_free_time); #ifdef PMEMMALLOC err = memkind_destroy_kind(pmem_bench_kind); if (err) { printf("Error: memkind_destroy_kind failed %d\n", err); return EXIT_FAILURE; } #endif return EXIT_SUCCESS; } void usage(char *name) { #ifdef PMEMMALLOC printf("Usage: %s <N> <SIZE> [DIR], where \n" "N is an number of repetitions \n" "SIZE is an allocation size in kbytes\n" "DIR is a custom path for PMEM kind, (default: \"/tmp/\")\n", name); #else printf("Usage: %s <N> <SIZE>, where \n" "N is an number of repetitions \n" "SIZE is an allocation size in kbytes\n", name); #endif } inline double ctimer() { struct timeval tmr; gettimeofday(&tmr, NULL); /* Return time in ms */ return (tmr.tv_sec + tmr.tv_usec/1000000.0)*1000; }
GB_unaryop__one_int64_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__one_int64_int64 // op(A') function: GB_tran__one_int64_int64 // C type: int64_t // A type: int64_t // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ int64_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CASTING(z, x) \ ; ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ONE || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__one_int64_int64 ( int64_t *restrict Cx, const int64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__one_int64_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
zlacpy.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" /***************************************************************************//** * * @ingroup plasma_lacpy * * Copies general rectangular or upper or lower triangular part of * a two-dimensional m-by-n matrix A to another m-by-n matrix B. * ******************************************************************************* * * @param[in] uplo * Specifies the part of the matrix A to be copied to B. * - PlasmaGeneral: General rectangular matrix A * - PlasmaUpper: Upper triangular part of A * - PlasmaLower: Lower triangular part of A * * @param[in] m * The number of rows of the matrix A. m >= 0. * * @param[in] n * The number of columns of the matrix A. n >= 0. * * @param[in] pA * The m-by-n matrix A. If uplo = PlasmaUpper, only the upper trapezium * is accessed; if uplo = PlasmaLower, only the lower trapezium is * accessed. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,m). * * @param[out] pB * The m-by-n matrix B. * On exit, B = A in the locations specified by uplo. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_zlacpy * @sa plasma_clacpy * @sa plasma_dlacpy * @sa plasma_slacpy * ******************************************************************************/ int plasma_zlacpy(plasma_enum_t uplo, plasma_enum_t transa, int m, int n, plasma_complex64_t *pA, int lda, plasma_complex64_t *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((uplo != PlasmaGeneral) && (uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); return -2; } if (m < 0) { plasma_error("illegal value of m"); return -3; } if (n < 0) { plasma_error("illegal value of n"); return -4; } if (transa != PlasmaNoTrans && m != n) { plasma_error("illegal value of m and n"); return -3; } if (lda < imax(1, m)) { plasma_error("illegal value of lda"); return -6; } if (ldb < imax(1, (transa == PlasmaGeneral ? m : n))) { plasma_error("illegal value of ldb"); return -8; } // quick return if (imin(n, m) == 0) return PlasmaSuccess; // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A, B; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_general_desc_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_general_desc_create() failed"); plasma_desc_destroy(&A); return retval; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, sequence, &request); plasma_omp_zge2desc(pB, ldb, B, sequence, &request); // Call tile async function. plasma_omp_zlacpy(uplo, transa, A, B, sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, sequence, &request); plasma_omp_zdesc2ge(B, pB, ldb, sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); // Return status. int status = sequence->status; plasma_sequence_destroy(sequence); return status; } /***************************************************************************//** * * @ingroup plasma_lacpy * * Copies general rectangular or upper or lower triangular part of * a two-dimensional m-by-n matrix A to another m-by-n matrix B. Non-blocking * tile version of plasma_zlacpy(). May return before the computation is * finished. Operates on matrices stored by tiles. All matrices are passed * through descriptors. All dimensions are taken from the descriptors. Allows * for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * Specifies the part of the matrix A to be copied to B. * - PlasmaGeneral: General rectangular matrix A * - PlasmaUpper: Upper triangular part of A * - PlasmaLower: Lower triangular part of A * * @param[in] transa * - PlasmaNoTrans: A is not transposed, * - PlasmaTrans: A is transposed, * - PlasmaConjTrans: A is conjugate transposed. * * @param[in] A * Descriptor of matrix A. * * @param[out] B * Descriptor of matrix B. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check the * sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zlacpy * @sa plasma_omp_clacpy * @sa plasma_omp_dlacpy * @sa plasma_omp_slacpy * ******************************************************************************/ void plasma_omp_zlacpy(plasma_enum_t uplo, plasma_enum_t transa, plasma_desc_t A, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaGeneral) && (uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((transa != PlasmaNoTrans) && (transa != PlasmaTrans) && (transa != PlasmaConjTrans)) { plasma_error("illegal value of transa"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (imin(A.m, A.n) == 0) return; // Call the parallel function. plasma_pzlacpy(uplo, transa, A, B, sequence, request); }
DRB097-target-teams-distribute-orig-no.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor 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. The GNU C 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 the GNU C Library; if not, see <http:www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: [email protected], [email protected], [email protected], [email protected], [email protected]) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https:github.comLLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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 <stdio.h> /* use of omp target + teams + distribute + parallel for */ int main(int argc, char * argv[]) { int i, i2; int len = 2560; double sum = 0.0, sum2 = 0.0; double a[len], b[len]; /* Initialize with some values */ int _ret_val_0; #pragma cetus private(i) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i) for (i=0; i<len; i ++ ) { a[i]=(((double)i)/2.0); b[i]=(((double)i)/3.0); } #pragma cetus private(i, i2) #pragma loop name main#1 #pragma cetus reduction(+: sum) #pragma cetus parallel #pragma omp parallel for private(i, i2) reduction(+: sum) for (i2=0; i2<len; i2+=256) { #pragma cetus private(i) #pragma loop name main#1#0 #pragma cetus reduction(+: sum) #pragma cetus parallel #pragma omp parallel for private(i) reduction(+: sum) for (i=i2; i<(((i2+256)<len) ? (i2+256) : len); i ++ ) { sum+=(a[i]*b[i]); } } /* CPU reference computation */ #pragma cetus private(i) #pragma loop name main#2 #pragma cetus reduction(+: sum2) #pragma cetus parallel #pragma omp parallel for private(i) reduction(+: sum2) for (i=0; i<len; i ++ ) { sum2+=(a[i]*b[i]); } printf("sum=%f sum2=%f\n", sum, sum2); _ret_val_0=0; return _ret_val_0; }
dds.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD DDDD SSSSS % % D D D D SS % % D D D D SSS % % D D D D SS % % DDDD DDDD SSSSS % % % % % % Read/Write Microsoft Direct Draw Surface Image Format % % % % Software Design % % Bianca van Schaik % % March 2008 % % Dirk Lemstra % % September 2013 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" /* Definitions */ #define DDSD_CAPS 0x00000001 #define DDSD_HEIGHT 0x00000002 #define DDSD_WIDTH 0x00000004 #define DDSD_PITCH 0x00000008 #define DDSD_PIXELFORMAT 0x00001000 #define DDSD_MIPMAPCOUNT 0x00020000 #define DDSD_LINEARSIZE 0x00080000 #define DDSD_DEPTH 0x00800000 #define DDPF_ALPHAPIXELS 0x00000001 #define DDPF_FOURCC 0x00000004 #define DDPF_RGB 0x00000040 #define DDPF_LUMINANCE 0x00020000 #define FOURCC_DXT1 0x31545844 #define FOURCC_DXT3 0x33545844 #define FOURCC_DXT5 0x35545844 #define DDSCAPS_COMPLEX 0x00000008 #define DDSCAPS_TEXTURE 0x00001000 #define DDSCAPS_MIPMAP 0x00400000 #define DDSCAPS2_CUBEMAP 0x00000200 #define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400 #define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800 #define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000 #define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000 #define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000 #define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000 #define DDSCAPS2_VOLUME 0x00200000 #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1) #endif /* Structure declarations. */ typedef struct _DDSPixelFormat { size_t flags, fourcc, rgb_bitcount, r_bitmask, g_bitmask, b_bitmask, alpha_bitmask; } DDSPixelFormat; typedef struct _DDSInfo { size_t flags, height, width, pitchOrLinearSize, depth, mipmapcount, ddscaps1, ddscaps2; DDSPixelFormat pixelformat; } DDSInfo; typedef struct _DDSColors { unsigned char r[4], g[4], b[4], a[4]; } DDSColors; typedef struct _DDSVector4 { float x, y, z, w; } DDSVector4; typedef struct _DDSVector3 { float x, y, z; } DDSVector3; typedef struct _DDSSourceBlock { unsigned char start, end, error; } DDSSourceBlock; typedef struct _DDSSingleColourLookup { DDSSourceBlock sources[2]; } DDSSingleColourLookup; typedef MagickBooleanType DDSDecoder(const ImageInfo *,Image *,DDSInfo *,const MagickBooleanType, ExceptionInfo *); typedef MagickBooleanType DDSPixelDecoder(Image *,DDSInfo *,ExceptionInfo *); static const DDSSingleColourLookup DDSLookup_5_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 1 } } }, { { { 0, 0, 2 }, { 0, 1, 0 } } }, { { { 0, 0, 3 }, { 0, 1, 1 } } }, { { { 0, 0, 4 }, { 0, 2, 1 } } }, { { { 1, 0, 3 }, { 0, 2, 0 } } }, { { { 1, 0, 2 }, { 0, 2, 1 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 1, 2, 1 } } }, { { { 1, 0, 2 }, { 1, 2, 0 } } }, { { { 1, 0, 3 }, { 0, 4, 0 } } }, { { { 1, 0, 4 }, { 0, 5, 1 } } }, { { { 2, 0, 3 }, { 0, 5, 0 } } }, { { { 2, 0, 2 }, { 0, 5, 1 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 2, 3, 1 } } }, { { { 2, 0, 2 }, { 2, 3, 0 } } }, { { { 2, 0, 3 }, { 0, 7, 0 } } }, { { { 2, 0, 4 }, { 1, 6, 1 } } }, { { { 3, 0, 3 }, { 1, 6, 0 } } }, { { { 3, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 2 }, { 0, 10, 1 } } }, { { { 3, 0, 3 }, { 0, 10, 0 } } }, { { { 3, 0, 4 }, { 2, 7, 1 } } }, { { { 4, 0, 4 }, { 2, 7, 0 } } }, { { { 4, 0, 3 }, { 0, 11, 0 } } }, { { { 4, 0, 2 }, { 1, 10, 1 } } }, { { { 4, 0, 1 }, { 1, 10, 0 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 1 } } }, { { { 4, 0, 2 }, { 0, 13, 0 } } }, { { { 4, 0, 3 }, { 0, 13, 1 } } }, { { { 4, 0, 4 }, { 0, 14, 1 } } }, { { { 5, 0, 3 }, { 0, 14, 0 } } }, { { { 5, 0, 2 }, { 2, 11, 1 } } }, { { { 5, 0, 1 }, { 2, 11, 0 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 1, 14, 1 } } }, { { { 5, 0, 2 }, { 1, 14, 0 } } }, { { { 5, 0, 3 }, { 0, 16, 0 } } }, { { { 5, 0, 4 }, { 0, 17, 1 } } }, { { { 6, 0, 3 }, { 0, 17, 0 } } }, { { { 6, 0, 2 }, { 0, 17, 1 } } }, { { { 6, 0, 1 }, { 0, 18, 1 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 2, 15, 1 } } }, { { { 6, 0, 2 }, { 2, 15, 0 } } }, { { { 6, 0, 3 }, { 0, 19, 0 } } }, { { { 6, 0, 4 }, { 1, 18, 1 } } }, { { { 7, 0, 3 }, { 1, 18, 0 } } }, { { { 7, 0, 2 }, { 0, 20, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 21, 1 } } }, { { { 7, 0, 2 }, { 0, 22, 1 } } }, { { { 7, 0, 3 }, { 0, 22, 0 } } }, { { { 7, 0, 4 }, { 2, 19, 1 } } }, { { { 8, 0, 4 }, { 2, 19, 0 } } }, { { { 8, 0, 3 }, { 0, 23, 0 } } }, { { { 8, 0, 2 }, { 1, 22, 1 } } }, { { { 8, 0, 1 }, { 1, 22, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 1 } } }, { { { 8, 0, 2 }, { 0, 25, 0 } } }, { { { 8, 0, 3 }, { 0, 25, 1 } } }, { { { 8, 0, 4 }, { 0, 26, 1 } } }, { { { 9, 0, 3 }, { 0, 26, 0 } } }, { { { 9, 0, 2 }, { 2, 23, 1 } } }, { { { 9, 0, 1 }, { 2, 23, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 1, 26, 1 } } }, { { { 9, 0, 2 }, { 1, 26, 0 } } }, { { { 9, 0, 3 }, { 0, 28, 0 } } }, { { { 9, 0, 4 }, { 0, 29, 1 } } }, { { { 10, 0, 3 }, { 0, 29, 0 } } }, { { { 10, 0, 2 }, { 0, 29, 1 } } }, { { { 10, 0, 1 }, { 0, 30, 1 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 2, 27, 1 } } }, { { { 10, 0, 2 }, { 2, 27, 0 } } }, { { { 10, 0, 3 }, { 0, 31, 0 } } }, { { { 10, 0, 4 }, { 1, 30, 1 } } }, { { { 11, 0, 3 }, { 1, 30, 0 } } }, { { { 11, 0, 2 }, { 4, 24, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 0 }, { 1, 31, 0 } } }, { { { 11, 0, 1 }, { 1, 31, 1 } } }, { { { 11, 0, 2 }, { 2, 30, 1 } } }, { { { 11, 0, 3 }, { 2, 30, 0 } } }, { { { 11, 0, 4 }, { 2, 31, 1 } } }, { { { 12, 0, 4 }, { 2, 31, 0 } } }, { { { 12, 0, 3 }, { 4, 27, 0 } } }, { { { 12, 0, 2 }, { 3, 30, 1 } } }, { { { 12, 0, 1 }, { 3, 30, 0 } } }, { { { 12, 0, 0 }, { 4, 28, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 1 } } }, { { { 12, 0, 2 }, { 3, 31, 0 } } }, { { { 12, 0, 3 }, { 3, 31, 1 } } }, { { { 12, 0, 4 }, { 4, 30, 1 } } }, { { { 13, 0, 3 }, { 4, 30, 0 } } }, { { { 13, 0, 2 }, { 6, 27, 1 } } }, { { { 13, 0, 1 }, { 6, 27, 0 } } }, { { { 13, 0, 0 }, { 4, 31, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 1 } } }, { { { 13, 0, 2 }, { 5, 30, 0 } } }, { { { 13, 0, 3 }, { 8, 24, 0 } } }, { { { 13, 0, 4 }, { 5, 31, 1 } } }, { { { 14, 0, 3 }, { 5, 31, 0 } } }, { { { 14, 0, 2 }, { 5, 31, 1 } } }, { { { 14, 0, 1 }, { 6, 30, 1 } } }, { { { 14, 0, 0 }, { 6, 30, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 1 } } }, { { { 14, 0, 2 }, { 6, 31, 0 } } }, { { { 14, 0, 3 }, { 8, 27, 0 } } }, { { { 14, 0, 4 }, { 7, 30, 1 } } }, { { { 15, 0, 3 }, { 7, 30, 0 } } }, { { { 15, 0, 2 }, { 8, 28, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 0 }, { 7, 31, 0 } } }, { { { 15, 0, 1 }, { 7, 31, 1 } } }, { { { 15, 0, 2 }, { 8, 30, 1 } } }, { { { 15, 0, 3 }, { 8, 30, 0 } } }, { { { 15, 0, 4 }, { 10, 27, 1 } } }, { { { 16, 0, 4 }, { 10, 27, 0 } } }, { { { 16, 0, 3 }, { 8, 31, 0 } } }, { { { 16, 0, 2 }, { 9, 30, 1 } } }, { { { 16, 0, 1 }, { 9, 30, 0 } } }, { { { 16, 0, 0 }, { 12, 24, 0 } } }, { { { 16, 0, 1 }, { 9, 31, 1 } } }, { { { 16, 0, 2 }, { 9, 31, 0 } } }, { { { 16, 0, 3 }, { 9, 31, 1 } } }, { { { 16, 0, 4 }, { 10, 30, 1 } } }, { { { 17, 0, 3 }, { 10, 30, 0 } } }, { { { 17, 0, 2 }, { 10, 31, 1 } } }, { { { 17, 0, 1 }, { 10, 31, 0 } } }, { { { 17, 0, 0 }, { 12, 27, 0 } } }, { { { 17, 0, 1 }, { 11, 30, 1 } } }, { { { 17, 0, 2 }, { 11, 30, 0 } } }, { { { 17, 0, 3 }, { 12, 28, 0 } } }, { { { 17, 0, 4 }, { 11, 31, 1 } } }, { { { 18, 0, 3 }, { 11, 31, 0 } } }, { { { 18, 0, 2 }, { 11, 31, 1 } } }, { { { 18, 0, 1 }, { 12, 30, 1 } } }, { { { 18, 0, 0 }, { 12, 30, 0 } } }, { { { 18, 0, 1 }, { 14, 27, 1 } } }, { { { 18, 0, 2 }, { 14, 27, 0 } } }, { { { 18, 0, 3 }, { 12, 31, 0 } } }, { { { 18, 0, 4 }, { 13, 30, 1 } } }, { { { 19, 0, 3 }, { 13, 30, 0 } } }, { { { 19, 0, 2 }, { 16, 24, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 0 }, { 13, 31, 0 } } }, { { { 19, 0, 1 }, { 13, 31, 1 } } }, { { { 19, 0, 2 }, { 14, 30, 1 } } }, { { { 19, 0, 3 }, { 14, 30, 0 } } }, { { { 19, 0, 4 }, { 14, 31, 1 } } }, { { { 20, 0, 4 }, { 14, 31, 0 } } }, { { { 20, 0, 3 }, { 16, 27, 0 } } }, { { { 20, 0, 2 }, { 15, 30, 1 } } }, { { { 20, 0, 1 }, { 15, 30, 0 } } }, { { { 20, 0, 0 }, { 16, 28, 0 } } }, { { { 20, 0, 1 }, { 15, 31, 1 } } }, { { { 20, 0, 2 }, { 15, 31, 0 } } }, { { { 20, 0, 3 }, { 15, 31, 1 } } }, { { { 20, 0, 4 }, { 16, 30, 1 } } }, { { { 21, 0, 3 }, { 16, 30, 0 } } }, { { { 21, 0, 2 }, { 18, 27, 1 } } }, { { { 21, 0, 1 }, { 18, 27, 0 } } }, { { { 21, 0, 0 }, { 16, 31, 0 } } }, { { { 21, 0, 1 }, { 17, 30, 1 } } }, { { { 21, 0, 2 }, { 17, 30, 0 } } }, { { { 21, 0, 3 }, { 20, 24, 0 } } }, { { { 21, 0, 4 }, { 17, 31, 1 } } }, { { { 22, 0, 3 }, { 17, 31, 0 } } }, { { { 22, 0, 2 }, { 17, 31, 1 } } }, { { { 22, 0, 1 }, { 18, 30, 1 } } }, { { { 22, 0, 0 }, { 18, 30, 0 } } }, { { { 22, 0, 1 }, { 18, 31, 1 } } }, { { { 22, 0, 2 }, { 18, 31, 0 } } }, { { { 22, 0, 3 }, { 20, 27, 0 } } }, { { { 22, 0, 4 }, { 19, 30, 1 } } }, { { { 23, 0, 3 }, { 19, 30, 0 } } }, { { { 23, 0, 2 }, { 20, 28, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 0 }, { 19, 31, 0 } } }, { { { 23, 0, 1 }, { 19, 31, 1 } } }, { { { 23, 0, 2 }, { 20, 30, 1 } } }, { { { 23, 0, 3 }, { 20, 30, 0 } } }, { { { 23, 0, 4 }, { 22, 27, 1 } } }, { { { 24, 0, 4 }, { 22, 27, 0 } } }, { { { 24, 0, 3 }, { 20, 31, 0 } } }, { { { 24, 0, 2 }, { 21, 30, 1 } } }, { { { 24, 0, 1 }, { 21, 30, 0 } } }, { { { 24, 0, 0 }, { 24, 24, 0 } } }, { { { 24, 0, 1 }, { 21, 31, 1 } } }, { { { 24, 0, 2 }, { 21, 31, 0 } } }, { { { 24, 0, 3 }, { 21, 31, 1 } } }, { { { 24, 0, 4 }, { 22, 30, 1 } } }, { { { 25, 0, 3 }, { 22, 30, 0 } } }, { { { 25, 0, 2 }, { 22, 31, 1 } } }, { { { 25, 0, 1 }, { 22, 31, 0 } } }, { { { 25, 0, 0 }, { 24, 27, 0 } } }, { { { 25, 0, 1 }, { 23, 30, 1 } } }, { { { 25, 0, 2 }, { 23, 30, 0 } } }, { { { 25, 0, 3 }, { 24, 28, 0 } } }, { { { 25, 0, 4 }, { 23, 31, 1 } } }, { { { 26, 0, 3 }, { 23, 31, 0 } } }, { { { 26, 0, 2 }, { 23, 31, 1 } } }, { { { 26, 0, 1 }, { 24, 30, 1 } } }, { { { 26, 0, 0 }, { 24, 30, 0 } } }, { { { 26, 0, 1 }, { 26, 27, 1 } } }, { { { 26, 0, 2 }, { 26, 27, 0 } } }, { { { 26, 0, 3 }, { 24, 31, 0 } } }, { { { 26, 0, 4 }, { 25, 30, 1 } } }, { { { 27, 0, 3 }, { 25, 30, 0 } } }, { { { 27, 0, 2 }, { 28, 24, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 0 }, { 25, 31, 0 } } }, { { { 27, 0, 1 }, { 25, 31, 1 } } }, { { { 27, 0, 2 }, { 26, 30, 1 } } }, { { { 27, 0, 3 }, { 26, 30, 0 } } }, { { { 27, 0, 4 }, { 26, 31, 1 } } }, { { { 28, 0, 4 }, { 26, 31, 0 } } }, { { { 28, 0, 3 }, { 28, 27, 0 } } }, { { { 28, 0, 2 }, { 27, 30, 1 } } }, { { { 28, 0, 1 }, { 27, 30, 0 } } }, { { { 28, 0, 0 }, { 28, 28, 0 } } }, { { { 28, 0, 1 }, { 27, 31, 1 } } }, { { { 28, 0, 2 }, { 27, 31, 0 } } }, { { { 28, 0, 3 }, { 27, 31, 1 } } }, { { { 28, 0, 4 }, { 28, 30, 1 } } }, { { { 29, 0, 3 }, { 28, 30, 0 } } }, { { { 29, 0, 2 }, { 30, 27, 1 } } }, { { { 29, 0, 1 }, { 30, 27, 0 } } }, { { { 29, 0, 0 }, { 28, 31, 0 } } }, { { { 29, 0, 1 }, { 29, 30, 1 } } }, { { { 29, 0, 2 }, { 29, 30, 0 } } }, { { { 29, 0, 3 }, { 29, 30, 1 } } }, { { { 29, 0, 4 }, { 29, 31, 1 } } }, { { { 30, 0, 3 }, { 29, 31, 0 } } }, { { { 30, 0, 2 }, { 29, 31, 1 } } }, { { { 30, 0, 1 }, { 30, 30, 1 } } }, { { { 30, 0, 0 }, { 30, 30, 0 } } }, { { { 30, 0, 1 }, { 30, 31, 1 } } }, { { { 30, 0, 2 }, { 30, 31, 0 } } }, { { { 30, 0, 3 }, { 30, 31, 1 } } }, { { { 30, 0, 4 }, { 31, 30, 1 } } }, { { { 31, 0, 3 }, { 31, 30, 0 } } }, { { { 31, 0, 2 }, { 31, 30, 1 } } }, { { { 31, 0, 1 }, { 31, 31, 1 } } }, { { { 31, 0, 0 }, { 31, 31, 0 } } } }; static const DDSSingleColourLookup DDSLookup_6_4[] = { { { { 0, 0, 0 }, { 0, 0, 0 } } }, { { { 0, 0, 1 }, { 0, 1, 0 } } }, { { { 0, 0, 2 }, { 0, 2, 0 } } }, { { { 1, 0, 1 }, { 0, 3, 1 } } }, { { { 1, 0, 0 }, { 0, 3, 0 } } }, { { { 1, 0, 1 }, { 0, 4, 0 } } }, { { { 1, 0, 2 }, { 0, 5, 0 } } }, { { { 2, 0, 1 }, { 0, 6, 1 } } }, { { { 2, 0, 0 }, { 0, 6, 0 } } }, { { { 2, 0, 1 }, { 0, 7, 0 } } }, { { { 2, 0, 2 }, { 0, 8, 0 } } }, { { { 3, 0, 1 }, { 0, 9, 1 } } }, { { { 3, 0, 0 }, { 0, 9, 0 } } }, { { { 3, 0, 1 }, { 0, 10, 0 } } }, { { { 3, 0, 2 }, { 0, 11, 0 } } }, { { { 4, 0, 1 }, { 0, 12, 1 } } }, { { { 4, 0, 0 }, { 0, 12, 0 } } }, { { { 4, 0, 1 }, { 0, 13, 0 } } }, { { { 4, 0, 2 }, { 0, 14, 0 } } }, { { { 5, 0, 1 }, { 0, 15, 1 } } }, { { { 5, 0, 0 }, { 0, 15, 0 } } }, { { { 5, 0, 1 }, { 0, 16, 0 } } }, { { { 5, 0, 2 }, { 1, 15, 0 } } }, { { { 6, 0, 1 }, { 0, 17, 0 } } }, { { { 6, 0, 0 }, { 0, 18, 0 } } }, { { { 6, 0, 1 }, { 0, 19, 0 } } }, { { { 6, 0, 2 }, { 3, 14, 0 } } }, { { { 7, 0, 1 }, { 0, 20, 0 } } }, { { { 7, 0, 0 }, { 0, 21, 0 } } }, { { { 7, 0, 1 }, { 0, 22, 0 } } }, { { { 7, 0, 2 }, { 4, 15, 0 } } }, { { { 8, 0, 1 }, { 0, 23, 0 } } }, { { { 8, 0, 0 }, { 0, 24, 0 } } }, { { { 8, 0, 1 }, { 0, 25, 0 } } }, { { { 8, 0, 2 }, { 6, 14, 0 } } }, { { { 9, 0, 1 }, { 0, 26, 0 } } }, { { { 9, 0, 0 }, { 0, 27, 0 } } }, { { { 9, 0, 1 }, { 0, 28, 0 } } }, { { { 9, 0, 2 }, { 7, 15, 0 } } }, { { { 10, 0, 1 }, { 0, 29, 0 } } }, { { { 10, 0, 0 }, { 0, 30, 0 } } }, { { { 10, 0, 1 }, { 0, 31, 0 } } }, { { { 10, 0, 2 }, { 9, 14, 0 } } }, { { { 11, 0, 1 }, { 0, 32, 0 } } }, { { { 11, 0, 0 }, { 0, 33, 0 } } }, { { { 11, 0, 1 }, { 2, 30, 0 } } }, { { { 11, 0, 2 }, { 0, 34, 0 } } }, { { { 12, 0, 1 }, { 0, 35, 0 } } }, { { { 12, 0, 0 }, { 0, 36, 0 } } }, { { { 12, 0, 1 }, { 3, 31, 0 } } }, { { { 12, 0, 2 }, { 0, 37, 0 } } }, { { { 13, 0, 1 }, { 0, 38, 0 } } }, { { { 13, 0, 0 }, { 0, 39, 0 } } }, { { { 13, 0, 1 }, { 5, 30, 0 } } }, { { { 13, 0, 2 }, { 0, 40, 0 } } }, { { { 14, 0, 1 }, { 0, 41, 0 } } }, { { { 14, 0, 0 }, { 0, 42, 0 } } }, { { { 14, 0, 1 }, { 6, 31, 0 } } }, { { { 14, 0, 2 }, { 0, 43, 0 } } }, { { { 15, 0, 1 }, { 0, 44, 0 } } }, { { { 15, 0, 0 }, { 0, 45, 0 } } }, { { { 15, 0, 1 }, { 8, 30, 0 } } }, { { { 15, 0, 2 }, { 0, 46, 0 } } }, { { { 16, 0, 2 }, { 0, 47, 0 } } }, { { { 16, 0, 1 }, { 1, 46, 0 } } }, { { { 16, 0, 0 }, { 0, 48, 0 } } }, { { { 16, 0, 1 }, { 0, 49, 0 } } }, { { { 16, 0, 2 }, { 0, 50, 0 } } }, { { { 17, 0, 1 }, { 2, 47, 0 } } }, { { { 17, 0, 0 }, { 0, 51, 0 } } }, { { { 17, 0, 1 }, { 0, 52, 0 } } }, { { { 17, 0, 2 }, { 0, 53, 0 } } }, { { { 18, 0, 1 }, { 4, 46, 0 } } }, { { { 18, 0, 0 }, { 0, 54, 0 } } }, { { { 18, 0, 1 }, { 0, 55, 0 } } }, { { { 18, 0, 2 }, { 0, 56, 0 } } }, { { { 19, 0, 1 }, { 5, 47, 0 } } }, { { { 19, 0, 0 }, { 0, 57, 0 } } }, { { { 19, 0, 1 }, { 0, 58, 0 } } }, { { { 19, 0, 2 }, { 0, 59, 0 } } }, { { { 20, 0, 1 }, { 7, 46, 0 } } }, { { { 20, 0, 0 }, { 0, 60, 0 } } }, { { { 20, 0, 1 }, { 0, 61, 0 } } }, { { { 20, 0, 2 }, { 0, 62, 0 } } }, { { { 21, 0, 1 }, { 8, 47, 0 } } }, { { { 21, 0, 0 }, { 0, 63, 0 } } }, { { { 21, 0, 1 }, { 1, 62, 0 } } }, { { { 21, 0, 2 }, { 1, 63, 0 } } }, { { { 22, 0, 1 }, { 10, 46, 0 } } }, { { { 22, 0, 0 }, { 2, 62, 0 } } }, { { { 22, 0, 1 }, { 2, 63, 0 } } }, { { { 22, 0, 2 }, { 3, 62, 0 } } }, { { { 23, 0, 1 }, { 11, 47, 0 } } }, { { { 23, 0, 0 }, { 3, 63, 0 } } }, { { { 23, 0, 1 }, { 4, 62, 0 } } }, { { { 23, 0, 2 }, { 4, 63, 0 } } }, { { { 24, 0, 1 }, { 13, 46, 0 } } }, { { { 24, 0, 0 }, { 5, 62, 0 } } }, { { { 24, 0, 1 }, { 5, 63, 0 } } }, { { { 24, 0, 2 }, { 6, 62, 0 } } }, { { { 25, 0, 1 }, { 14, 47, 0 } } }, { { { 25, 0, 0 }, { 6, 63, 0 } } }, { { { 25, 0, 1 }, { 7, 62, 0 } } }, { { { 25, 0, 2 }, { 7, 63, 0 } } }, { { { 26, 0, 1 }, { 16, 45, 0 } } }, { { { 26, 0, 0 }, { 8, 62, 0 } } }, { { { 26, 0, 1 }, { 8, 63, 0 } } }, { { { 26, 0, 2 }, { 9, 62, 0 } } }, { { { 27, 0, 1 }, { 16, 48, 0 } } }, { { { 27, 0, 0 }, { 9, 63, 0 } } }, { { { 27, 0, 1 }, { 10, 62, 0 } } }, { { { 27, 0, 2 }, { 10, 63, 0 } } }, { { { 28, 0, 1 }, { 16, 51, 0 } } }, { { { 28, 0, 0 }, { 11, 62, 0 } } }, { { { 28, 0, 1 }, { 11, 63, 0 } } }, { { { 28, 0, 2 }, { 12, 62, 0 } } }, { { { 29, 0, 1 }, { 16, 54, 0 } } }, { { { 29, 0, 0 }, { 12, 63, 0 } } }, { { { 29, 0, 1 }, { 13, 62, 0 } } }, { { { 29, 0, 2 }, { 13, 63, 0 } } }, { { { 30, 0, 1 }, { 16, 57, 0 } } }, { { { 30, 0, 0 }, { 14, 62, 0 } } }, { { { 30, 0, 1 }, { 14, 63, 0 } } }, { { { 30, 0, 2 }, { 15, 62, 0 } } }, { { { 31, 0, 1 }, { 16, 60, 0 } } }, { { { 31, 0, 0 }, { 15, 63, 0 } } }, { { { 31, 0, 1 }, { 24, 46, 0 } } }, { { { 31, 0, 2 }, { 16, 62, 0 } } }, { { { 32, 0, 2 }, { 16, 63, 0 } } }, { { { 32, 0, 1 }, { 17, 62, 0 } } }, { { { 32, 0, 0 }, { 25, 47, 0 } } }, { { { 32, 0, 1 }, { 17, 63, 0 } } }, { { { 32, 0, 2 }, { 18, 62, 0 } } }, { { { 33, 0, 1 }, { 18, 63, 0 } } }, { { { 33, 0, 0 }, { 27, 46, 0 } } }, { { { 33, 0, 1 }, { 19, 62, 0 } } }, { { { 33, 0, 2 }, { 19, 63, 0 } } }, { { { 34, 0, 1 }, { 20, 62, 0 } } }, { { { 34, 0, 0 }, { 28, 47, 0 } } }, { { { 34, 0, 1 }, { 20, 63, 0 } } }, { { { 34, 0, 2 }, { 21, 62, 0 } } }, { { { 35, 0, 1 }, { 21, 63, 0 } } }, { { { 35, 0, 0 }, { 30, 46, 0 } } }, { { { 35, 0, 1 }, { 22, 62, 0 } } }, { { { 35, 0, 2 }, { 22, 63, 0 } } }, { { { 36, 0, 1 }, { 23, 62, 0 } } }, { { { 36, 0, 0 }, { 31, 47, 0 } } }, { { { 36, 0, 1 }, { 23, 63, 0 } } }, { { { 36, 0, 2 }, { 24, 62, 0 } } }, { { { 37, 0, 1 }, { 24, 63, 0 } } }, { { { 37, 0, 0 }, { 32, 47, 0 } } }, { { { 37, 0, 1 }, { 25, 62, 0 } } }, { { { 37, 0, 2 }, { 25, 63, 0 } } }, { { { 38, 0, 1 }, { 26, 62, 0 } } }, { { { 38, 0, 0 }, { 32, 50, 0 } } }, { { { 38, 0, 1 }, { 26, 63, 0 } } }, { { { 38, 0, 2 }, { 27, 62, 0 } } }, { { { 39, 0, 1 }, { 27, 63, 0 } } }, { { { 39, 0, 0 }, { 32, 53, 0 } } }, { { { 39, 0, 1 }, { 28, 62, 0 } } }, { { { 39, 0, 2 }, { 28, 63, 0 } } }, { { { 40, 0, 1 }, { 29, 62, 0 } } }, { { { 40, 0, 0 }, { 32, 56, 0 } } }, { { { 40, 0, 1 }, { 29, 63, 0 } } }, { { { 40, 0, 2 }, { 30, 62, 0 } } }, { { { 41, 0, 1 }, { 30, 63, 0 } } }, { { { 41, 0, 0 }, { 32, 59, 0 } } }, { { { 41, 0, 1 }, { 31, 62, 0 } } }, { { { 41, 0, 2 }, { 31, 63, 0 } } }, { { { 42, 0, 1 }, { 32, 61, 0 } } }, { { { 42, 0, 0 }, { 32, 62, 0 } } }, { { { 42, 0, 1 }, { 32, 63, 0 } } }, { { { 42, 0, 2 }, { 41, 46, 0 } } }, { { { 43, 0, 1 }, { 33, 62, 0 } } }, { { { 43, 0, 0 }, { 33, 63, 0 } } }, { { { 43, 0, 1 }, { 34, 62, 0 } } }, { { { 43, 0, 2 }, { 42, 47, 0 } } }, { { { 44, 0, 1 }, { 34, 63, 0 } } }, { { { 44, 0, 0 }, { 35, 62, 0 } } }, { { { 44, 0, 1 }, { 35, 63, 0 } } }, { { { 44, 0, 2 }, { 44, 46, 0 } } }, { { { 45, 0, 1 }, { 36, 62, 0 } } }, { { { 45, 0, 0 }, { 36, 63, 0 } } }, { { { 45, 0, 1 }, { 37, 62, 0 } } }, { { { 45, 0, 2 }, { 45, 47, 0 } } }, { { { 46, 0, 1 }, { 37, 63, 0 } } }, { { { 46, 0, 0 }, { 38, 62, 0 } } }, { { { 46, 0, 1 }, { 38, 63, 0 } } }, { { { 46, 0, 2 }, { 47, 46, 0 } } }, { { { 47, 0, 1 }, { 39, 62, 0 } } }, { { { 47, 0, 0 }, { 39, 63, 0 } } }, { { { 47, 0, 1 }, { 40, 62, 0 } } }, { { { 47, 0, 2 }, { 48, 46, 0 } } }, { { { 48, 0, 2 }, { 40, 63, 0 } } }, { { { 48, 0, 1 }, { 41, 62, 0 } } }, { { { 48, 0, 0 }, { 41, 63, 0 } } }, { { { 48, 0, 1 }, { 48, 49, 0 } } }, { { { 48, 0, 2 }, { 42, 62, 0 } } }, { { { 49, 0, 1 }, { 42, 63, 0 } } }, { { { 49, 0, 0 }, { 43, 62, 0 } } }, { { { 49, 0, 1 }, { 48, 52, 0 } } }, { { { 49, 0, 2 }, { 43, 63, 0 } } }, { { { 50, 0, 1 }, { 44, 62, 0 } } }, { { { 50, 0, 0 }, { 44, 63, 0 } } }, { { { 50, 0, 1 }, { 48, 55, 0 } } }, { { { 50, 0, 2 }, { 45, 62, 0 } } }, { { { 51, 0, 1 }, { 45, 63, 0 } } }, { { { 51, 0, 0 }, { 46, 62, 0 } } }, { { { 51, 0, 1 }, { 48, 58, 0 } } }, { { { 51, 0, 2 }, { 46, 63, 0 } } }, { { { 52, 0, 1 }, { 47, 62, 0 } } }, { { { 52, 0, 0 }, { 47, 63, 0 } } }, { { { 52, 0, 1 }, { 48, 61, 0 } } }, { { { 52, 0, 2 }, { 48, 62, 0 } } }, { { { 53, 0, 1 }, { 56, 47, 0 } } }, { { { 53, 0, 0 }, { 48, 63, 0 } } }, { { { 53, 0, 1 }, { 49, 62, 0 } } }, { { { 53, 0, 2 }, { 49, 63, 0 } } }, { { { 54, 0, 1 }, { 58, 46, 0 } } }, { { { 54, 0, 0 }, { 50, 62, 0 } } }, { { { 54, 0, 1 }, { 50, 63, 0 } } }, { { { 54, 0, 2 }, { 51, 62, 0 } } }, { { { 55, 0, 1 }, { 59, 47, 0 } } }, { { { 55, 0, 0 }, { 51, 63, 0 } } }, { { { 55, 0, 1 }, { 52, 62, 0 } } }, { { { 55, 0, 2 }, { 52, 63, 0 } } }, { { { 56, 0, 1 }, { 61, 46, 0 } } }, { { { 56, 0, 0 }, { 53, 62, 0 } } }, { { { 56, 0, 1 }, { 53, 63, 0 } } }, { { { 56, 0, 2 }, { 54, 62, 0 } } }, { { { 57, 0, 1 }, { 62, 47, 0 } } }, { { { 57, 0, 0 }, { 54, 63, 0 } } }, { { { 57, 0, 1 }, { 55, 62, 0 } } }, { { { 57, 0, 2 }, { 55, 63, 0 } } }, { { { 58, 0, 1 }, { 56, 62, 1 } } }, { { { 58, 0, 0 }, { 56, 62, 0 } } }, { { { 58, 0, 1 }, { 56, 63, 0 } } }, { { { 58, 0, 2 }, { 57, 62, 0 } } }, { { { 59, 0, 1 }, { 57, 63, 1 } } }, { { { 59, 0, 0 }, { 57, 63, 0 } } }, { { { 59, 0, 1 }, { 58, 62, 0 } } }, { { { 59, 0, 2 }, { 58, 63, 0 } } }, { { { 60, 0, 1 }, { 59, 62, 1 } } }, { { { 60, 0, 0 }, { 59, 62, 0 } } }, { { { 60, 0, 1 }, { 59, 63, 0 } } }, { { { 60, 0, 2 }, { 60, 62, 0 } } }, { { { 61, 0, 1 }, { 60, 63, 1 } } }, { { { 61, 0, 0 }, { 60, 63, 0 } } }, { { { 61, 0, 1 }, { 61, 62, 0 } } }, { { { 61, 0, 2 }, { 61, 63, 0 } } }, { { { 62, 0, 1 }, { 62, 62, 1 } } }, { { { 62, 0, 0 }, { 62, 62, 0 } } }, { { { 62, 0, 1 }, { 62, 63, 0 } } }, { { { 62, 0, 2 }, { 63, 62, 0 } } }, { { { 63, 0, 1 }, { 63, 63, 1 } } }, { { { 63, 0, 0 }, { 63, 63, 0 } } } }; static const DDSSingleColourLookup* DDS_LOOKUP[] = { DDSLookup_5_4, DDSLookup_6_4, DDSLookup_5_4 }; /* Macros */ #define C565_r(x) (((x) & 0xF800) >> 11) #define C565_g(x) (((x) & 0x07E0) >> 5) #define C565_b(x) ((x) & 0x001F) #define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2)) #define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4)) #define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2)) #define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1) #define FixRange(min, max, steps) \ if (min > max) \ min = max; \ if ((ssize_t) max - min < steps) \ max = MagickMin(min + steps, 255); \ if ((ssize_t) max - min < steps) \ min = MagickMax(0, (ssize_t) max - steps) #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z) #define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \ = value #define VectorInit3(vector, value) vector.x = vector.y = vector.z = value #define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \ g && mask.b_bitmask == b && mask.alpha_bitmask == a) /* Forward declarations */ /* Forward declarations */ static MagickBooleanType ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3, DDSVector4 *, DDSVector4 *, unsigned char *, size_t), ReadDDSInfo(Image *,DDSInfo *), ReadDXT1(const ImageInfo *,Image *,DDSInfo *,const MagickBooleanType, ExceptionInfo *), ReadDXT3(const ImageInfo *,Image *,DDSInfo *,const MagickBooleanType, ExceptionInfo *), ReadDXT5(const ImageInfo *,Image *,DDSInfo *,const MagickBooleanType, ExceptionInfo *), ReadUncompressedRGB(const ImageInfo *,Image *,DDSInfo *, const MagickBooleanType,ExceptionInfo *), ReadUncompressedRGBA(const ImageInfo *,Image *,DDSInfo *, const MagickBooleanType,ExceptionInfo *), SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), WriteDDSImage(const ImageInfo *,Image *,ExceptionInfo *), WriteMipmaps(Image *,const ImageInfo*,const size_t,const size_t,const size_t, const MagickBooleanType,const MagickBooleanType,const MagickBooleanType, ExceptionInfo *); static void RemapIndices(const ssize_t *,const unsigned char *,unsigned char *), WriteDDSInfo(Image *,const size_t,const size_t,const size_t), WriteFourCC(Image *,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteIndices(Image *,const DDSVector3,const DDSVector3,unsigned char *), WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *), WriteUncompressed(Image *,ExceptionInfo *); static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x + right.x; destination->y = left.y + right.y; destination->z = left.z + right.z; destination->w = left.w + right.w; } static inline void VectorClamp(DDSVector4 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); } static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); } static inline void VectorCopy43(const DDSVector4 source, DDSVector3 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; } static inline void VectorCopy44(const DDSVector4 source, DDSVector4 *destination) { destination->x = source.x; destination->y = source.y; destination->z = source.z; destination->w = source.w; } static inline void VectorNegativeMultiplySubtract(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = c.x - (a.x * b.x); destination->y = c.y - (a.y * b.y); destination->z = c.z - (a.z * b.z); destination->w = c.w - (a.w * b.w); } static inline void VectorMultiply(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; destination->w = left.w * right.w; } static inline void VectorMultiply3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x * right.x; destination->y = left.y * right.y; destination->z = left.z * right.z; } static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; destination->w = (a.w * b.w) + c.w; } static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b, const DDSVector3 c, DDSVector3 *destination) { destination->x = (a.x * b.x) + c.x; destination->y = (a.y * b.y) + c.y; destination->z = (a.z * b.z) + c.z; } static inline void VectorReciprocal(const DDSVector4 value, DDSVector4 *destination) { destination->x = 1.0f / value.x; destination->y = 1.0f / value.y; destination->z = 1.0f / value.z; destination->w = 1.0f / value.w; } static inline void VectorSubtract(const DDSVector4 left, const DDSVector4 right, DDSVector4 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; destination->w = left.w - right.w; } static inline void VectorSubtract3(const DDSVector3 left, const DDSVector3 right, DDSVector3 *destination) { destination->x = left.x - right.x; destination->y = left.y - right.y; destination->z = left.z - right.z; } static inline void VectorTruncate(DDSVector4 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w); } static inline void VectorTruncate3(DDSVector3 *value) { value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x); value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y); value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z); } static void CalculateColors(unsigned short c0, unsigned short c1, DDSColors *c, MagickBooleanType ignoreAlpha) { c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0; c->r[0] = (unsigned char) C565_red(c0); c->g[0] = (unsigned char) C565_green(c0); c->b[0] = (unsigned char) C565_blue(c0); c->r[1] = (unsigned char) C565_red(c1); c->g[1] = (unsigned char) C565_green(c1); c->b[1] = (unsigned char) C565_blue(c1); if (ignoreAlpha != MagickFalse || c0 > c1) { c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3); c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3); c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3); c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3); c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3); c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3); } else { c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2); c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2); c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2); c->r[3] = c->g[3] = c->b[3] = 0; c->a[3] = 255; } } static size_t CompressAlpha(const size_t min, const size_t max, const size_t steps, const ssize_t *alphas, unsigned char* indices) { unsigned char codes[8]; register ssize_t i; size_t error, index, j, least, value; codes[0] = (unsigned char) min; codes[1] = (unsigned char) max; codes[6] = 0; codes[7] = 255; for (i=1; i < (ssize_t) steps; i++) codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps); error = 0; for (i=0; i<16; i++) { if (alphas[i] == -1) { indices[i] = 0; continue; } value = alphas[i]; least = SIZE_MAX; index = 0; for (j=0; j<8; j++) { size_t dist; dist = value - (size_t)codes[j]; dist *= dist; if (dist < least) { least = dist; index = j; } } indices[i] = (unsigned char)index; error += least; } return error; } static void CompressClusterFit(const size_t count, const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3* end, unsigned char *indices) { DDSVector3 axis; DDSVector4 grid, gridrcp, half, onethird_onethird2, pointsWeights[16], two, twonineths, twothirds_twothirds2, xSumwSum; float bestError = 1e+37f; size_t bestIteration = 0, besti = 0, bestj = 0, bestk = 0, iterationIndex; ssize_t i; unsigned char *o, order[128], unordered[16]; VectorInit(half,0.5f); VectorInit(two,2.0f); VectorInit(onethird_onethird2,1.0f/3.0f); onethird_onethird2.w = 1.0f/9.0f; VectorInit(twothirds_twothirds2,2.0f/3.0f); twothirds_twothirds2.w = 4.0f/9.0f; VectorInit(twonineths,2.0f/9.0f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; grid.w = 0.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; gridrcp.w = 0.0f; xSumwSum.x = 0.0f; xSumwSum.y = 0.0f; xSumwSum.z = 0.0f; xSumwSum.w = 0.0f; ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0); for (iterationIndex = 0;;) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,1) \ num_threads(GetMagickResourceLimit(ThreadResource)) #endif for (i=0; i < (ssize_t) count; i++) { DDSVector4 part0, part1, part2; size_t ii, j, k, kmin; VectorInit(part0,0.0f); for(ii=0; ii < (size_t) i; ii++) VectorAdd(pointsWeights[ii],part0,&part0); VectorInit(part1,0.0f); for (j=(size_t) i;;) { if (j == 0) { VectorCopy44(pointsWeights[0],&part2); kmin = 1; } else { VectorInit(part2,0.0f); kmin = j; } for (k=kmin;;) { DDSVector4 a, alpha2_sum, alphax_sum, alphabeta_sum, b, beta2_sum, betax_sum, e1, e2, factor, part3; float error; VectorSubtract(xSumwSum,part2,&part3); VectorSubtract(part3,part1,&part3); VectorSubtract(part3,part0,&part3); VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum); VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum); VectorInit(alpha2_sum,alphax_sum.w); VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum); VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum); VectorInit(beta2_sum,betax_sum.w); VectorAdd(part1,part2,&alphabeta_sum); VectorInit(alphabeta_sum,alphabeta_sum.w); VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum); VectorMultiply(alpha2_sum,beta2_sum,&factor); VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor, &factor); VectorReciprocal(factor,&factor); VectorMultiply(alphax_sum,beta2_sum,&a); VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a); VectorMultiply(a,factor,&a); VectorMultiply(betax_sum,alpha2_sum,&b); VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b); VectorMultiply(b,factor,&b); VectorClamp(&a); VectorMultiplyAdd(grid,a,half,&a); VectorTruncate(&a); VectorMultiply(a,gridrcp,&a); VectorClamp(&b); VectorMultiplyAdd(grid,b,half,&b); VectorTruncate(&b); VectorMultiply(b,gridrcp,&b); VectorMultiply(b,b,&e1); VectorMultiply(e1,beta2_sum,&e1); VectorMultiply(a,a,&e2); VectorMultiplyAdd(e2,alpha2_sum,e1,&e1); VectorMultiply(a,b,&e2); VectorMultiply(e2,alphabeta_sum,&e2); VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2); VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2); VectorMultiplyAdd(two,e2,e1,&e2); VectorMultiply(e2,metric,&e2); error = e2.x + e2.y + e2.z; if (error < bestError) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (DDS_CompressClusterFit) #endif { if (error < bestError) { VectorCopy43(a,start); VectorCopy43(b,end); bestError = error; besti = i; bestj = j; bestk = k; bestIteration = iterationIndex; } } } if (k == count) break; VectorAdd(pointsWeights[k],part2,&part2); k++; } if (j == count) break; VectorAdd(pointsWeights[j],part1,&part1); j++; } } if (bestIteration != iterationIndex) break; iterationIndex++; if (iterationIndex == 8) break; VectorSubtract3(*end,*start,&axis); if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order, iterationIndex) == MagickFalse) break; } o = order + (16*bestIteration); for (i=0; i < (ssize_t) besti; i++) unordered[o[i]] = 0; for (i=besti; i < (ssize_t) bestj; i++) unordered[o[i]] = 2; for (i=bestj; i < (ssize_t) bestk; i++) unordered[o[i]] = 3; for (i=bestk; i < (ssize_t) count; i++) unordered[o[i]] = 1; RemapIndices(map,unordered,indices); } static void CompressRangeFit(const size_t count, const DDSVector4* points, const ssize_t *map, const DDSVector3 principle, const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end, unsigned char *indices) { float d, bestDist, max, min, val; DDSVector3 codes[4], grid, gridrcp, half, dist; register ssize_t i; size_t bestj, j; unsigned char closest[16]; VectorInit3(half,0.5f); grid.x = 31.0f; grid.y = 63.0f; grid.z = 31.0f; gridrcp.x = 1.0f/31.0f; gridrcp.y = 1.0f/63.0f; gridrcp.z = 1.0f/31.0f; if (count > 0) { VectorCopy43(points[0],start); VectorCopy43(points[0],end); min = max = Dot(points[0],principle); for (i=1; i < (ssize_t) count; i++) { val = Dot(points[i],principle); if (val < min) { VectorCopy43(points[i],start); min = val; } else if (val > max) { VectorCopy43(points[i],end); max = val; } } } VectorClamp3(start); VectorMultiplyAdd3(grid,*start,half,start); VectorTruncate3(start); VectorMultiply3(*start,gridrcp,start); VectorClamp3(end); VectorMultiplyAdd3(grid,*end,half,end); VectorTruncate3(end); VectorMultiply3(*end,gridrcp,end); codes[0] = *start; codes[1] = *end; codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f)); codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f)); codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f)); codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f)); codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f)); codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f)); for (i=0; i < (ssize_t) count; i++) { bestDist = 1e+37f; bestj = 0; for (j=0; j < 4; j++) { dist.x = (points[i].x - codes[j].x) * metric.x; dist.y = (points[i].y - codes[j].y) * metric.y; dist.z = (points[i].z - codes[j].z) * metric.z; d = Dot(dist,dist); if (d < bestDist) { bestDist = d; bestj = j; } } closest[i] = (unsigned char) bestj; } RemapIndices(map, closest, indices); } static void ComputeEndPoints(const DDSSingleColourLookup *lookup[], const unsigned char *color, DDSVector3 *start, DDSVector3 *end, unsigned char *index) { register ssize_t i; size_t c, maxError = SIZE_MAX; for (i=0; i < 2; i++) { const DDSSourceBlock* sources[3]; size_t error = 0; for (c=0; c < 3; c++) { sources[c] = &lookup[c][color[c]].sources[i]; error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error); } if (error > maxError) continue; start->x = (float) sources[0]->start / 31.0f; start->y = (float) sources[1]->start / 63.0f; start->z = (float) sources[2]->start / 31.0f; end->x = (float) sources[0]->end / 31.0f; end->y = (float) sources[1]->end / 63.0f; end->z = (float) sources[2]->end / 31.0f; *index = (unsigned char) (2*i); maxError = error; } } static void ComputePrincipleComponent(const float *covariance, DDSVector3 *principle) { DDSVector4 row0, row1, row2, v; register ssize_t i; row0.x = covariance[0]; row0.y = covariance[1]; row0.z = covariance[2]; row0.w = 0.0f; row1.x = covariance[1]; row1.y = covariance[3]; row1.z = covariance[4]; row1.w = 0.0f; row2.x = covariance[2]; row2.y = covariance[4]; row2.z = covariance[5]; row2.w = 0.0f; VectorInit(v,1.0f); for (i=0; i < 8; i++) { DDSVector4 w; float a; w.x = row0.x * v.x; w.y = row0.y * v.x; w.z = row0.z * v.x; w.w = row0.w * v.x; w.x = (row1.x * v.y) + w.x; w.y = (row1.y * v.y) + w.y; w.z = (row1.z * v.y) + w.z; w.w = (row1.w * v.y) + w.w; w.x = (row2.x * v.z) + w.x; w.y = (row2.y * v.z) + w.y; w.z = (row2.z * v.z) + w.z; w.w = (row2.w * v.z) + w.w; a = (float) PerceptibleReciprocal(MagickMax(w.x,MagickMax(w.y,w.z))); v.x = w.x * a; v.y = w.y * a; v.z = w.z * a; v.w = w.w * a; } VectorCopy43(v,principle); } static void ComputeWeightedCovariance(const size_t count, const DDSVector4 *points, float *covariance) { DDSVector3 centroid; float total; size_t i; total = 0.0f; VectorInit3(centroid,0.0f); for (i=0; i < count; i++) { total += points[i].w; centroid.x += (points[i].x * points[i].w); centroid.y += (points[i].y * points[i].w); centroid.z += (points[i].z * points[i].w); } if( total > 1.192092896e-07F) { centroid.x /= total; centroid.y /= total; centroid.z /= total; } for (i=0; i < 6; i++) covariance[i] = 0.0f; for (i = 0; i < count; i++) { DDSVector3 a, b; a.x = points[i].x - centroid.x; a.y = points[i].y - centroid.y; a.z = points[i].z - centroid.z; b.x = points[i].w * a.x; b.y = points[i].w * a.y; b.z = points[i].w * a.z; covariance[0] += a.x*b.x; covariance[1] += a.x*b.y; covariance[2] += a.x*b.z; covariance[3] += a.y*b.y; covariance[4] += a.y*b.z; covariance[5] += a.z*b.z; } } static MagickBooleanType ConstructOrdering(const size_t count, const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights, DDSVector4 *xSumwSum, unsigned char *order, size_t iteration) { float dps[16], f; register ssize_t i; size_t j; unsigned char c, *o, *p; o = order + (16*iteration); for (i=0; i < (ssize_t) count; i++) { dps[i] = Dot(points[i],axis); o[i] = (unsigned char)i; } for (i=0; i < (ssize_t) count; i++) { for (j=i; j > 0 && dps[j] < dps[j - 1]; j--) { f = dps[j]; dps[j] = dps[j - 1]; dps[j - 1] = f; c = o[j]; o[j] = o[j - 1]; o[j - 1] = c; } } for (i=0; i < (ssize_t) iteration; i++) { MagickBooleanType same; p = order + (16*i); same = MagickTrue; for (j=0; j < count; j++) { if (o[j] != p[j]) { same = MagickFalse; break; } } if (same != MagickFalse) return MagickFalse; } xSumwSum->x = 0; xSumwSum->y = 0; xSumwSum->z = 0; xSumwSum->w = 0; for (i=0; i < (ssize_t) count; i++) { DDSVector4 v; j = (size_t) o[i]; v.x = points[j].w * points[j].x; v.y = points[j].w * points[j].y; v.z = points[j].w * points[j].z; v.w = points[j].w * 1.0f; VectorCopy44(v,&pointsWeights[i]); VectorAdd(*xSumwSum,v,xSumwSum); } return MagickTrue; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s D D S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsDDS() returns MagickTrue if the image format type, identified by the % magick string, is DDS. % % The format of the IsDDS method is: % % MagickBooleanType IsDDS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"DDS ", 4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadDDSImage() reads a DirectDraw Surface image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadDDSImage method is: % % Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: The image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) { const char *option; CompressionType compression; DDSInfo dds_info; DDSDecoder *decoder; Image *image; MagickBooleanType status, cubemap, volume, read_mipmaps; PixelTrait alpha_trait; size_t n, num_images; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cubemap=MagickFalse, volume=MagickFalse, read_mipmaps=MagickFalse; image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ if (ReadDDSInfo(image, &dds_info) != MagickTrue) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) cubemap = MagickTrue; if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) volume = MagickTrue; (void) SeekBlob(image, 128, SEEK_SET); /* Determine pixel format */ if (dds_info.pixelformat.flags & DDPF_RGB) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { alpha_trait = BlendPixelTrait; decoder = ReadUncompressedRGBA; } else { alpha_trait = UndefinedPixelTrait; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) { compression = NoCompression; if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) { /* Not sure how to handle this */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } else { alpha_trait = UndefinedPixelTrait; decoder = ReadUncompressedRGB; } } else if (dds_info.pixelformat.flags & DDPF_FOURCC) { switch (dds_info.pixelformat.fourcc) { case FOURCC_DXT1: { alpha_trait = UndefinedPixelTrait; compression = DXT1Compression; decoder = ReadDXT1; break; } case FOURCC_DXT3: { alpha_trait = BlendPixelTrait; compression = DXT3Compression; decoder = ReadDXT3; break; } case FOURCC_DXT5: { alpha_trait = BlendPixelTrait; compression = DXT5Compression; decoder = ReadDXT5; break; } default: { /* Unknown FOURCC */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } } } else { /* Neither compressed nor uncompressed... thus unsupported */ ThrowReaderException(CorruptImageError, "ImageTypeNotSupported"); } num_images = 1; if (cubemap) { /* Determine number of faces defined in the cubemap */ num_images = 0; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; } if (volume) num_images = dds_info.depth; if ((num_images == 0) || (num_images > GetBlobSize(image))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireMagickResource(ListLengthResource,num_images) == MagickFalse) ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit"); option=GetImageOption(image_info,"dds:skip-mipmaps"); if (IsStringFalse(option) != MagickFalse) read_mipmaps=MagickTrue; for (n = 0; n < num_images; n++) { if (n != 0) { /* Start a new image */ if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } image->alpha_trait=alpha_trait; image->compression=compression; image->columns=dds_info.width; image->rows=dds_info.height; image->storage_class=DirectClass; image->endian=LSBEndian; image->depth=8; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) SetImageBackgroundColor(image,exception); status=(decoder)(image_info,image,&dds_info,read_mipmaps,exception); if (status == MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info) { size_t hdr_size, required; /* Seek to start of header */ (void) SeekBlob(image, 4, SEEK_SET); /* Check header field */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 124) return MagickFalse; /* Fill in DDS info struct */ dds_info->flags = ReadBlobLSBLong(image); /* Check required flags */ required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); if ((dds_info->flags & required) != required) return MagickFalse; dds_info->height = ReadBlobLSBLong(image); dds_info->width = ReadBlobLSBLong(image); dds_info->pitchOrLinearSize = ReadBlobLSBLong(image); dds_info->depth = ReadBlobLSBLong(image); dds_info->mipmapcount = ReadBlobLSBLong(image); (void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */ /* Read pixel format structure */ hdr_size = ReadBlobLSBLong(image); if (hdr_size != 32) return MagickFalse; dds_info->pixelformat.flags = ReadBlobLSBLong(image); dds_info->pixelformat.fourcc = ReadBlobLSBLong(image); dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image); dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image); dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image); dds_info->ddscaps1 = ReadBlobLSBLong(image); dds_info->ddscaps2 = ReadBlobLSBLong(image); (void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */ return MagickTrue; } static MagickBooleanType SetDXT1Pixels(Image *image,ssize_t x,ssize_t y, DDSColors colors,size_t bits,Quantum *q) { register ssize_t i; ssize_t j; unsigned char code; for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) image->columns && (y + j) < (ssize_t) image->rows) { code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3); SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q); SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q); SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q); SetPixelOpacity(image,ScaleCharToQuantum(colors.a[code]),q); if ((colors.a[code] != 0) && (image->alpha_trait == UndefinedPixelTrait)) return(MagickFalse); q+=GetPixelChannels(image); } } } return(MagickTrue); } static MagickBooleanType ReadMipmaps(const ImageInfo *image_info,Image *image, DDSInfo *dds_info,DDSPixelDecoder decoder,ExceptionInfo *exception) { MagickBooleanType status; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } status=MagickTrue; if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { register ssize_t i; size_t h, w; w=DIV2(dds_info->width); h=DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(MagickFalse); image=SyncNextImageInList(image); status=SetImageExtent(image,w,h,exception); if (status == MagickFalse) break; status=decoder(image,dds_info,exception); if (status == MagickFalse) break; if ((w == 1) && (h == 1)) break; w=DIV2(w); h=DIV2(h); } } return(status); } static MagickBooleanType ReadDXT1Pixels(Image *image, DDSInfo *magick_unused(dds_info),ExceptionInfo *exception) { DDSColors colors; register Quantum *q; register ssize_t x; size_t bits; ssize_t y; unsigned short c0, c1; magick_unreferenced(dds_info); for (y = 0; y < (ssize_t) image->rows; y += 4) { for (x = 0; x < (ssize_t) image->columns; x += 4) { /* Get 4x4 patch of pixels to write on */ q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x), MagickMin(4,image->rows-y),exception); if (q == (Quantum *) NULL) return(MagickFalse); /* Read 8 bytes of data from the image */ c0=ReadBlobLSBShort(image); c1=ReadBlobLSBShort(image); bits=ReadBlobLSBLong(image); CalculateColors(c0,c1,&colors,MagickFalse); if (EOFBlob(image) != MagickFalse) return(MagickFalse); /* Write the pixels */ if (SetDXT1Pixels(image,x,y,colors,bits,q) == MagickFalse) { /* Correct alpha */ SetImageAlpha(image,QuantumRange,exception); q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x), MagickMin(4,image->rows-y),exception); if (q != (Quantum *) NULL) SetDXT1Pixels(image,x,y,colors,bits,q); } if (SyncAuthenticPixels(image,exception) == MagickFalse) return(MagickFalse); } if (EOFBlob(image) != MagickFalse) return(MagickFalse); } return(MagickTrue); } static MagickBooleanType ReadDXT1(const ImageInfo *image_info,Image *image, DDSInfo *dds_info,const MagickBooleanType read_mipmaps, ExceptionInfo *exception) { if (ReadDXT1Pixels(image,dds_info,exception) == MagickFalse) return(MagickFalse); if (read_mipmaps != MagickFalse) return(ReadMipmaps(image_info,image,dds_info,ReadDXT1Pixels,exception)); else return(SkipDXTMipmaps(image,dds_info,8,exception)); } static MagickBooleanType ReadDXT3Pixels(Image *image, DDSInfo *magick_unused(dds_info),ExceptionInfo *exception) { DDSColors colors; register Quantum *q; register ssize_t i, x; unsigned char alpha; size_t a0, a1, bits, code; ssize_t j, y; unsigned short c0, c1; magick_unreferenced(dds_info); for (y = 0; y < (ssize_t) image->rows; y += 4) { for (x = 0; x < (ssize_t) image->columns; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, image->columns - x), MagickMin(4, image->rows - y),exception); if (q == (Quantum *) NULL) return(MagickFalse); /* Read alpha values (8 bytes) */ a0 = ReadBlobLSBLong(image); a1 = ReadBlobLSBLong(image); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); if (EOFBlob(image) != MagickFalse) return(MagickFalse); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) image->columns && (y + j) < (ssize_t) image->rows) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q); SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q); SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q); /* Extract alpha value: multiply 0..15 by 17 to get range 0..255 */ if (j < 2) alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf); else alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) alpha),q); q+=GetPixelChannels(image); } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return(MagickFalse); } if (EOFBlob(image) != MagickFalse) return(MagickFalse); } return(MagickTrue); } static MagickBooleanType ReadDXT3(const ImageInfo *image_info,Image *image, DDSInfo *dds_info,const MagickBooleanType read_mipmaps, ExceptionInfo *exception) { if (ReadDXT3Pixels(image,dds_info,exception) == MagickFalse) return(MagickFalse); if (read_mipmaps != MagickFalse) return(ReadMipmaps(image_info,image,dds_info,ReadDXT3Pixels,exception)); else return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadDXT5Pixels(Image *image, DDSInfo *magick_unused(dds_info),ExceptionInfo *exception) { DDSColors colors; MagickSizeType alpha_bits; register Quantum *q; register ssize_t i, x; unsigned char a0, a1; size_t alpha, bits, code, alpha_code; ssize_t j, y; unsigned short c0, c1; magick_unreferenced(dds_info); for (y = 0; y < (ssize_t) image->rows; y += 4) { for (x = 0; x < (ssize_t) image->columns; x += 4) { /* Get 4x4 patch of pixels to write on */ q = QueueAuthenticPixels(image, x, y, MagickMin(4, image->columns - x), MagickMin(4, image->rows - y),exception); if (q == (Quantum *) NULL) return(MagickFalse); /* Read alpha values (8 bytes) */ a0 = (unsigned char) ReadBlobByte(image); a1 = (unsigned char) ReadBlobByte(image); alpha_bits = (MagickSizeType)ReadBlobLSBLong(image); alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32); /* Read 8 bytes of data from the image */ c0 = ReadBlobLSBShort(image); c1 = ReadBlobLSBShort(image); bits = ReadBlobLSBLong(image); CalculateColors(c0, c1, &colors, MagickTrue); if (EOFBlob(image) != MagickFalse) return(MagickFalse); /* Write the pixels */ for (j = 0; j < 4; j++) { for (i = 0; i < 4; i++) { if ((x + i) < (ssize_t) image->columns && (y + j) < (ssize_t) image->rows) { code = (bits >> ((4*j+i)*2)) & 0x3; SetPixelRed(image,ScaleCharToQuantum(colors.r[code]),q); SetPixelGreen(image,ScaleCharToQuantum(colors.g[code]),q); SetPixelBlue(image,ScaleCharToQuantum(colors.b[code]),q); /* Extract alpha value */ alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7; if (alpha_code == 0) alpha = a0; else if (alpha_code == 1) alpha = a1; else if (a0 > a1) alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7; else if (alpha_code == 6) alpha = 0; else if (alpha_code == 7) alpha = 255; else alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) alpha),q); q+=GetPixelChannels(image); } } } if (SyncAuthenticPixels(image,exception) == MagickFalse) return(MagickFalse); } if (EOFBlob(image) != MagickFalse) return(MagickFalse); } return(MagickTrue); } static MagickBooleanType ReadDXT5(const ImageInfo *image_info,Image *image, DDSInfo *dds_info,const MagickBooleanType read_mipmaps, ExceptionInfo *exception) { if (ReadDXT5Pixels(image,dds_info,exception) == MagickFalse) return(MagickFalse); if (read_mipmaps != MagickFalse) return(ReadMipmaps(image_info,image,dds_info,ReadDXT5Pixels,exception)); else return(SkipDXTMipmaps(image,dds_info,16,exception)); } static MagickBooleanType ReadUncompressedRGBPixels(Image *image, DDSInfo *dds_info,ExceptionInfo *exception) { register Quantum *q; ssize_t x, y; unsigned short color; for (y = 0; y < (ssize_t) image->rows; y++) { q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (Quantum *) NULL) return(MagickFalse); for (x = 0; x < (ssize_t) image->columns; x++) { if (dds_info->pixelformat.rgb_bitcount == 8) SetPixelGray(image,ScaleCharToQuantum(ReadBlobByte(image)),q); else if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); SetPixelRed(image,ScaleCharToQuantum((unsigned char) (((color >> 11)/31.0)*255)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 5) >> 10)/63.0)*255)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255)),q); } else { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); if (dds_info->pixelformat.rgb_bitcount == 32) (void) ReadBlobByte(image); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) return(MagickFalse); if (EOFBlob(image) != MagickFalse) return(MagickFalse); } return(MagickTrue); } static MagickBooleanType ReadUncompressedRGB(const ImageInfo *image_info, Image *image,DDSInfo *dds_info,const MagickBooleanType read_mipmaps, ExceptionInfo *exception) { if (dds_info->pixelformat.rgb_bitcount == 8) (void) SetImageType(image,GrayscaleType,exception); else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask( dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000)) ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); if (ReadUncompressedRGBPixels(image,dds_info,exception) == MagickFalse) return(MagickFalse); if (read_mipmaps != MagickFalse) return(ReadMipmaps(image_info,image,dds_info,ReadUncompressedRGBPixels, exception)); else return(SkipRGBMipmaps(image,dds_info,3,exception)); } static MagickBooleanType ReadUncompressedRGBAPixels(Image *image, DDSInfo *dds_info,ExceptionInfo *exception) { register Quantum *q; ssize_t alphaBits, x, y; unsigned short color; alphaBits=0; if (dds_info->pixelformat.rgb_bitcount == 16) { if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000)) alphaBits=1; else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00)) { alphaBits=2; (void) SetImageType(image,GrayscaleAlphaType,exception); } else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000)) alphaBits=4; else ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported", image->filename); } for (y = 0; y < (ssize_t) image->rows; y++) { q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception); if (q == (Quantum *) NULL) return(MagickFalse); for (x = 0; x < (ssize_t) image->columns; x++) { if (dds_info->pixelformat.rgb_bitcount == 16) { color=ReadBlobShort(image); if (alphaBits == 1) { SetPixelAlpha(image,(color & (1 << 15)) ? QuantumRange : 0,q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 1) >> 11)/31.0)*255)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 6) >> 11)/31.0)*255)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 11) >> 11)/31.0)*255)),q); } else if (alphaBits == 2) { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (color >> 8)),q); SetPixelGray(image,ScaleCharToQuantum((unsigned char)color),q); } else { SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) (((color >> 12)/15.0)*255)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 4) >> 12)/15.0)*255)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 8) >> 12)/15.0)*255)),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ((((unsigned short)(color << 12) >> 12)/15.0)*255)),q); } } else { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) return(MagickFalse); if (EOFBlob(image) != MagickFalse) return(MagickFalse); } return(MagickTrue); } static MagickBooleanType ReadUncompressedRGBA(const ImageInfo *image_info, Image *image,DDSInfo *dds_info,const MagickBooleanType read_mipmaps, ExceptionInfo *exception) { if (ReadUncompressedRGBAPixels(image,dds_info,exception) == MagickFalse) return(MagickFalse); if (read_mipmaps != MagickFalse) return(ReadMipmaps(image_info,image,dds_info,ReadUncompressedRGBAPixels, exception)); else return(SkipRGBMipmaps(image,dds_info,4,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterDDSImage() adds attributes for the DDS image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterDDSImage method is: % % RegisterDDSImage(void) % */ ModuleExport size_t RegisterDDSImage(void) { MagickInfo *entry; entry = AcquireMagickInfo("DDS","DDS","Microsoft DirectDraw Surface"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry = AcquireMagickInfo("DDS","DXT1","Microsoft DirectDraw Surface"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry = AcquireMagickInfo("DDS","DXT5","Microsoft DirectDraw Surface"); entry->decoder = (DecodeImageHandler *) ReadDDSImage; entry->encoder = (EncodeImageHandler *) WriteDDSImage; entry->magick = (IsImageFormatHandler *) IsDDS; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } static void RemapIndices(const ssize_t *map, const unsigned char *source, unsigned char *target) { register ssize_t i; for (i = 0; i < 16; i++) { if (map[i] == -1) target[i] = 3; else target[i] = source[map[i]]; } } /* Skip the mipmap images for compressed (DXTn) dds files */ static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { MagickOffsetType offset; register ssize_t i; size_t h, w; w=DIV2(dds_info->width); h=DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset=(MagickOffsetType)((w+3)/4)*((h+3)/4)*texel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; w=DIV2(w); h=DIV2(h); if ((w == 1) && (h == 1)) break; } } return(MagickTrue); } /* Skip the mipmap images for uncompressed (RGB or RGBA) dds files */ static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { MagickOffsetType offset; register ssize_t i; size_t h, w; w=DIV2(dds_info->width); h=DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset=(MagickOffsetType)w*h*pixel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; w=DIV2(w); h=DIV2(h); if ((w == 1) && (h == 1)) break; } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterDDSImage() removes format registrations made by the % DDS module from the list of supported formats. % % The format of the UnregisterDDSImage method is: % % UnregisterDDSImage(void) % */ ModuleExport void UnregisterDDSImage(void) { (void) UnregisterMagickInfo("DDS"); (void) UnregisterMagickInfo("DXT1"); (void) UnregisterMagickInfo("DXT5"); } static void WriteAlphas(Image *image, const ssize_t *alphas, size_t min5, size_t max5, size_t min7, size_t max7) { register ssize_t i; size_t err5, err7, j; unsigned char indices5[16], indices7[16]; FixRange(min5,max5,5); err5 = CompressAlpha(min5,max5,5,alphas,indices5); FixRange(min7,max7,7); err7 = CompressAlpha(min7,max7,7,alphas,indices7); if (err7 < err5) { for (i=0; i < 16; i++) { unsigned char index; index = indices7[i]; if( index == 0 ) indices5[i] = 1; else if (index == 1) indices5[i] = 0; else indices5[i] = 9 - index; } min5 = max7; max5 = min7; } (void) WriteBlobByte(image,(unsigned char) min5); (void) WriteBlobByte(image,(unsigned char) max5); for(i=0; i < 2; i++) { size_t value = 0; for (j=0; j < 8; j++) { size_t index = (size_t) indices5[j + i*8]; value |= ( index << 3*j ); } for (j=0; j < 3; j++) { size_t byte = (value >> 8*j) & 0xff; (void) WriteBlobByte(image,(unsigned char) byte); } } } static void WriteCompressed(Image *image, const size_t count, DDSVector4 *points, const ssize_t *map, const MagickBooleanType clusterFit) { float covariance[16]; DDSVector3 end, principle, start; DDSVector4 metric; unsigned char indices[16]; VectorInit(metric,1.0f); VectorInit3(start,0.0f); VectorInit3(end,0.0f); ComputeWeightedCovariance(count,points,covariance); ComputePrincipleComponent(covariance,&principle); if ((clusterFit == MagickFalse) || (count == 0)) CompressRangeFit(count,points,map,principle,metric,&start,&end,indices); else CompressClusterFit(count,points,map,principle,metric,&start,&end,indices); WriteIndices(image,start,end,indices); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e D D S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format. % % The format of the WriteBMPImage method is: % % MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteDDSImage(const ImageInfo *image_info, Image *image, ExceptionInfo *exception) { const char *option; size_t compression, columns, maxMipmaps, mipmaps, pixelFormat, rows; MagickBooleanType clusterFit, fromlist, status, weightByAlpha; assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace,exception); pixelFormat=DDPF_FOURCC; compression=FOURCC_DXT5; if (image->alpha_trait == UndefinedPixelTrait) compression=FOURCC_DXT1; if (LocaleCompare(image_info->magick,"dxt1") == 0) compression=FOURCC_DXT1; option=GetImageOption(image_info,"dds:compression"); if (option != (char *) NULL) { if (LocaleCompare(option,"dxt1") == 0) compression=FOURCC_DXT1; if (LocaleCompare(option,"none") == 0) pixelFormat=DDPF_RGB; } clusterFit=MagickFalse; weightByAlpha=MagickFalse; if (pixelFormat == DDPF_FOURCC) { option=GetImageOption(image_info,"dds:cluster-fit"); if (IsStringTrue(option) != MagickFalse) { clusterFit=MagickTrue; if (compression != FOURCC_DXT1) { option=GetImageOption(image_info,"dds:weight-by-alpha"); if (IsStringTrue(option) != MagickFalse) weightByAlpha=MagickTrue; } } } mipmaps=0; fromlist=MagickFalse; option=GetImageOption(image_info,"dds:mipmaps"); if (option != (char *) NULL) { if (LocaleNCompare(option,"fromlist",8) == 0) { Image *next; fromlist=MagickTrue; next=image->next; while(next != (Image *) NULL) { mipmaps++; next=next->next; } } } if ((mipmaps == 0) && ((image->columns & (image->columns - 1)) == 0) && ((image->rows & (image->rows - 1)) == 0)) { maxMipmaps=SIZE_MAX; if (option != (char *) NULL) maxMipmaps=StringToUnsignedLong(option); if (maxMipmaps != 0) { columns=image->columns; rows=image->rows; while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps) { columns=DIV2(columns); rows=DIV2(rows); mipmaps++; } } } WriteDDSInfo(image,pixelFormat,compression,mipmaps); WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha, exception); if ((mipmaps > 0) && (WriteMipmaps(image,image_info,pixelFormat,compression, mipmaps,fromlist,clusterFit,weightByAlpha,exception) == MagickFalse)) return(MagickFalse); (void) CloseBlob(image); return(MagickTrue); } static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MagickPathExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (format == DDPF_FOURCC) flags=flags | DDSD_LINEARSIZE; else flags=flags | DDSD_PITCH; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->alpha_trait != UndefinedPixelTrait) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (pixelFormat == DDPF_FOURCC) { /* Compressed DDS requires linear compressed size of first image */ if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8)); else /* DXT5 */ (void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1, (image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16)); } else { /* Uncompressed DDS requires byte pitch of first image */ if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4)); else (void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3)); } (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) memset(software,0,sizeof(software)); (void) CopyMagickString(software,"IMAGEMAGICK",MagickPathExtent); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) /* bitcount / masks */ (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->alpha_trait != UndefinedPixelTrait) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) /* ddscaps2 + reserved region */ (void) WriteBlobLSBLong(image,0x00); } static void WriteFourCC(Image *image, const size_t compression, const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { register ssize_t x; ssize_t i, y, bx, by; register const Quantum *p; for (y=0; y < (ssize_t) image->rows; y+=4) { for (x=0; x < (ssize_t) image->columns; x+=4) { MagickBooleanType match; DDSVector4 point, points[16]; size_t count = 0, max5 = 0, max7 = 0, min5 = 255, min7 = 255, columns = 4, rows = 4; ssize_t alphas[16], map[16]; unsigned char alpha; if (x + columns >= image->columns) columns = image->columns - x; if (y + rows >= image->rows) rows = image->rows - y; p=GetVirtualPixels(image,x,y,columns,rows,exception); if (p == (const Quantum *) NULL) break; for (i=0; i<16; i++) { map[i] = -1; alphas[i] = -1; } for (by=0; by < (ssize_t) rows; by++) { for (bx=0; bx < (ssize_t) columns; bx++) { if (compression == FOURCC_DXT5) alpha = ScaleQuantumToChar(GetPixelAlpha(image,p)); else alpha = 255; if (compression == FOURCC_DXT5) { if (alpha < min7) min7 = alpha; if (alpha > max7) max7 = alpha; if (alpha != 0 && alpha < min5) min5 = alpha; if (alpha != 255 && alpha > max5) max5 = alpha; } alphas[4*by + bx] = (size_t)alpha; point.x = (float)ScaleQuantumToChar(GetPixelRed(image,p)) / 255.0f; point.y = (float)ScaleQuantumToChar(GetPixelGreen(image,p)) / 255.0f; point.z = (float)ScaleQuantumToChar(GetPixelBlue(image,p)) / 255.0f; point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f; p+=GetPixelChannels(image); match = MagickFalse; for (i=0; i < (ssize_t) count; i++) { if ((points[i].x == point.x) && (points[i].y == point.y) && (points[i].z == point.z) && (alpha >= 128 || compression == FOURCC_DXT5)) { points[i].w += point.w; map[4*by + bx] = i; match = MagickTrue; break; } } if (match != MagickFalse) continue; points[count].x = point.x; points[count].y = point.y; points[count].z = point.z; points[count].w = point.w; map[4*by + bx] = count; count++; } } for (i=0; i < (ssize_t) count; i++) points[i].w = sqrt(points[i].w); if (compression == FOURCC_DXT5) WriteAlphas(image,alphas,min5,max5,min7,max7); if (count == 1) WriteSingleColorFit(image,points,map); else WriteCompressed(image,count,points,map,clusterFit); } } } static void WriteImageData(Image *image, const size_t pixelFormat, const size_t compression,const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha, ExceptionInfo *exception) { if (pixelFormat == DDPF_FOURCC) WriteFourCC(image,compression,clusterFit,weightByAlpha,exception); else WriteUncompressed(image,exception); } static inline size_t ClampToLimit(const float value, const size_t limit) { size_t result = (int) (value + 0.5f); if (result < 0.0f) return(0); if (result > limit) return(limit); return result; } static inline size_t ColorTo565(const DDSVector3 point) { size_t r = ClampToLimit(31.0f*point.x,31); size_t g = ClampToLimit(63.0f*point.y,63); size_t b = ClampToLimit(31.0f*point.z,31); return (r << 11) | (g << 5) | b; } static void WriteIndices(Image *image, const DDSVector3 start, const DDSVector3 end, unsigned char *indices) { register ssize_t i; size_t a, b; unsigned char remapped[16]; const unsigned char *ind; a = ColorTo565(start); b = ColorTo565(end); for (i=0; i<16; i++) { if( a < b ) remapped[i] = (indices[i] ^ 0x1) & 0x3; else if( a == b ) remapped[i] = 0; else remapped[i] = indices[i]; } if( a < b ) Swap(a,b); (void) WriteBlobByte(image,(unsigned char) (a & 0xff)); (void) WriteBlobByte(image,(unsigned char) (a >> 8)); (void) WriteBlobByte(image,(unsigned char) (b & 0xff)); (void) WriteBlobByte(image,(unsigned char) (b >> 8)); for (i=0; i<4; i++) { ind = remapped + 4*i; (void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) | (ind[3] << 6)); } } static MagickBooleanType WriteMipmaps(Image *image,const ImageInfo *image_info, const size_t pixelFormat,const size_t compression,const size_t mipmaps, const MagickBooleanType fromlist,const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,ExceptionInfo *exception) { const char *option; Image *mipmap_image, *resize_image; MagickBooleanType fast_mipmaps, status; register ssize_t i; size_t columns, rows; columns=DIV2(image->columns); rows=DIV2(image->rows); option=GetImageOption(image_info,"dds:fast-mipmaps"); fast_mipmaps=IsStringTrue(option); mipmap_image=image; resize_image=image; status=MagickTrue; for (i=0; i < (ssize_t) mipmaps; i++) { if (fromlist == MagickFalse) { mipmap_image=ResizeImage(resize_image,columns,rows,TriangleFilter, exception); if (mipmap_image == (Image *) NULL) { status=MagickFalse; break; } } else { mipmap_image=mipmap_image->next; if ((mipmap_image->columns != columns) || (mipmap_image->rows != rows)) ThrowBinaryException(CoderError,"ImageColumnOrRowSizeIsNotSupported", image->filename); } DestroyBlob(mipmap_image); mipmap_image->blob=ReferenceBlob(image->blob); WriteImageData(mipmap_image,pixelFormat,compression,weightByAlpha, clusterFit,exception); if (fromlist == MagickFalse) { if (fast_mipmaps == MagickFalse) mipmap_image=DestroyImage(mipmap_image); else { if (resize_image != image) resize_image=DestroyImage(resize_image); resize_image=mipmap_image; } } columns=DIV2(columns); rows=DIV2(rows); } if (resize_image != image) resize_image=DestroyImage(resize_image); return(status); } static void WriteSingleColorFit(Image *image, const DDSVector4 *points, const ssize_t *map) { DDSVector3 start, end; register ssize_t i; unsigned char color[3], index, indexes[16], indices[16]; color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255); color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255); color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255); index=0; ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index); for (i=0; i< 16; i++) indexes[i]=index; RemapIndices(map,indexes,indices); WriteIndices(image,start,end,indices); } static void WriteUncompressed(Image *image, ExceptionInfo *exception) { register const Quantum *p; register ssize_t x; ssize_t y; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(image,p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(image,p))); (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(image,p))); if (image->alpha_trait != UndefinedPixelTrait) (void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } }
matrix_multiplication.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<omp.h> void* init_matriz (int rows, int cols) { return malloc (sizeof (float[rows][cols])); } void* read_matriz (FILE *fr, int *n_row, int *n_col) { fscanf(fr, "%d", n_row); fscanf(fr, "%d", n_col); int rows = *n_row; int cols = *n_col; float (*matriz)[cols] = init_matriz(rows, cols); float cv = 0; int i, j = 0; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { fscanf(fr, "%f,", &cv); matriz[i][j] = cv; } } return matriz; } void* multiply_matrices(int ra, int ca, int rb, int cb, float A[][ca], float B[][cb]) { float (*result)[cb] = init_matriz(ra, cb); int i, j, k, tid; memset(result, 0, sizeof result); for (i = 0; i < ra; i++) for (j = 0; j < cb; j++) result[i][j] = 0; int chunk = 10, nthreads; #pragma omp parallel shared(A, B, result, chunk) private(i, j, k, tid) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); //printf("Number of threads = %d\n", nthreads); } //printf("Thread %d starting...\n", tid); #pragma omp for schedule(static, chunk) collapse(3) for (i = 0; i < ra; i++) { for (k = 0; k < cb; k++) { for (j = 0; j < ca; j++) { //printf("Thread %d is doing %dth row and the %dth col\n", tid, i, j); result[i][k] += A[i][j] * B[j][k]; } } } } return result; } void write_result(int rows, int cols, float matriz[][cols]) { FILE *fw = fopen("resulting_matrix.out", "w"); int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { fprintf(fw, "%f", matriz[i][j]); if (j + 1 < cols) fprintf(fw, ", "); } fprintf(fw, "\n"); } fclose(fw); } void print_matriz(int rows, int cols, float matriz[][cols]) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) printf("%f ", matriz[i][j]); printf("\n"); } } int main () { int rows_a, rows_b, cols_a, cols_b, i, j; FILE *fr; // reading the first file fr = fopen("ma.in", "r"); float (*matriz_A)[] = read_matriz(fr, &rows_a, &cols_a); print_matriz(rows_a, cols_a, matriz_A); fclose(fr); // reading the second file fr = fopen("mb.in", "rb"); float (*matriz_B)[] = read_matriz(fr, &rows_b, &cols_b); print_matriz(rows_b, cols_b, matriz_B); fclose(fr); //multiplying the matrices float (*result)[] = multiply_matrices(rows_a, cols_a, rows_b, cols_b, matriz_A, matriz_B); print_matriz(rows_a, cols_b, result); write_result(rows_a, cols_b, result); free(result); free(matriz_A); free(matriz_B); return 0; }
vecadd_opt3.c
#include <stdio.h> #include <time.h> #include "timer.h" #include "omp.h" #include "place_report_omp.h" // large enough to force into main memory #define ARRAY_SIZE 80000000 static double a[ARRAY_SIZE], b[ARRAY_SIZE], c[ARRAY_SIZE]; void vector_add(double *c, double *a, double *b, int n); int main(int argc, char *argv[]){ #ifdef VERBOSE place_report_omp(); #endif struct timespec tstart; double time_sum = 0.0; #pragma omp parallel { #pragma omp for for (int i=0; i<ARRAY_SIZE; i++) { a[i] = 1.0; b[i] = 2.0; } #pragma omp master cpu_timer_start(&tstart); vector_add(c, a, b, ARRAY_SIZE); #pragma omp master time_sum += cpu_timer_stop(tstart); } // end of omp parallel printf(" %lf \n", time_sum); } void vector_add(double *c, double *a, double *b, int n) { #pragma omp for for (int i=0; i < n; i++){ c[i] = a[i] + b[i]; } }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 24; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
stagger.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "grb2.h" #include "wgrib2.h" #include "fnlist.h" /* * stagger.c Public domain 1/2014 Wesley Ebisuzaki * * * usually x[0] = y[0] = 0.0 * * usually x[] and y[] are integers (except when grids are shiffed +/- 1/2) * * normally: * x = x[]*dx + x_0, note: for gctpc x_0 is not needed * y = y[]*dy + y_0, note: for gctpc y_0 is not needed * x_0 and y_0 are the x and y of the first grid point (raw order) * * version: proposal 5 */ extern double *lat, *lon; extern enum output_order_type output_order; extern int scan; /* * stagger fills x[] and y[], lo1 and la1 have X==0 and Y==0 * * assumed_npnts is number if grid points that the calling program thinks is right * this is for error checking. use -1 if don't know * * to a grid transform: * setup grid transform (proj4 library for example( * call stagger() to get the x() and y() values of the grid * transform x() and y() to lon() and lat() * * like many programs, stagger requires grid to be on we:sn order */ int stagger(unsigned char **sec, unsigned int assumed_npnts, double *x, double *y) { int nx, ny, res, scan; unsigned int npnts; int nnx, nx_even, nx_odd, nx2; double x0, y0, dx_offset, dx_offset_even, dx_offset_odd, dy_offset; unsigned int i, ix, iy, n; int reduced_grid, dx_off_odd, dx_off_even, dy_off; int dx, dy, even; get_nxny(sec, &nx, &ny, &npnts, &res, &scan); if (scan == -1) return 1; if (output_order != wesn) return 1; if (nx < 1 || ny < 1) return 1; /* get stagger bits */ dx_off_odd = ((unsigned int) scan >> 3) & 1; dx_off_even = ((unsigned int) scan >> 2) & 1; dy_off = ((unsigned int) scan >> 1) & 1; reduced_grid = (unsigned int) scan & 1; dx = (scan & 128) ? -1 : 1; dy = (scan & 64) ? 1 : -1; if (reduced_grid && dy_off) ny--; if (dy < 0 && ((ny % 2) == 0)) { // swap even and odd rows if ns to sn and even number of rows i = dx_off_odd; dx_off_odd = dx_off_even; dx_off_even = i; } dx_offset_odd = reduced_grid ? 0.5 * dx_off_odd : 0.5 * dx_off_odd * dx; dx_offset_even = reduced_grid ? 0.5 * dx_off_even : 0.5 * dx_off_even * dx; dy_offset = reduced_grid ? 0.5 * dy_off : 0.5 * dy_off * dy; nx_odd = nx - (dx_off_odd & reduced_grid); nx_even = nx - (dx_off_even & reduced_grid); nx2 = nx_odd + nx_even; //fprintf(stderr, "stagger: dx_off_odd %lf dx_off_even %lf dy_off %lf reduced_grid %d nx=%d %d\n", // dx_offset_odd, dx_offset_even, dy_offset, reduced_grid, nx_odd,nx_even); //fprintf(stderr,"dx_off_odd %d reduced_grid %d, and %d\n", dx_off_odd , reduced_grid, dx_off_odd & reduced_grid); //fprintf(stderr,"dx_off_even %d reduced_grid %d, and %d\n", dx_off_even , reduced_grid, dx_off_even & reduced_grid); // number of grid points n = (ny/2)*nx_even + ((ny+1)/2)*nx_odd; // check to number of points if (assumed_npnts != n) fatal_error_ii("stagger: program error think npnts=%d assumed npnts=%d",n, (int) assumed_npnts); if (n != GB2_Sec3_npts(sec)) fatal_error_ii("stagger: program error think npnts=%d, Sec3 gives %d",n, GB2_Sec3_npts(sec)); if (x == NULL || y == NULL) return 1; /* return X[] and Y[] relative to the first grid point but on a we:sn grid */ x0 = (dx > 0) ? 0.0 : 1.0 - (double) nx; y0 = (dy > 0) ? 0.0 : 1.0 - (double) ny; #pragma omp parallel for private(ix,iy,even,i,dx_offset, nnx) for (iy = 0; iy < ny; iy++) { // even = iy % 2; // first row is odd .. iy % 2 == 0 even = (iy & 1); // first row is odd i = even ? nx2*(iy >> 1) + nx_odd : nx2*(iy >> 1); nnx = even ? nx_even : nx_odd; dx_offset = even ? dx_offset_even : dx_offset_odd; for (ix = 0; ix < nnx; ix++) { x[i + ix] = x0 + dx_offset + ix; y[i + ix] = y0 + dy_offset + iy; } } return 0; }
contact.c
#include <stdio.h> #include <math.h> inline double sqeuclidean3(const double a[], const double b[]) { //Calculate the dot product between length-three vectors b and c return (a[0] - b[0])*(a[0] - b[0]) + (a[1] - b[1])*(a[1] - b[1]) + (a[2] - b[2])*(a[2] - b[2]) ; } void atomic_contact(const double *xyzlist, const int *contacts, int num_contacts, int traj_length, int num_atoms, double *results) { // For each length-2 row of contacts, compute the distance between the atoms with indices // in the first and second entries int i, j; const int* atom_ind; const double *frame, *atom1, *atom2; double *results_ptr; #pragma omp parallel for default(none) shared(results, xyzlist, contacts, num_contacts, num_atoms, traj_length) private(j, atom_ind, frame, atom1, atom2, results_ptr) for (i = 0; i < traj_length; i++) { frame = (const double*) xyzlist + num_atoms * 3 * i; results_ptr = results + num_contacts * i; atom_ind = contacts; for (j = 0; j < num_contacts; j++, results_ptr++, atom_ind = atom_ind + 2) { //indices of the two atoms atom1 = frame + *(atom_ind) * 3; atom2 = frame + *(atom_ind + 1) * 3; *results_ptr = sqrt(sqeuclidean3(atom1, atom2)); } } } void atomic_displacement(const double *xyzlist, const int *contacts, int num_contacts, int traj_length, int num_atoms, double *results_dr, double *results_dx) { // For each length-2 row of contacts, compute the distance between the atoms with indices // in the first and second entries int i, j, k; const int* atom_ind; const double *frame, *atom1, *atom2; double *results_dr_ptr, *results_dx_ptr; #pragma omp parallel for default(none) shared(results_dr, results_dx, xyzlist, contacts, num_contacts, num_atoms, traj_length) private(j, k, atom_ind, frame, atom1, atom2, results_dr_ptr, results_dx_ptr) for (i = 0; i < traj_length; i++) { frame = (const double*) xyzlist + num_atoms * 3 * i; results_dr_ptr = results_dr + num_contacts * i; results_dx_ptr = results_dx + num_contacts * i * 3; atom_ind = contacts; for (j = 0; j < num_contacts; j++, results_dr_ptr++, atom_ind = atom_ind + 2) { //indices of the two atoms atom1 = frame + *(atom_ind) * 3; atom2 = frame + *(atom_ind + 1) * 3; *results_dr_ptr = sqrt(sqeuclidean3(atom1, atom2)); for (k = 0; k < 3 ; k++, results_dx_ptr++) { *results_dx_ptr = atom2[k] - atom1[k]; } } } } void closest_contact(const double *xyzlist, const int *residues, const int num_residues, const int residue_width, const int* atoms_per_residue, const int *contacts, int num_contacts, int traj_length, int num_atoms, double *results) { /* xyzlist - traj_length x num_atoms x 3 residue_atoms - num_residues x residue_width, but only the first num_residue_atoms are used num_residue_atoms - num_residues x 1 -- max column index ofresidue_atoms that we care about (rest is padding) contacts - num_contacts x 2 -- each row is the indices of the RESIDUES who we monitor for contact results traj_length x num_contacts */ int i, j, k, l, max_k, max_l; int *atom0_ind_ptr, *atom1_ind_ptr, *a1_ind_ptr; int *contact_ptr; double min, curr; double *results_ptr; const double *frame, *atom0, *atom1; #pragma omp parallel for default(none) shared(results, xyzlist, contacts, num_contacts, num_atoms, traj_length, residues, atoms_per_residue) private(j, k, l, max_k, max_l, atom0_ind_ptr, atom1_ind_ptr, a1_ind_ptr, contact_ptr, min, curr, results_ptr, frame, atom0, atom1) for (i = 0; i < traj_length; i++) { frame = (const double*) xyzlist + num_atoms * 3 * i; contact_ptr = (int*) contacts; results_ptr = results + num_contacts * i; for (j = 0; j < num_contacts; j++, contact_ptr += 2, results_ptr++) { //Calculate the distance between each atom in residue_atoms[contacts[j,0]] //and residue_atoms[contacts[j,1]] atom0_ind_ptr = (int*) residues + *(contact_ptr) * residue_width; atom1_ind_ptr = (int*) residues + *(contact_ptr + 1) * residue_width; max_k = *(atoms_per_residue + *(contact_ptr)); max_l = *(atoms_per_residue + *(contact_ptr + 1)); min = 1000000; for (k = 0; k < max_k; k++, atom0_ind_ptr++) { a1_ind_ptr = atom1_ind_ptr; for (l = 0; l < max_l; l++, a1_ind_ptr++ ) { //printf("Comparing atoms %d and %d\n", *atom0_ind_ptr, *a1_ind_ptr); atom0 = frame + *(atom0_ind_ptr) * 3; atom1 = frame + *(a1_ind_ptr) * 3; //printf("With x coords %f, %f\n", *atom0, *atom1); curr = sqeuclidean3(atom0, atom1); min = curr < min ? curr : min; } } //printf("Min is %f\n", min); *results_ptr = sqrt(min); } //printf("Next frame\n"); } }
vec_avx.h
/* Copyright (c) 2018 Mozilla 2012-2017 Jean-Marc Valin */ /* 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. 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 FOUNDATION 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. */ /* AVX implementation of vector operations, compile with -mavx AVX2/FMA implementation of vector operations, compile with -mavx2 -mfma */ #include <immintrin.h> #include <omp.h> #define OMP #ifdef __AVX2__ static __m256 exp8_approx(__m256 X) { const __m256 K0 = _mm256_set1_ps(0.99992522f); const __m256 K1 = _mm256_set1_ps(0.69583354f); const __m256 K2 = _mm256_set1_ps(0.22606716f); const __m256 K3 = _mm256_set1_ps(0.078024523f); const __m256 log2_E = _mm256_set1_ps(1.44269504); const __m256 max_in = _mm256_set1_ps(50.f); const __m256 min_in = _mm256_set1_ps(-50.f); const __m256i mask = _mm256_set1_epi32(0x7fffffff); __m256 XF, Y; __m256i I; X = _mm256_mul_ps(X, log2_E); X = _mm256_max_ps(min_in, _mm256_min_ps(max_in, X)); XF = _mm256_floor_ps(X); I = _mm256_cvtps_epi32(XF); X = _mm256_sub_ps(X, XF); Y = _mm256_fmadd_ps(_mm256_fmadd_ps(_mm256_fmadd_ps(K3, X, K2), X, K1), X, K0); I = _mm256_slli_epi32(I, 23); Y = _mm256_castsi256_ps(_mm256_and_si256(mask, _mm256_add_epi32(I, _mm256_castps_si256(Y)))); return Y; } #else #define _mm256_fmadd_ps(a,b,c) _mm256_add_ps(_mm256_mul_ps(a, b), c) #define _mm_fmadd_ps(a,b,c) _mm_add_ps(_mm_mul_ps(a, b), c) static __m128 exp4_approx(__m128 X) { const __m128 K0 = _mm_set1_ps(0.99992522f); const __m128 K1 = _mm_set1_ps(0.69583354f); const __m128 K2 = _mm_set1_ps(0.22606716f); const __m128 K3 = _mm_set1_ps(0.078024523f); const __m128 log2_E = _mm_set1_ps(1.44269504); const __m128 max_in = _mm_set1_ps(50.f); const __m128 min_in = _mm_set1_ps(-50.f); const __m128i mask = _mm_set1_epi32(0x7fffffff); __m128 XF, Y; __m128i I; X = _mm_mul_ps(X, log2_E); X = _mm_max_ps(min_in, _mm_min_ps(max_in, X)); XF = _mm_floor_ps(X); I = _mm_cvtps_epi32(XF); X = _mm_sub_ps(X, XF); Y = _mm_fmadd_ps(_mm_fmadd_ps(_mm_fmadd_ps(K3, X, K2), X, K1), X, K0); I = _mm_slli_epi32(I, 23); Y = _mm_castsi128_ps(_mm_and_si128(mask, _mm_add_epi32(I, _mm_castps_si128(Y)))); return Y; } static __m256 exp8_approx(__m256 X) { __m256 Y; __m128 Xhi, Xlo, Yhi, Ylo; Xhi = _mm256_extractf128_ps(X, 1); Xlo = _mm256_extractf128_ps(X, 0); Yhi = exp4_approx(Xhi); Ylo = exp4_approx(Xlo); Y = _mm256_insertf128_ps(_mm256_setzero_ps(), Yhi, 1); Y = _mm256_insertf128_ps(Y, Ylo, 0); return Y; } #endif static float celt_exp(float x) { float out[8]; __m256 X, Y; X = _mm256_set1_ps(x); Y = exp8_approx(X); _mm256_storeu_ps(out, Y); return out[0]; } static void softmax(float *y, const float *x, int N) { int i; for (i=0;i<N-7;i+=8) { __m256 X, Y; X = _mm256_loadu_ps(&x[i]); Y = exp8_approx(X); _mm256_storeu_ps(&y[i], Y); } for (;i<N;i++) y[i] = celt_exp(x[i]); } static void vec_tanh(float *y, const float *x, int N) { int i; for (i=0;i<N-7;i+=8) { const __m256 two = _mm256_set1_ps(2.f); const __m256 one = _mm256_set1_ps(1.f); __m256 X, Y; X = _mm256_loadu_ps(&x[i]); X = _mm256_mul_ps(X, two); Y = exp8_approx(X); Y = _mm256_mul_ps(_mm256_sub_ps(Y, one), _mm256_rcp_ps(_mm256_add_ps(Y, one))); _mm256_storeu_ps(&y[i], Y); } for (;i<N;i++) { float ex2; ex2 = celt_exp(2*x[i]); y[i] = (ex2-1)/(ex2+1); } } static void vec_sigmoid(float *y, const float *x, int N) { int i; for (i=0;i<N-7;i+=8) { const __m256 one = _mm256_set1_ps(1.f); __m256 X, Y; X = _mm256_loadu_ps(&x[i]); Y = exp8_approx(X); Y = _mm256_mul_ps(Y, _mm256_rcp_ps(_mm256_add_ps(Y, one))); _mm256_storeu_ps(&y[i], Y); } for (;i<N;i++) { float ex; ex = celt_exp(x[i]); y[i] = (ex)/(ex+1); } } static void sgemv_accum16(float *out, const float *weights, int rows, int cols, int col_stride, const float *x) { // #pragma omp parallel for for ( int i = 0; i < rows; i += 16 ) { float *y = &out[i]; __m256 vy0 = _mm256_loadu_ps(&y[0]); __m256 vy8 = _mm256_loadu_ps(&y[8]); for ( int j = 0; j < cols; j++ ) { int weights_id = j*col_stride + i; __m256 vxj = _mm256_broadcast_ss(&x[j]); __m256 vw0 = _mm256_loadu_ps(&weights[weights_id]); __m256 vw8 = _mm256_loadu_ps(&weights[weights_id + 8]); vy0 = _mm256_fmadd_ps(vw0, vxj, vy0); vy8 = _mm256_fmadd_ps(vw8, vxj, vy8); } _mm256_storeu_ps (&y[0], vy0); _mm256_storeu_ps (&y[8], vy8); } } static void sparse_sgemv_accum16(float *out, const float *weights, int rows, const int *idx, const float *x) { #pragma omp parallel for for ( int i = 0; i < rows; i += 16 ) { int tmp_i = i / 16; int offset_w = idx[3*tmp_i + 1]; int offset_idx = idx[3*tmp_i + 2]; float *y = &out[i]; __m256 vy0 = _mm256_loadu_ps(&y[0]); __m256 vy8 = _mm256_loadu_ps(&y[8]); for ( int j = 0; j < idx[3*tmp_i]; j++ ) { int id = idx[offset_idx + j]; __m256 vxj = _mm256_broadcast_ss(&x[id]); __m256 vw0 = _mm256_loadu_ps(&weights[offset_w]); __m256 vw8 = _mm256_loadu_ps(&weights[offset_w+8]); vy0 = _mm256_fmadd_ps(vw0, vxj, vy0); vy8 = _mm256_fmadd_ps(vw8, vxj, vy8); offset_w += 16; } _mm256_storeu_ps (&y[0], vy0); _mm256_storeu_ps (&y[8], vy8); } }
wavelet.c
/* Copyright 2014. The Regents of the University of California. * Copyright 2017. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2013 Frank Ong <[email protected]> * 2013-2017 Martin Uecker <[email protected]> */ /* * md_*-based multi-dimensional wavelet implementation * * - 3 levels (1d, md, md-hierarchical) * - all higher-level code should work for GPU as well * * Bugs: * * - GPU version is not optimized * - memory use could possible be reduced * * Missing: * * - different boundary conditions * (symmetric, periodic, zero) */ #include <stdio.h> #include <complex.h> #include <assert.h> #include <limits.h> #include <stdbool.h> #include "misc/misc.h" #include "misc/debug.h" #include "num/flpmath.h" #include "num/multind.h" #include "num/ops.h" #ifdef USE_CUDA #include "num/gpuops.h" #include "wavelet/wl3-cuda.h" #endif #include "wavelet.h" #ifdef __MINGW32__ #define ffs __builtin_ffs #endif // layer 1 - 1-dimensional wavelet transform static unsigned int bandsize(unsigned int imsize, unsigned int flen) { return (imsize + flen - 1) / 2; } static complex float* access(const long str[3], complex float* x, long i, long j, long k) { return (void*)x + str[2] * i + str[1] * j + str[0] * k; } static const complex float* caccess(const long str[3], const complex float* x, long i, long j, long k) { return (const void*)x + str[2] * i + str[1] * j + str[0] * k; } static int coord(int l, int x, int flen, int k) { int n = 2 * l + 1 - (flen - 1) + k; if (n < 0) n = -n - 1; if (n >= x) n = x - 1 - (n - x); return n; } static void wavelet_down3(const long dims[3], const long out_str[3], complex float* out, const long in_str[3], const complex float* in, unsigned int flen, const float filter[flen]) { #pragma omp parallel for collapse(3) for (unsigned int i = 0; i < dims[2]; i++) for (unsigned int j = 0; j < bandsize(dims[1], flen); j++) for (unsigned int k = 0; k < dims[0]; k++) { *access(out_str, out, i, j, k) = 0.; for (unsigned int l = 0; l < flen; l++) { int n = coord(j, dims[1], flen, l); *access(out_str, out, i, j, k) += *(caccess(in_str, in, i, n, k)) * filter[flen - l - 1]; } } } static void wavelet_up3(const long dims[3], const long out_str[3], complex float* out, const long in_str[3], const complex float* in, unsigned int flen, const float filter[flen]) { // md_clear2(3, dims, out_str, out, CFL_SIZE); #pragma omp parallel for collapse(3) for (unsigned int i = 0; i < dims[2]; i++) for (unsigned int j = 0; j < dims[1]; j++) for (unsigned int k = 0; k < dims[0]; k++) { // *access(out_str, out, i, j, k) = 0.; for (unsigned int l = ((j + flen / 2 - 0) - (flen - 1)) % 2; l < flen; l += 2) { int n = ((j + flen / 2 - 0) - (flen - 1) + l) / 2; if ((0 <= n) && ((unsigned int)n < bandsize(dims[1], flen))) *access(out_str, out, i, j, k) += *caccess(in_str, in, i, n, k) * filter[flen - l - 1]; } } } void fwt1(unsigned int N, unsigned int d, const long dims[N], const long ostr[N], complex float* low, complex float* hgh, const long istr[N], const complex float* in, const long flen, const float filter[2][2][flen]) { debug_printf(DP_DEBUG4, "fwt1: %d/%d\n", d, N); debug_print_dims(DP_DEBUG4, N, dims); assert(dims[d] >= 2); long odims[N]; md_copy_dims(N, odims, dims); odims[d] = bandsize(dims[d], flen); debug_print_dims(DP_DEBUG4, N, odims); long o = d + 1; long u = N - o; // 0 1 2 3 4 5 6|7 // --d-- * --u--|N // ---o--- assert(d == md_calc_blockdim(d, dims + 0, istr + 0, CFL_SIZE)); assert(u == md_calc_blockdim(u, dims + o, istr + o, CFL_SIZE * md_calc_size(o, dims))); assert(d == md_calc_blockdim(d, odims + 0, ostr + 0, CFL_SIZE)); assert(u == md_calc_blockdim(u, odims + o, ostr + o, CFL_SIZE * md_calc_size(o, odims))); // merge dims long wdims[3] = { md_calc_size(d, dims), dims[d], md_calc_size(u, dims + o) }; long wistr[3] = { CFL_SIZE, istr[d], CFL_SIZE * md_calc_size(o, dims) }; long wostr[3] = { CFL_SIZE, ostr[d], CFL_SIZE * md_calc_size(o, odims) }; #ifdef USE_CUDA if (cuda_ondevice(in)) { assert(cuda_ondevice(low)); assert(cuda_ondevice(hgh)); float* flow = md_gpu_move(1, MD_DIMS(flen), filter[0][0], FL_SIZE); float* fhgh = md_gpu_move(1, MD_DIMS(flen), filter[0][1], FL_SIZE); wl3_cuda_down3(wdims, wostr, low, wistr, in, flen, flow); wl3_cuda_down3(wdims, wostr, hgh, wistr, in, flen, fhgh); md_free(flow); md_free(fhgh); return; } #endif // no clear needed wavelet_down3(wdims, wostr, low, wistr, in, flen, filter[0][0]); wavelet_down3(wdims, wostr, hgh, wistr, in, flen, filter[0][1]); } void iwt1(unsigned int N, unsigned int d, const long dims[N], const long ostr[N], complex float* out, const long istr[N], const complex float* low, const complex float* hgh, const long flen, const float filter[2][2][flen]) { debug_printf(DP_DEBUG4, "ifwt1: %d/%d\n", d, N); debug_print_dims(DP_DEBUG4, N, dims); assert(dims[d] >= 2); long idims[N]; md_copy_dims(N, idims, dims); idims[d] = bandsize(dims[d], flen); debug_print_dims(DP_DEBUG4, N, idims); long o = d + 1; long u = N - o; // 0 1 2 3 4 5 6|7 // --d-- * --u--|N // ---o--- assert(d == md_calc_blockdim(d, dims + 0, ostr + 0, CFL_SIZE)); assert(u == md_calc_blockdim(u, dims + o, ostr + o, CFL_SIZE * md_calc_size(o, dims))); assert(d == md_calc_blockdim(d, idims + 0, istr + 0, CFL_SIZE)); assert(u == md_calc_blockdim(u, idims + o, istr + o, CFL_SIZE * md_calc_size(o, idims))); long wdims[3] = { md_calc_size(d, dims), dims[d], md_calc_size(u, dims + o) }; long wistr[3] = { CFL_SIZE, istr[d], CFL_SIZE * md_calc_size(o, idims) }; long wostr[3] = { CFL_SIZE, ostr[d], CFL_SIZE * md_calc_size(o, dims) }; md_clear(3, wdims, out, CFL_SIZE); // we cannot clear because we merge outputs #ifdef USE_CUDA if (cuda_ondevice(out)) { assert(cuda_ondevice(low)); assert(cuda_ondevice(hgh)); float* flow = md_gpu_move(1, MD_DIMS(flen), filter[1][0], FL_SIZE); float* fhgh = md_gpu_move(1, MD_DIMS(flen), filter[1][1], FL_SIZE); wl3_cuda_up3(wdims, wostr, out, wistr, low, flen, flow); wl3_cuda_up3(wdims, wostr, out, wistr, hgh, flen, fhgh); md_free(flow); md_free(fhgh); return; } #endif wavelet_up3(wdims, wostr, out, wistr, low, flen, filter[1][0]); wavelet_up3(wdims, wostr, out, wistr, hgh, flen, filter[1][1]); } // layer 2 - multi-dimensional wavelet transform static void wavelet_dims_r(unsigned int N, unsigned int n, unsigned int flags, long odims[2 * N], const long dims[N], const long flen) { if (MD_IS_SET(flags, n)) { odims[0 + n] = bandsize(dims[n], flen); odims[N + n] = 2; } if (n > 0) wavelet_dims_r(N, n - 1, flags, odims, dims, flen); } void wavelet_dims(unsigned int N, unsigned int flags, long odims[2 * N], const long dims[N], const long flen) { md_copy_dims(N, odims, dims); md_singleton_dims(N, odims + N); wavelet_dims_r(N, N - 1, flags, odims, dims, flen); } void fwtN(unsigned int N, unsigned int flags, const long shifts[N], const long dims[N], const long ostr[2 * N], complex float* out, const long istr[N], const complex float* in, const long flen, const float filter[2][2][flen]) { long odims[2 * N]; wavelet_dims(N, flags, odims, dims, flen); assert(md_calc_size(2 * N, odims) >= md_calc_size(N, dims)); // FIXME one of these is unnecessary if we use the output complex float* tmpA = md_alloc_sameplace(2 * N, odims, CFL_SIZE, out); complex float* tmpB = md_alloc_sameplace(2 * N, odims, CFL_SIZE, out); long tidims[2 * N]; md_copy_dims(N, tidims, dims); md_singleton_dims(N, tidims + N); long tistrs[2 * N]; md_calc_strides(2 * N, tistrs, tidims, CFL_SIZE); long todims[2 * N]; md_copy_dims(2 * N, todims, tidims); long tostrs[2 * N]; // maybe we should push the randshift into lower levels //md_copy2(N, dims, tistrs, tmpA, istr, in, CFL_SIZE); md_circ_shift2(N, dims, shifts, tistrs, tmpA, istr, in, CFL_SIZE); for (unsigned int i = 0; i < N; i++) { if (MD_IS_SET(flags, i)) { todims[0 + i] = odims[0 + i]; todims[N + i] = odims[N + i]; md_calc_strides(2 * N, tostrs, todims, CFL_SIZE); fwt1(2 * N, i, tidims, tostrs, tmpB, (void*)tmpB + tostrs[N + i], tistrs, tmpA, flen, filter); md_copy_dims(2 * N, tidims, todims); md_copy_dims(2 * N, tistrs, tostrs); complex float* swap = tmpA; tmpA = tmpB; tmpB = swap; } } md_copy2(2 * N, todims, ostr, out, tostrs, tmpA, CFL_SIZE); md_free(tmpA); md_free(tmpB); } void iwtN(unsigned int N, unsigned int flags, const long shifts[N], const long dims[N], const long ostr[N], complex float* out, const long istr[2 * N], const complex float* in, const long flen, const float filter[2][2][flen]) { long idims[2 * N]; wavelet_dims(N, flags, idims, dims, flen); assert(md_calc_size(2 * N, idims) >= md_calc_size(N, dims)); complex float* tmpA = md_alloc_sameplace(2 * N, idims, CFL_SIZE, out); complex float* tmpB = md_alloc_sameplace(2 * N, idims, CFL_SIZE, out); long tidims[2 * N]; md_copy_dims(2 * N, tidims, idims); long tistrs[2 * N]; md_calc_strides(2 * N, tistrs, tidims, CFL_SIZE); long todims[2 * N]; md_copy_dims(2 * N, todims, tidims); long tostrs[2 * N]; long ishifts[N]; for (unsigned int i = 0; i < N; i++) ishifts[i] = -shifts[i]; md_copy2(2 * N, tidims, tistrs, tmpA, istr, in, CFL_SIZE); for (int i = N - 1; i >= 0; i--) { // run backwards to maintain contigous blocks if (MD_IS_SET(flags, i)) { todims[0 + i] = dims[0 + i]; todims[N + i] = 1; md_calc_strides(2 * N, tostrs, todims, CFL_SIZE); iwt1(2 * N, i, todims, tostrs, tmpB, tistrs, tmpA, (void*)tmpA + tistrs[N + i], flen, filter); md_copy_dims(2 * N, tidims, todims); md_copy_dims(2 * N, tistrs, tostrs); complex float* swap = tmpA; tmpA = tmpB; tmpB = swap; } } //md_copy2(N, dims, ostr, out, tostrs, tmpA, CFL_SIZE); md_circ_shift2(N, dims, ishifts, ostr, out, tostrs, tmpA, CFL_SIZE); md_free(tmpA); md_free(tmpB); } // layer 3 - hierarchical multi-dimensional wavelet transform static long wavelet_filter_flags(unsigned int N, long flags, const long dims[N], const long min[N]) { for (unsigned int i = 0; i < N; i++) if (dims[i] < min[i]) // CHECK flags = MD_CLEAR(flags, i); return flags; } long wavelet_num_levels(unsigned int N, unsigned int flags, const long dims[N], const long min[N], const long flen) { if (0 == flags) return 1; long wdims[2 * N]; wavelet_dims(N, flags, wdims, dims, flen); return 1 + wavelet_num_levels(N, wavelet_filter_flags(N, flags, wdims, min), wdims, min, flen); } static long wavelet_coeffs_r(unsigned int levels, unsigned int N, unsigned int flags, const long dims[N], const long min[N], const long flen) { long wdims[2 * N]; wavelet_dims(N, flags, wdims, dims, flen); long coeffs = md_calc_size(N, wdims); long bands = md_calc_size(N, wdims + N); assert((0 == flags) == (0 == levels)); if (0 == flags) return bands * coeffs; return coeffs * (bands - 1) + wavelet_coeffs_r(levels - 1, N, wavelet_filter_flags(N, flags, wdims, min), wdims, min, flen); } long wavelet_coeffs(unsigned int N, unsigned int flags, const long dims[N], const long min[N], const long flen) { unsigned int levels = wavelet_num_levels(N, flags, dims, min, flen); assert(levels > 0); return wavelet_coeffs_r(levels - 1, N, flags, dims, min, flen); } void wavelet_thresh(unsigned int N, float lambda, unsigned int flags, unsigned int jflags, const long shifts[N], const long dims[N], complex float* out, const complex float* in, const long minsize[N], long flen, const float filter[2][2][flen]) { assert(0 == (flags & jflags)); long wdims[N]; wavelet_coeffs2(N, flags, wdims, dims, minsize, flen); long wstr[N]; md_calc_strides(N, wstr, wdims, CFL_SIZE); complex float* tmp = md_alloc_sameplace(N, wdims, CFL_SIZE, out); long str[N]; md_calc_strides(N, str, dims, CFL_SIZE); fwt2(N, flags, shifts, wdims, wstr, tmp, dims, str, in, minsize, flen, filter); md_zsoftthresh(N, wdims, lambda, jflags, tmp, tmp); iwt2(N, flags, shifts, dims, str, out, wdims, wstr, tmp, minsize, flen, filter); md_free(tmp); } void wavelet_coeffs2(unsigned int N, unsigned int flags, long odims[N], const long dims[N], const long min[N], const long flen) { md_select_dims(N, ~flags, odims, dims); if (0 == flags) return; unsigned int levels = wavelet_num_levels(N, flags, dims, min, flen); assert(levels > 0); long wdims[N]; md_select_dims(N, flags, wdims, dims); // remove unmodified dims unsigned int b = ffs(flags) - 1; odims[b] = wavelet_coeffs_r(levels - 1, N, flags, wdims, min, flen); } static bool wavelet_check_dims(unsigned int N, unsigned int flags, const long dims[N], const long minsize[N]) { for (unsigned int i = 0; i < N; i++) if (MD_IS_SET(flags, i)) if ((minsize[i] <= 2) || (dims[i] < minsize[i])) return false; return true; } static void embed(unsigned int N, unsigned int flags, long ostr[N], const long dims[N], const long str[N]) { unsigned int b = ffs(flags) - 1; long dims1[N]; md_select_dims(N, flags, dims1, dims); md_calc_strides(N, ostr, dims1, str[b]); for (unsigned int i = 0; i < N; i++) if (!MD_IS_SET(flags, i)) ostr[i] = str[i]; } void fwt2(unsigned int N, unsigned int flags, const long shifts[N], const long odims[N], const long ostr[N], complex float* out, const long idims[N], const long istr[N], const complex float* in, const long minsize[N], long flen, const float filter[2][2][flen]) { assert(wavelet_check_dims(N, flags, idims, minsize)); if (0 == flags) { // note: recursion does *not* end here assert(md_check_compat(N, 0u, odims, idims)); md_copy2(N, idims, ostr, out, istr, in, CFL_SIZE); return; } // check output dimensions long odims2[N]; wavelet_coeffs2(N, flags, odims2, idims, minsize, flen); assert(md_check_compat(N, 0u, odims2, odims)); long wdims2[2 * N]; wavelet_dims(N, flags, wdims2, idims, flen); // only consider transform dims... long dims1[N]; md_select_dims(N, flags, dims1, idims); long wdims[2 * N]; wavelet_dims(N, flags, wdims, dims1, flen); long level_coeffs = md_calc_size(2 * N, wdims); // ... which get embedded in dimension b unsigned int b = ffs(flags) - 1; long ostr2[2 * N]; md_calc_strides(2 * N, ostr2, wdims, ostr[b]); // merge with original strides for (unsigned int i = 0; i < N; i++) if (!MD_IS_SET(flags, i)) ostr2[i] = ostr[i]; assert(odims[b] >= level_coeffs); long offset = (odims[b] - level_coeffs) * (ostr[b] / CFL_SIZE); long bands = md_calc_size(N, wdims + N); long coeffs = md_calc_size(N, wdims + 0); debug_printf(DP_DEBUG4, "fwt2: flags:%d lcoeffs:%ld coeffs:%ld (space:%ld) bands:%ld str:%ld off:%ld\n", flags, level_coeffs, coeffs, odims2[b], bands, ostr[b], offset / istr[b]); // subtract coefficients in high band odims2[b] -= (bands - 1) * coeffs; assert(odims2[b] > 0); long shifts0[N]; for (unsigned int i = 0; i < N; i++) shifts0[i] = 0; unsigned int flags2 = wavelet_filter_flags(N, flags, wdims, minsize); assert((0 == offset) == (0u == flags2)); fwtN(N, flags, shifts, idims, ostr2, out + offset, istr, in, flen, filter); if (0 != flags2) { long odims3[N]; wavelet_coeffs2(N, flags2, odims3, wdims2, minsize, flen); long ostr3[N]; embed(N, flags, ostr3, odims3, ostr); fwt2(N, flags2, shifts0, odims3, ostr3, out, wdims2, ostr2, out + offset, minsize, flen, filter); } } void iwt2(unsigned int N, unsigned int flags, const long shifts[N], const long odims[N], const long ostr[N], complex float* out, const long idims[N], const long istr[N], const complex float* in, const long minsize[N], const long flen, const float filter[2][2][flen]) { assert(wavelet_check_dims(N, flags, odims, minsize)); if (0 == flags) { // note: recursion does *not* end here assert(md_check_compat(N, 0u, odims, idims)); md_copy2(N, idims, ostr, out, istr, in, CFL_SIZE); return; } // check input dimensions long idims2[N]; wavelet_coeffs2(N, flags, idims2, odims, minsize, flen); assert(md_check_compat(N, 0u, idims2, idims)); long wdims2[2 * N]; wavelet_dims(N, flags, wdims2, odims, flen); // only consider transform dims... long dims1[N]; md_select_dims(N, flags, dims1, odims); long wdims[2 * N]; wavelet_dims(N, flags, wdims, dims1, flen); long level_coeffs = md_calc_size(2 * N, wdims); // ... which get embedded in dimension b unsigned int b = ffs(flags) - 1; long istr2[2 * N]; md_calc_strides(2 * N, istr2, wdims, istr[b]); // merge with original strides for (unsigned int i = 0; i < N; i++) if (!MD_IS_SET(flags, i)) istr2[i] = istr[i]; assert(idims[b] >= level_coeffs); long offset = (idims[b] - level_coeffs) * (istr[b] / CFL_SIZE); long bands = md_calc_size(N, wdims + N); long coeffs = md_calc_size(N, wdims + 0); // subtract coefficients in high band idims2[b] -= (bands - 1) * coeffs; assert(idims2[b] > 0); debug_printf(DP_DEBUG4, "ifwt2: flags:%d lcoeffs:%ld coeffs:%ld (space:%ld) bands:%ld str:%ld off:%ld\n", flags, level_coeffs, coeffs, idims2[b], bands, istr[b], offset / ostr[b]); // fix me we need temp storage complex float* tmp = md_alloc_sameplace(2 * N, wdims2, CFL_SIZE, out); long tstr[2 * N]; md_calc_strides(2 * N, tstr, wdims2, CFL_SIZE); md_copy2(2 * N, wdims2, tstr, tmp, istr2, in + offset, CFL_SIZE); long shifts0[N]; for (unsigned int i = 0; i < N; i++) shifts0[i] = 0; unsigned int flags2 = wavelet_filter_flags(N, flags, wdims, minsize); assert((0 == offset) == (0u == flags2)); if (0u != flags2) { long idims3[N]; wavelet_coeffs2(N, flags2, idims3, wdims2, minsize, flen); long istr3[N]; embed(N, flags, istr3, idims3, istr); iwt2(N, flags2, shifts0, wdims2, tstr, tmp, idims3, istr3, in, minsize, flen, filter); } iwtN(N, flags, shifts, odims, ostr, out, tstr, tmp, flen, filter); md_free(tmp); } void fwt(unsigned int N, unsigned int flags, const long shifts[N], const long odims[N], complex float* out, const long idims[N], const complex float* in, const long minsize[N], long flen, const float filter[2][2][flen]) { fwt2(N, flags, shifts, odims, MD_STRIDES(N, odims, CFL_SIZE), out, idims, MD_STRIDES(N, idims, CFL_SIZE), in, minsize, flen, filter); } void iwt(unsigned int N, unsigned int flags, const long shifts[N], const long odims[N], complex float* out, const long idims[N], const complex float* in, const long minsize[N], const long flen, const float filter[2][2][flen]) { iwt2(N, flags, shifts, odims, MD_STRIDES(N, odims, CFL_SIZE), out, idims, MD_STRIDES(N, idims, CFL_SIZE), in, minsize, flen, filter); } // 1D Wavelet coefficeints. // The first dimension indexes along forward wavelet decomposition and reconstruction filters for fwt and iwt // The second dimension indexes along low-pass and high-pass filters // The third dimension is the number of filter taps. const float wavelet_haar[2][2][2] = { { { +0.7071067811865475, +0.7071067811865475 }, { -0.7071067811865475, +0.7071067811865475 }, }, { { +0.7071067811865475, +0.7071067811865475 }, { +0.7071067811865475, -0.7071067811865475 }, }, }; const float wavelet_dau2[2][2][4] = { { { -0.1294095225512603, +0.2241438680420134, +0.8365163037378077, +0.4829629131445341 }, { -0.4829629131445341, +0.8365163037378077, -0.2241438680420134, -0.1294095225512603 }, }, { { +0.4829629131445341, +0.8365163037378077, +0.2241438680420134, -0.1294095225512603 }, { -0.1294095225512603, -0.2241438680420134, +0.8365163037378077, -0.4829629131445341 }, }, }; // Cohen-Daubechies-Feaveau wavelet const float wavelet_cdf44[2][2][10] = { { { +0.00000000000000000, +0.03782845550726404 , -0.023849465019556843, -0.11062440441843718 , +0.37740285561283066, +0.85269867900889385, +0.37740285561283066 , -0.11062440441843718 , -0.023849465019556843, +0.03782845550726404 }, { +0.00000000000000000, -0.064538882628697058, +0.040689417609164058, +0.41809227322161724 , -0.7884856164055829, +0.41809227322161724, +0.040689417609164058, -0.064538882628697058, +0.00000000000000000 , +0.00000000000000000 }, }, { { +0.00000000000000000, -0.064538882628697058, -0.040689417609164058, +0.41809227322161724 , +0.7884856164055829, +0.41809227322161724, -0.040689417609164058, -0.064538882628697058, +0.000000000000000000, +0.00000000000000000 }, { +0.00000000000000000, -0.03782845550726404 , -0.023849465019556843, +0.11062440441843718 , +0.37740285561283066, -0.85269867900889385, +0.37740285561283066 , +0.11062440441843718 , -0.023849465019556843, -0.03782845550726404 }, }, };
Example1.c
#include <stdio.h> int main(){ int T[5]; int sum = 0; // initializing array T for (int i = 0; i < 10; i ++) { T[i] = i; } // running the loop 10 times using openmp #pragma omp parallel for shared (T,sum) reduction (+ : sum) for ( int i = 0; i < 100; i ++) { // assign value for elements in array T for (int j =0; j < 5; j++) { T[j] = i ; } // increase "sum" by the toal of T array module by 2 sum += (T[0] + T[1] + T[2] + T[3] + T[4]) % 2; } printf("sum = %d\n",sum ); }
GB_unaryop__lnot_uint64_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint64_fp32 // op(A') function: GB_tran__lnot_uint64_fp32 // C type: uint64_t // A type: float // cast: uint64_t cij ; GB_CAST_UNSIGNED(cij,aij,64) // unaryop: cij = !(aij != 0) #define GB_ATYPE \ float #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ uint64_t z ; GB_CAST_UNSIGNED(z,x,64) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint64_fp32 ( uint64_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
soxr.c
/* SoX Resampler Library Copyright (c) 2007-13 [email protected] * Licence for this file: LGPL v2.1 See LICENCE for details. */ #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "soxr.h" #include "data-io.h" #include "internal.h" char const * soxr_version(void) { return "libsoxr-" SOXR_THIS_VERSION_STR; } typedef void sample_t; /* float or double */ typedef void (* fn_t)(void); typedef fn_t control_block_t[10]; #define resampler_input (*(sample_t * (*)(void *, sample_t * samples, size_t n))p->control_block[0]) #define resampler_process (*(void (*)(void *, size_t))p->control_block[1]) #define resampler_output (*(sample_t const * (*)(void *, sample_t * samples, size_t * n))p->control_block[2]) #define resampler_flush (*(void (*)(void *))p->control_block[3]) #define resampler_close (*(void (*)(void *))p->control_block[4]) #define resampler_delay (*(double (*)(void *))p->control_block[5]) #define resampler_sizes (*(void (*)(size_t * shared, size_t * channel))p->control_block[6]) #define resampler_create (*(char const * (*)(void * channel, void * shared, double io_ratio, soxr_quality_spec_t * q_spec, soxr_runtime_spec_t * r_spec, double scale))p->control_block[7]) #define resampler_set_io_ratio (*(void (*)(void *, double io_ratio, size_t len))p->control_block[8]) #define resampler_id (*(char const * (*)(void))p->control_block[9]) typedef void * resampler_t; /* For one channel. */ typedef void * resampler_shared_t; /* Between channels. */ typedef void (* deinterleave_t)(sample_t * * dest, soxr_datatype_t data_type, void const * * src0, size_t n, unsigned ch); typedef size_t (* interleave_t)(soxr_datatype_t data_type, void * * dest, sample_t const * const * src, size_t, unsigned, unsigned long *); struct soxr { unsigned num_channels; double io_ratio; soxr_error_t error; soxr_quality_spec_t q_spec; soxr_io_spec_t io_spec; soxr_runtime_spec_t runtime_spec; void * input_fn_state; soxr_input_fn_t input_fn; size_t max_ilen; resampler_shared_t shared; resampler_t * resamplers; control_block_t control_block; deinterleave_t deinterleave; interleave_t interleave; void * * channel_ptrs; size_t clips; unsigned long seed; int flushing; }; /* TODO: these should not be here. */ #define TO_3dB(a) ((1.6e-6*a-7.5e-4)*a+.646) #define LOW_Q_BW0 (1385 / 2048.) /* 0.67625 rounded to be a FP exact. */ soxr_quality_spec_t soxr_quality_spec(unsigned long recipe, unsigned long flags) { soxr_quality_spec_t spec, * p = &spec; unsigned quality = recipe & 0xf; double rej; memset(p, 0, sizeof(*p)); if (quality > 13) { p->e = "invalid quality type"; return spec; } if (quality == 13) quality = 6; else if (quality > 10) quality = 0; p->phase_response = "\62\31\144"[(recipe & 0x30)>>8]; p->stopband_begin = 1; p->precision = !quality? 0: quality < 3? 16 : quality < 8? 4 + quality * 4 : 55 - quality * 4; rej = p->precision * linear_to_dB(2.); p->flags = flags; if (quality < 8) { p->passband_end = quality == 1? LOW_Q_BW0 : 1 - .05 / TO_3dB(rej); if (quality <= 2) p->flags &= ~SOXR_ROLLOFF_NONE, p->flags |= SOXR_ROLLOFF_MEDIUM; } else { static float const bw[] = {.931f, .832f, .663f}; p->passband_end = bw[quality - 8]; if (quality - 8 == 2) p->flags &= ~SOXR_ROLLOFF_NONE, p->flags |= SOXR_ROLLOFF_MEDIUM; } if (recipe & SOXR_STEEP_FILTER) p->passband_end = 1 - .01 / TO_3dB(rej); return spec; } char const * soxr_engine(soxr_t p) { return resampler_id(); } size_t * soxr_num_clips(soxr_t p) { return &p->clips; } soxr_error_t soxr_error(soxr_t p) { return p->error; } soxr_runtime_spec_t soxr_runtime_spec(unsigned num_threads) { soxr_runtime_spec_t spec, * p = &spec; memset(p, 0, sizeof(*p)); p->log2_min_dft_size = 10; p->log2_large_dft_size = 17; p->coef_size_kbytes = 400; p->num_threads = num_threads; return spec; } soxr_io_spec_t soxr_io_spec( soxr_datatype_t itype, soxr_datatype_t otype) { soxr_io_spec_t spec, * p = &spec; memset(p, 0, sizeof(*p)); if ((itype | otype) >= SOXR_SPLIT * 2) p->e = "invalid io datatype(s)"; else { p->itype = itype; p->otype = otype; p->scale = 1; } return spec; } #if HAVE_SIMD static bool cpu_has_simd(void) { #if defined __x86_64__ || defined _M_X64 return true; #elif defined __GNUC__ && defined i386 uint32_t eax, ebx, ecx, edx; __asm__ __volatile__ ( "pushl %%ebx \n\t" "cpuid \n\t" "movl %%ebx, %1\n\t" "popl %%ebx \n\t" : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx) : "a"(1) : "cc" ); return !!(edx & 0x06000000); #elif defined _MSC_VER && defined _M_IX86 uint32_t d; __asm { xor eax, eax inc eax push ebx cpuid pop ebx mov d, edx } return !!(d & 0x06000000); #endif return false; } #endif extern control_block_t _soxr_rate32s_cb, _soxr_rate32_cb, _soxr_rate64_cb, _soxr_vr32_cb; soxr_t soxr_create( double input_rate, double output_rate, unsigned num_channels, soxr_error_t * error0, soxr_io_spec_t const * io_spec, soxr_quality_spec_t const * q_spec, soxr_runtime_spec_t const * runtime_spec) { double io_ratio = output_rate? input_rate? input_rate / output_rate : -1 : input_rate? -1 : 0; static const float datatype_full_scale[] = {1, 1, 65536.*32768, 32768}; soxr_t p = 0; soxr_error_t error = 0; if (q_spec && q_spec->e) error = q_spec->e; else if (io_spec && (io_spec->itype | io_spec->otype) >= SOXR_SPLIT * 2) error = "invalid io datatype(s)"; if (!error && !(p = calloc(sizeof(*p), 1))) error = "malloc failed"; if (p) { p->q_spec = q_spec? *q_spec : soxr_quality_spec(SOXR_HQ, 0); if (q_spec) { /* Backwards compatibility with original API: */ if (p->q_spec.passband_end > 2) p->q_spec.passband_end /= 100; if (p->q_spec.stopband_begin > 2) p->q_spec.stopband_begin = 2 - p->q_spec.stopband_begin / 100; } p->io_ratio = io_ratio; p->num_channels = num_channels; if (io_spec) p->io_spec = *io_spec; else p->io_spec.scale = 1; p->runtime_spec = runtime_spec? *runtime_spec : soxr_runtime_spec(1); p->io_spec.scale *= datatype_full_scale[p->io_spec.otype & 3] / datatype_full_scale[p->io_spec.itype & 3]; p->seed = (unsigned long)time(0) ^ (unsigned long)(size_t)p; #if HAVE_SINGLE_PRECISION if (!HAVE_DOUBLE_PRECISION || (p->q_spec.precision <= 20 && !(p->q_spec.flags & SOXR_DOUBLE_PRECISION)) || (p->q_spec.flags & SOXR_VR)) { p->deinterleave = (deinterleave_t)_soxr_deinterleave_f; p->interleave = (interleave_t)_soxr_interleave_f; memcpy(&p->control_block, (p->q_spec.flags & SOXR_VR)? &_soxr_vr32_cb : #if HAVE_SIMD cpu_has_simd()? &_soxr_rate32s_cb : #endif &_soxr_rate32_cb, sizeof(p->control_block)); } #if HAVE_DOUBLE_PRECISION else #endif #endif #if HAVE_DOUBLE_PRECISION { p->deinterleave = (deinterleave_t)_soxr_deinterleave; p->interleave = (interleave_t)_soxr_interleave; memcpy(&p->control_block, &_soxr_rate64_cb, sizeof(p->control_block)); } #endif if (p->num_channels && io_ratio) error = soxr_set_io_ratio(p, io_ratio, 0); } if (error) soxr_delete(p), p = 0; if (error0) *error0 = error; return p; } soxr_error_t soxr_set_input_fn(soxr_t p, soxr_input_fn_t input_fn, void * input_fn_state, size_t max_ilen) { p->input_fn_state = input_fn_state; p->input_fn = input_fn; p->max_ilen = max_ilen? max_ilen : (size_t)-1; return 0; } static void soxr_delete0(soxr_t p) { unsigned i; if (p->resamplers) for (i = 0; i < p->num_channels; ++i) { if (p->resamplers[i]) resampler_close(p->resamplers[i]); free(p->resamplers[i]); } free(p->resamplers); free(p->channel_ptrs); free(p->shared); memset(p, 0, sizeof(*p)); } double soxr_delay(soxr_t p) { return (p && !p->error && p->resamplers)? resampler_delay(p->resamplers[0]) : 0; } static soxr_error_t fatal_error(soxr_t p, soxr_error_t error) { soxr_delete0(p); return p->error = error; } static soxr_error_t initialise(soxr_t p) { unsigned i; size_t shared_size, channel_size; resampler_sizes(&shared_size, &channel_size); p->channel_ptrs = calloc(sizeof(*p->channel_ptrs), p->num_channels); p->shared = calloc(shared_size, 1); p->resamplers = calloc(sizeof(*p->resamplers), p->num_channels); if (!p->shared || !p->channel_ptrs || !p->resamplers) return fatal_error(p, "malloc failed"); for (i = 0; i < p->num_channels; ++i) { soxr_error_t error; if (!(p->resamplers[i] = calloc(channel_size, 1))) return fatal_error(p, "malloc failed"); error = resampler_create( p->resamplers[i], p->shared, p->io_ratio, &p->q_spec, &p->runtime_spec, p->io_spec.scale); if (error) return fatal_error(p, error); } return 0; } soxr_error_t soxr_set_num_channels(soxr_t p, unsigned num_channels) { if (!p) return "invalid soxr_t pointer"; if (num_channels == p->num_channels) return p->error; if (!num_channels) return "invalid # of channels"; if (p->resamplers) return "# of channels can't be changed"; p->num_channels = num_channels; return soxr_set_io_ratio(p, p->io_ratio, 0); } soxr_error_t soxr_set_io_ratio(soxr_t p, double io_ratio, size_t slew_len) { unsigned i; soxr_error_t error; if (!p) return "invalid soxr_t pointer"; if ((error = p->error)) return error; if (!p->num_channels) return "must set # channels before O/I ratio"; if (io_ratio <= 0) return "I/O ratio out-of-range"; if (!p->channel_ptrs) { p->io_ratio = io_ratio; return initialise(p); } if (p->control_block[8]) { for (i = 0; !error && i < p->num_channels; ++i) resampler_set_io_ratio(p->resamplers[i], io_ratio, slew_len); return error; } return fabs(p->io_ratio - io_ratio) < 1e-15? 0 : "Varying O/I ratio is not supported with this quality level"; } void soxr_delete(soxr_t p) { if (p) soxr_delete0(p), free(p); } soxr_error_t soxr_clear(soxr_t p) /* TODO: this, properly. */ { if (p) { struct soxr tmp = *p; soxr_delete0(p); memset(p, 0, sizeof(*p)); p->input_fn = tmp.input_fn; p->runtime_spec = tmp.runtime_spec; p->q_spec = tmp.q_spec; p->io_spec = tmp.io_spec; p->num_channels = tmp.num_channels; p->input_fn_state = tmp.input_fn_state; memcpy(p->control_block, tmp.control_block, sizeof(p->control_block)); p->deinterleave = tmp.deinterleave; p->interleave = tmp.interleave; return 0; } return "invalid soxr_t pointer"; } static void soxr_input_1ch(soxr_t p, unsigned i, soxr_cbuf_t src, size_t len) { sample_t * dest = resampler_input(p->resamplers[i], NULL, len); (*p->deinterleave)(&dest, p->io_spec.itype, &src, len, 1); } static size_t soxr_input(soxr_t p, void const * in, size_t len) { bool separated = !!(p->io_spec.itype & SOXR_SPLIT); unsigned i; if (!p || p->error) return 0; if (!in && len) {p->error = "null input buffer pointer"; return 0;} if (!len) { p->flushing = true; return 0; } if (separated) for (i = 0; i < p->num_channels; ++i) soxr_input_1ch(p, i, ((soxr_cbufs_t)in)[i], len); else { for (i = 0; i < p->num_channels; ++i) p->channel_ptrs[i] = resampler_input(p->resamplers[i], NULL, len); (*p->deinterleave)( (sample_t **)p->channel_ptrs, p->io_spec.itype, &in, len, p->num_channels); } return len; } static size_t soxr_output_1ch(soxr_t p, unsigned i, soxr_buf_t dest, size_t len, bool separated) { sample_t const * src; if (p->flushing) resampler_flush(p->resamplers[i]); resampler_process(p->resamplers[i], len); src = resampler_output(p->resamplers[i], NULL, &len); if (separated) p->clips += (p->interleave)(p->io_spec.otype, &dest, &src, len, 1, (p->io_spec.flags & SOXR_NO_DITHER)? 0 : &p->seed); else p->channel_ptrs[i] = (void /* const */ *)src; return len; } static size_t soxr_output_no_callback(soxr_t p, soxr_buf_t out, size_t len) { unsigned u; size_t done = 0; bool separated = !!(p->io_spec.otype & SOXR_SPLIT); #if defined _OPENMP int i; if (!p->runtime_spec.num_threads && p->num_channels > 1) #pragma omp parallel for for (i = 0; i < (int)p->num_channels; ++i) { size_t done1; done1 = soxr_output_1ch(p, (unsigned)i, ((soxr_bufs_t)out)[i], len, separated); if (!i) done = done1; } else #endif for (u = 0; u < p->num_channels; ++u) done = soxr_output_1ch(p, u, ((soxr_bufs_t)out)[u], len, separated); if (!separated) p->clips += (p->interleave)(p->io_spec.otype, &out, (sample_t const * const *)p->channel_ptrs, done, p->num_channels, (p->io_spec.flags & SOXR_NO_DITHER)? 0 : &p->seed); return done; } size_t soxr_output(soxr_t p, void * out, size_t len0) { size_t odone, odone0 = 0, olen = len0, osize, idone; size_t ilen = min(p->max_ilen, (size_t)ceil((double)olen *p->io_ratio)); void const * in = out; /* Set to !=0, so that caller may leave unset. */ bool was_flushing; if (!p || p->error) return 0; if (!out && len0) {p->error = "null output buffer pointer"; return 0;} do { odone = soxr_output_no_callback(p, out, olen); odone0 += odone; if (odone0 == len0 || !p->input_fn || p->flushing) break; osize = soxr_datatype_size(p->io_spec.otype) * p->num_channels; out = (char *)out + osize * odone; olen -= odone; idone = p->input_fn(p->input_fn_state, &in, ilen); was_flushing = p->flushing; if (!in) p->error = "input function reported failure"; else soxr_input(p, in, idone); } while (odone || idone || (!was_flushing && p->flushing)); return odone0; } static size_t soxr_i_for_o(soxr_t p, size_t olen, size_t ilen) { size_t result; #if 0 if (p->runtime_spec.flags & SOXR_STRICT_BUFFERING) result = rate_i_for_o(p->resamplers[0], olen); else #endif result = (size_t)ceil((double)olen * p->io_ratio); return min(result, ilen); } #if 0 static size_t soxr_o_for_i(soxr_t p, size_t ilen, size_t olen) { size_t result = (size_t)ceil((double)ilen / p->io_ratio); return min(result, olen); } #endif soxr_error_t soxr_process(soxr_t p, void const * in , size_t ilen0, size_t * idone0, void * out, size_t olen , size_t * odone0) { size_t ilen, idone, odone = 0; unsigned u; bool flush_requested = false; if (!p) return "null pointer"; if (!in) flush_requested = true, ilen = ilen0 = 0; else { if ((ptrdiff_t)ilen0 < 0) flush_requested = true, ilen0 = ~ilen0; if (idone0 && (1 || flush_requested)) ilen = soxr_i_for_o(p, olen, ilen0); else ilen = ilen0/*, olen = soxr_o_for_i(p, ilen, olen)*/; } p->flushing |= ilen == ilen0 && flush_requested; if (!out && !in) idone = ilen; else if (p->io_spec.itype & p->io_spec.otype & SOXR_SPLIT) { /* Both i & o */ #if defined _OPENMP int i; if (!p->runtime_spec.num_threads && p->num_channels > 1) #pragma omp parallel for for (i = 0; i < (int)p->num_channels; ++i) { size_t done; if (in) soxr_input_1ch(p, (unsigned)i, ((soxr_cbufs_t)in)[i], ilen); done = soxr_output_1ch(p, (unsigned)i, ((soxr_bufs_t)out)[i], olen, true); if (!i) odone = done; } else #endif for (u = 0; u < p->num_channels; ++u) { if (in) soxr_input_1ch(p, u, ((soxr_cbufs_t)in)[u], ilen); odone = soxr_output_1ch(p, u, ((soxr_bufs_t)out)[u], olen, true); } idone = ilen; } else { idone = ilen? soxr_input (p, in , ilen) : 0; odone = soxr_output(p, out, olen); } if (idone0) *idone0 = idone; if (odone0) *odone0 = odone; return p->error; } soxr_error_t soxr_oneshot( double irate, double orate, unsigned num_channels, void const * in , size_t ilen, size_t * idone, void * out, size_t olen, size_t * odone, soxr_io_spec_t const * io_spec, soxr_quality_spec_t const * q_spec, soxr_runtime_spec_t const * runtime_spec) { soxr_t resampler; soxr_error_t error = q_spec? q_spec->e : 0; if (!error) { soxr_quality_spec_t q_spec1; if (!q_spec) q_spec1 = soxr_quality_spec(SOXR_LQ, 0), q_spec = &q_spec1; resampler = soxr_create(irate, orate, num_channels, &error, io_spec, q_spec, runtime_spec); } if (!error) { error = soxr_process(resampler, in, ~ilen, idone, out, olen, odone); soxr_delete(resampler); } return error; } soxr_error_t soxr_set_error(soxr_t p, soxr_error_t error) { if (!p) return "null pointer"; if (!p->error && p->error != error) return p->error; p->error = error; return 0; }
memory_ops_dm.c
#include <stdio.h> #include <stdlib.h> #include "memory_ops_dm.h" #include "utility.h" #include <time.h> #include <limits.h> #ifdef _OPENMP #include <omp.h> #endif CTYPE* dm_allocate_quantum_state(ITYPE dim) { CTYPE* state = (CTYPE*)malloc((size_t)(sizeof(CTYPE)*dim*dim)); if (!state){ fprintf(stderr,"Out of memory\n"); exit(1); } return state; } void dm_initialize_quantum_state(CTYPE *state, ITYPE dim) { ITYPE index; #ifdef _OPENMP #pragma omp parallel for #endif for(index=0; index < dim*dim ; ++index){ state[index]=0; } state[0] = 1.0; } void dm_release_quantum_state(CTYPE* state){ free(state); } void dm_initialize_with_pure_state(CTYPE *state, const CTYPE *pure_state, ITYPE dim) { ITYPE ind_y; #ifdef _OPENMP #pragma omp parallel for #endif for (ind_y = 0; ind_y < dim; ++ind_y) { ITYPE ind_x; for (ind_x = 0; ind_x < dim; ++ind_x) { state[ind_y*dim+ind_x] = pure_state[ind_y]*conj(pure_state[ind_x]); } } }
ops.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #pragma once #ifndef OPS_H_ #define OPS_H_ #include <op_boilerplate.h> #include <array/DataTypeUtils.h> #include <helpers/shape.h> #include <vector> #include <Environment.h> #include <loops/summarystatsreduce.h> #include <loops/ReduceType.h> #define MIN_V 1e-12 #define MAX_FLOAT 1e37 #define MIN_FLOAT 1e-37 #define MAX_INT 2147483647 #define MIN_CUTFOFF -3.79297773665f #define FLOAT_MIN_NORMAL 1.17549435e-38 #define EPS 1e-5 #define AFFINITY close #define DOUBLE_PI_T T(2.0 * 3.14159265358979323846) #define DOUBLE_PI_X X(2.0 * 3.14159265358979323846) #define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #ifdef __CUDACC__ #define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #else // hacky fix for isnan/being being out of scope //#ifdef IOS //#define isinf(x) 0 // this isn't right. But std::isinf fails //#define isnan(x) 0 //#else //#define isnan std::isnan //#define isinf std::isinf //#endif #define no_op_exec_special_cuda #define no_op_exec_special_accumulation_cuda #define no_op_exec_special_accumulation_same_cuda #define no_op_exec_special_accumulation_long_cuda #define no_op_exec_special_any_cuda #define no_op_exec_special_bool_cuda #define no_op_exec_special_same_cuda #define no_op_exec_special_accumulation_same_cuda #endif #define SELU_ALPHA 1.6732632423543772848170429916717 #define SELU_LAMBDA 1.0507009873554804934193349852946 #ifdef _OPENMP #pragma omp declare reduction(maxTF : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\ initializer (omp_priv=-MAX_FLOAT) #pragma omp declare reduction(minTF : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\ initializer (omp_priv=MAX_FLOAT) #pragma omp declare reduction(maxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\ initializer (omp_priv=0) #pragma omp declare reduction(minT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\ initializer (omp_priv=0) #pragma omp declare reduction(amaxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_max(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) ) #pragma omp declare reduction(aminT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_min(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) ) #pragma omp declare reduction(asumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_abs(omp_in) + nd4j::math::nd4j_abs(omp_out))\ initializer (omp_priv=0) #pragma omp declare reduction(sumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = omp_in + omp_out)\ initializer (omp_priv=0) #pragma omp declare reduction(prodT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = omp_in * omp_out)\ initializer (omp_priv=1) #endif namespace functions { namespace indexreduce { template <typename T> struct IndexValue { T value; Nd4jLong index; _CUDA_HD IndexValue() = default; _CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {} }; } namespace summarystats { template <typename T> class SummaryStatsData; } } namespace simdOps { template <typename X, typename Y, typename Z> class Add { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 + params[0]); } op_def static X startingValue() { return static_cast<X>(0.f); } }; template <typename X, typename Y> class NewAdd { public: op_def static X op(X d1, Y d2, X *params) { return d1 + d2; } }; template <typename X, typename Y, typename Z> class Subtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 - params[0]); } }; template <typename X, typename Y, typename Z> class SquaredSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(d1 - params[0]); return d * d; } }; template <typename X, typename Y, typename Z> class SquaredReverseSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(params[0] - d1); return d * d; } }; template <typename X, typename Y, typename Z> class ReverseSubtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] - d1); } }; template <typename X, typename Y, typename Z> class LogPoissonLossFull { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z) { auto zz = static_cast<Z>(z); return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)); } // op for MetaOps op_def static X op(X z, Y *params) { return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z))); } }; template <typename X, typename Y, typename Z> class LogPoissonLoss { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z) { return static_cast<Z>(z); } // op for MetaOps op_def static Z op(X z, Y *params) { return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0])); } }; template <typename X, typename Y, typename Z> class Multiply { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 * params[0]); } op_def static X startingValue() { return static_cast<X>(1.f); } }; template <typename X, typename Y, typename Z> class Divide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class DivideNoNan { public: op_def static Z op(X d1, Y d2) { if (d2 == (Y)0) return (Z)0; return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if (d2 == (Y)0) return (Z)0; return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if (params[0] == (Y)0) return (Z)0; return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class SafeDivide { public: op_def static Z op(X d1, Y d2) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if(params[0] == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / params[0]); } }; template <typename X, typename Y, typename Z> class FloorDiv { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1)); } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0])); } }; template <typename X, typename Y, typename Z> class TruncateDiv { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 / i2); } }; template <typename X, typename Y, typename Z> class TruncateMod { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 % i2); } }; template<typename X, typename Y, typename Z> class Remainder { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FMod { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FloorMod { public: op_def static Z op(X d1, Y d2) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1, Y d2, Z *params) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseDivide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] / d1); } }; template <typename X, typename Y, typename Z> class CopyPws { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X> class Copy { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X, typename Y, typename Z> class Copy2 { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X, typename Y, typename Z> class Axpy { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 + d1); } op_def static Z op(X d1, Y d2, Z *params) { auto alpha = params[0]; return alpha * static_cast<Z>(d1) + static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class Assign { public: no_op_exec_special_any no_op_exec_special_any_cuda op_def static Z op(X d1, X *params) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class And { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X> class IntOr { public: op_def static X op(X d1, X d2) { return d2 | d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class IntAnd { public: op_def static X op(X d1, X d2) { return d2 & d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class IntXor { public: op_def static X op(X d1, X d2) { return d2 ^ d1; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class ShiftLeft { public: op_def static X op(X d1, X d2) { return d1 << d2; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class ShiftRight { public: op_def static X op(X d1, X d2) { return d1 >> d2; } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class CyclicShiftLeft { public: op_def static X op(X d1, X d2) { return d1 << d2 | d1 >> ((sizeof(X) * 8) - d2); } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X> class CyclicShiftRight { public: op_def static X op(X d1, X d2) { return d1 >> d2 | d1 << ((sizeof(X) * 8) - d2); } op_def static X op(X d1, X d2, X *params) { return op(d1, d2); } }; template <typename X, typename Z> class Or { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Xor { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Z> class Not { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0); } // this transform op should run only on boolean input op_def static Z op(X d1, X *params) { auto b1 = static_cast<bool>(d1); return !b1; } }; template <typename X, typename Y, typename Z> class LogicalNot { public: op_def static Z op(X d1, Y d2) { return !((int) d1 && (int) d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2))); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class LogicalXor { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return (i1 | i2) &~ (i1 & i2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalAnd { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) & static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(Y d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalOr { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) | static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class Mod { public: /* // just a optional note, feel free to remove later op_def static half op(half d1, half d2, half *params) { return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr)); } */ op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) % static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseMod { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d2) % static_cast<int>(d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; /** * Whether 2 elements in an array * are epsilion equal */ template <typename X, typename Z> class Epsilon { public: op_def static Z op(X d1, X d2) { X diff = d1 - d2; X absDiff = nd4j::math::nd4j_abs<X>(diff); if (absDiff <= static_cast<X>(MIN_V)) return static_cast<Z>(1); return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class EqualTo { public: op_def static Z op(X d1, X d2) { return d1 == d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class NotEqualTo { public: op_def static Z op(X d1, X d2) { return d1 != d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 >= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThan { public: op_def static Z op(X d1, X d2) { return d1 > d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThan { public: op_def static Z op(X d1, X d2) { return d1 < d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 <= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X> class Abs { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_abs<X>(d1); } }; template <typename X> class Ceiling { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_ceil<X,X>(d1); } }; template <typename X> class Cosine { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cos<X,X>(d1); } }; template <typename X> class Exp { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X> class HardTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f)); } }; template <typename X> class HardTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 < static_cast<X>(-1)) return static_cast<X>(-1); else if (d1 > static_cast<X>(1)) return static_cast<X>(1); else return d1; } }; template <typename X> class Floor { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_floor<X,X>(d1); } }; template <typename X> class Log { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(d1); } }; template <typename X> class Log1p { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(1 + d1); } }; template <typename X, typename Y, typename Z> class LogX { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ; } }; template <typename X> class StabilizeFP16 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return static_cast<X>(nd4j::DataTypeUtils::min<float16>()); else return d1; } }; template <typename X> class StabilizeX { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return nd4j::DataTypeUtils::min<X>(); else return d1; } }; template <typename X> class SpecialDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1.f) - d1); } }; template <typename X> class Neg { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return -d1; } }; template <typename X> class Erf { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erf<X,X>(d1); } }; template <typename X> class Erfc { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erfc<X,X>(d1); } }; template <typename X> class Reciprocal { public: no_op_exec_special_same no_op_exec_special_same_cuda // op_def static T op(T d1) { // return (T(1.0f) / d1); // } // op for MetaOps op_def static X op(X d1, X *params) { return (static_cast<X>(1) / d1); } }; template <typename X, typename Z> class Sqr { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } }; template <typename X, typename Y, typename Z> class RelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_re<X>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X threshold = params[0]; return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryMinimumAbsoluteRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, X *params) { X d2 = params[0]; X thresholdRelative = params[1]; X thresholdAbsolute = params[2]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1, Y d2, Z *params) { X thresholdRelative = params[0]; X thresholdAbsolute = params[1]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class ReversePow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(params[0], d1); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class Pow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class PowDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1) { return d1; } }; template <typename X> class Round { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_round<X,X>(d1); } }; template <typename X, typename Z> class IsNan { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class Expm1 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1); } }; template <typename X, typename Z> class IsPositive { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return d1 > (X)0.f; } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInf { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInfOrNan{ public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) && old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction != static_cast<X>(0); } }; template <typename X, typename Z> class IsFinite { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput == static_cast<X>(0) || old == static_cast<X>(0) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction != static_cast<X>(0); } }; template <typename X> class ClipByValue { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 > params[1]) return params[1]; if (d1 < params[0]) return params[0]; return d1; } }; template <typename X, typename Y, typename Z> class LstmClip { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X _v = (X) d2; if (d1 > _v) return _v; else if (d1 < -_v) return -_v; else return d1; } }; template <typename X> class Swish { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1); } }; template <typename X> class GELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(static_cast<X>(1.702f) * d1); } }; template <typename X> class PreciseGELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto sp = nd4j::math::nd4j_sqrt<X, X>(static_cast<X>(2) / static_cast<X>(M_PI)); auto xp = d1 + nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(0.044715) * d1, static_cast<X>(3)); return (d1 / static_cast<X>(2)) * (static_cast<X>(1) + nd4j::math::nd4j_tanh<X, X>(sp * xp)); } }; template <typename X> class GELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x17 = static_cast<X>(1.702f) * d1; auto ep = nd4j::math::nd4j_pow<X,X,X>(static_cast<X>(M_E), x17); // (E^(1.702 x) (1. + E^(1.702 x) + 1.702 x))/(1. + E^(1.702 x))^2 return (ep * (static_cast<X>(1.f) + ep + x17)) / nd4j::math::nd4j_pow<X, int, X>((static_cast<X>(1.f) + ep), 2); } }; template <typename X> class PreciseGELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x79 = static_cast<X>(0.797885) * d1; auto x03 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0356774) * d1, 3); auto x39 = static_cast<X>(0.398942) * d1; auto x05 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0535161) * d1, 3); auto scz = nd4j::math::nd4j_sech<X, X>(x79 + x03); // 0.5 + (0.398942 x + 0.0535161 x^3) Sech[0.797885 x + 0.0356774 x^3]^2 + 0.5 Tanh[0.797885 x + 0.0356774 x^3] return static_cast<X>(0.5) + (x39 + x05) * (scz * scz) + static_cast<X>(0.5) * nd4j::math::nd4j_tanh<X, X>(x79 + x03); } }; template <typename X> class SwishDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1); return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f)); } }; template <typename X> class LogSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1)); } }; template <typename X> class LogSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1); return static_cast<X>(1.f) / (ex + static_cast<X>(1.f)); } }; template <typename X> class Sigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoid<X, X>(d1); } }; template <typename X> class SigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoidderivative<X, X>(d1); } }; template <typename X> class HardSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f))); } }; template <typename X> class HardSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f); } }; /** * Scale to be between a min and max */ template <typename X> class SetRange { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto min = params[0]; auto max = params[1]; if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max) return d1; if (min == static_cast<X>(0) && max == static_cast<X>(1)) { auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1)); return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min); } return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min); } }; template <typename X> class Sin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sin<X,X>(d1); } }; template <typename X> class Square { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1; } }; template <typename X, typename Z> class Sqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X, typename Z> class RSqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X> class Rint { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_rint<X,X>(d1); } }; template <typename X> class SoftPlus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::softplus<X, X>(d1); } }; template <typename X> class Sign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0)); } }; template <typename X> class TimesOneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1) - d1); } }; template <typename X> class RationalTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { // keep 2/3 as runtime variable, to match precision auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1; auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) ))); return static_cast<X>(1.7159f) * tanh; } }; template <typename X> class RationalTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1; auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)); auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a); return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv; } }; template <typename X> class Tanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanh<X, X>(d1); } }; template <typename X> class RectifiedTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1)); } }; template <typename X> class RectifiedTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f); } }; template <typename X> class ATanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atanh<X,X>(d1); } }; template <typename X> class TanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanhderivative<X,X>(d1); } }; template <typename X> class Cube { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1 * d1; } }; template <typename X> class CubeDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(3) * d1 * d1; } }; template <typename X> class ACos { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acos<X, X>(d1); } }; template <typename X> class ASinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asinh<X, X>(d1); } }; template <typename X> class ASinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f))); } }; template <typename X> class ACosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acosh<X, X>(d1); } }; template <typename X> class ACoshDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f))); } }; template <typename X> class Ones { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.0f); } }; template <typename X> class SoftSign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsign<X, X>(d1); } }; template <typename X> class SoftSignDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsignderivative<X,X>(d1); } }; template <typename X, typename Z> class MatchConditionBool { public: no_op_exec_special_bool no_op_exec_special_bool_cuda // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false; case 2: // less_than return d1 < compare ? true : false; case 3: // greater_than return d1 > compare ? true : false; case 4: // less_or_equals_than return d1 <= compare ? true : false; case 5: // greater_or_equals_than return d1 >= compare ? true : false; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? true : false; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? true : false; case 10: return (d1 == compare) ? true : false; case 11: return (d1 != compare) ? true : false; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)); case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1); default: printf("Undefined match condition: [%i]\n", mode); } return d1; } }; template <typename X, typename Z> class MatchCondition { public: no_op_exec_special no_op_exec_special_cuda no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return old + opOutput; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return old + opOutput; } // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //printf("value: %f; comp: %f; eps: %f; mode: %i;\n", (float) d1, (float) compare, (float) eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0; case 2: // less_than return d1 < compare ? 1 : 0; case 3: // greater_than return d1 > compare ? 1 : 0; case 4: // less_or_equals_than return d1 <= compare ? 1 : 0; case 5: // greater_or_equals_than return d1 >= compare ? 1 : 0; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? 1 : 0; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? 1 : 0; case 10: return (d1 == compare) ? 1 : 0; case 11: return (d1 != compare) ? 1 : 0; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0; case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0; default: printf("Undefined match condition: [%i]\n", mode); } return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class ELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_elu<X,Z>(d1, static_cast<X>(d2)); } }; template <typename X, typename Y, typename Z> class ELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_eluderivative<X,Z>(d1, static_cast<X>(d2)); } }; template <typename X, typename Y, typename Z> class RELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto xt = static_cast<Z>(d1); auto xf = static_cast<Z>(d2); return xt < xf ? xf : xt; } }; template <typename X, typename Y, typename Z> class SXELogitsSmoother { public: op_def static Z op(X d1, Y d2, Z *params) { return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2; } }; template <typename X, typename Y, typename Z> class RELU6 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params); return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6); } }; template <typename X, typename Y, typename Z> class LeakyRELU { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { auto val = static_cast<Z>(d1); auto alpha = static_cast<Z>(d2); return val < 0.0f ? alpha * val : val; } }; template <typename X> class SELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA)); } }; template <typename X> class SELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X, typename Y, typename Z> class LeakyRELUDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { if (d1 >= static_cast<X>(0)) return static_cast<Z>(1); else return static_cast<Z>(d2); } }; template <typename X> class ASin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asin<X,X>(d1); } }; template <typename X> class Sinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sinh<X,X>(d1); } }; template <typename X> class SinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X, X>(d1); } }; template <typename X> class Cosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X,X>(d1); } }; template <typename X> class Tan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tan<X,X>(d1); } }; template <typename X> class TanDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f)); } }; template <typename X> class ATan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atan<X, X>(d1); } }; template <typename X, typename Y, typename Z> class Atan2 { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_atan2<X, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X> class Identity { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X> class Stabilize { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X k = params[0]; if (d1 * k > static_cast<X>(- MIN_CUTFOFF)) return static_cast<X>(- MIN_CUTFOFF) / k; else if (d1 * k < static_cast<X>(MIN_CUTFOFF)) return static_cast<X>(MIN_CUTFOFF) / k; return d1; } }; template <typename X, typename Y, typename Z> class Step { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0)); } }; template <typename X> class OneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1) - d1; } }; template <typename X> class Sum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ReduceSameBenchmarkOp { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<X>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class ShannonEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto p = d1 * d1; return static_cast<Z>(p) * nd4j::math::nd4j_log<X, Z>(p); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return -reduction; } }; template <typename X, typename Z> class LogEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { //entropy is -sum(p(x) * log(p(x))); log entropy is log of this return nd4j::math::nd4j_log<Z, Z>(-reduction); } }; template <typename X, typename Z> class Entropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x))) } }; template <typename X> class ASum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X, typename Z> class CountNonZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class CountZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return static_cast<Z>(reduction); } }; template <typename X> class Prod { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Any { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ; } }; template <typename X, typename Z> class All { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0); } }; template <typename X, typename Z> class Mean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction / (Z) n; } }; template <typename X, typename Z> class ReduceFloatBenchmarkOp { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<Z>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return (Z) reduction / (Z) n; } }; template <typename X, typename Z> class AMean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_abs<Z>(reduction) / static_cast<Z>(n); } }; template <typename X> class Max { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MAX; op_def static X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class AMaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class AMinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class MaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X, typename Y, typename Z> class MinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X> class AMax { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMAX; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2; } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class AMin { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMIN; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class Min { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MIN; op_def static X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm1 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm2 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } }; template <typename X, typename Z> class SquaredNorm { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class NormFrobenius { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { X v = nd4j::math::nd4j_abs<X>(d1); return static_cast<Z>(v * v); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } }; template <typename X, typename Z> class NormP { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_pow<Z, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]); } }; template <typename X, typename Z> class NormMax { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(old), nd4j::math::nd4j_abs<Z>(opOutput)); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(reduction), nd4j::math::nd4j_abs<Z>(reduction)); } }; template <typename X, typename Z> class Variance { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static X op(X d1, Z *extraParams) { X mean = static_cast<X>(extraParams[0]); X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { // T bias = extraParams[1]; // return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1) return static_cast<Z>(reduction) / static_cast<Z>(n - 1); } }; /** * Standard deviation of a buffer */ template <typename X, typename Z> class StandardDeviation { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z op(X d1, Z *extraParams) { X mean = extraParams[0]; X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams); Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret); return sqrtRet; } }; template <typename X, typename Y> class CosineSimilarity { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(d1 * d1); extraParams[1] += static_cast<Y>(d2 * d2); return static_cast<Y>(d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2)); return static_cast<Y>(d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class JaccardDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { // num / denom return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]); } op_def static Y num(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static Y denom(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(num(d1, d2)); extraParams[1] += static_cast<Y>(denom(d1, d2)); return static_cast<Y>(0.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2)); return static_cast<Y>(0.0f); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class SimpleHammingDistance { public: static const int extraParamsLen = 0; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return static_cast<Y>(reduction / n); } op_def static Y op(X d1, X d2, Y *extraParams) { return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { return op(d1, d2, extraParams); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class CosineDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]))); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1)); extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2)); return (d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2)); return (d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; /** * Dot product between 2 arrays */ template <typename X, typename Y> class Dot { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op //delete[] * extraParamsRef; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return static_cast<Y>(d1 * d2); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; /** * Op to check equality within arrays */ template <typename X, typename Z> class EqualsWithEps { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) { return reduction; } op_def static Z op(X d1, X d2, Z *extraParamsRef) { double eps = nd4j::math::nd4j_abs<double>(extraParamsRef[2]); return static_cast<Z>(!nd4j::math::nd4j_eq<X>(d1, d2, eps)); } #ifdef __CUDACC__ __device__ static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) { return opOutput + old; } op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {} }; template <typename X, typename Y> class EuclideanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return nd4j::math::nd4j_sqrt<Y, Y>(reduction); } op_def static Y op(X d1, X d2, Y *extraParamsRef) { X ret = d1 - d2; return static_cast<Y>(ret * ret); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; template <typename X, typename Y> class ManhattanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return nd4j::math::nd4j_abs<X>(d1 - d2); } op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return old + opOutput; } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif #ifndef __clang__ #pragma omp declare simd uniform(extraParamsRef) #endif op_def static Y merge(X old, X opOutput, X *extraParamsRef) { return update(old, opOutput, extraParamsRef); } }; template <typename X, typename Z> class IndexAbsoluteMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return nd4j::math::nd4j_abs<X>(val); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value > old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return 0; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class FirstIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); //printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index > opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index > f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X, typename Z> class LastIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index < opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index < f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X, typename Z> class IndexMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value > old.value) { return opOutput; } #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value > f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class IndexAbsoluteMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class IndexMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::infOrMax<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value < f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsVariance { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { Z ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return static_cast<Z>(val.variance()); return ret; } return static_cast<Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsStandardDeviation { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { auto ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); else return nd4j::math::nd4j_sqrt<double, Z>(ret); } return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X> class DropOut { public: no_op_exec_special_same no_op_exec_special_same_cuda inline _CUDA_D static X op(X d1, X *params) { X prob = params[0]; #ifdef __CUDACC__ X length = params[1]; X tid = blockIdx.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= prob ? static_cast<X>(0.0f) : d1; } }; template <typename X, typename Y, typename Z> class DropOutInverted { public: no_op_exec_special no_op_exec_special_cuda #ifdef __CUDACC__ __device__ #endif inline static Z op(X d1, Y d2, Z *params) { Y prob = d2; #ifdef __CUDACC__ X length = params[1]; X tid = blockIdx.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob)); } }; template <typename X, typename Y, typename Z> class ReplaceNans { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ; } }; // this op is used for conditional pairwise transforms only template <typename X, typename Y, typename Z> class CompareAndReplace{ public: // op definition for PairWise Transform op_def static Z op(X d1, Y d2, Z *params) { auto zd1 = static_cast<Z>(d1); auto zd2 = static_cast<Z>(d2); auto compare = params[0]; auto eps = params[2]; int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps) return zd2; else return zd1; else if (mode == 1) // not equals eps if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps) return zd2; else return zd1; else if (mode == 2) // less_than eps if (zd1 < compare) return zd2; else return zd1; else if (mode ==3) // greater_than if (zd1 > compare) return zd2; else return zd1; else if (mode == 4) // less_or_equals_than if (zd1 <= compare) return zd2; else return zd1; else if (mode == 5) // greater_or_equals_than if (zd1 >= compare) return zd2; else return zd1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(zd1) < compare) return zd2; else return zd1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(zd1) > compare) return zd2; else return zd1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(zd1)) return zd2; else return zd1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(zd1)) return zd2; else return zd1; else if (mode == 10) if (zd1 == compare) return zd2; else return zd1; else if (mode == 11) if (zd1 != compare) return zd2; else return zd1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) >= compare) return zd2; else return zd1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) <= compare) return zd2; else return zd1; else printf("Undefined boolean operation: [%i]\n", mode); return zd1; } }; template <typename X, typename Y, typename Z> class CompareAndSet { public: // op definition for PairWise Transform op_def static Z op(X dX, Y dY, Z *params) { auto d1 = static_cast<Z>(dX); auto d2 = static_cast<Z>(dY); auto compare = params[0]; auto eps = params[2]; auto mode = static_cast<int>(params[3]); if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps) return d2; else return d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps) return d2; else return d1; else if (mode == 2) // less_than if (d2 < compare) return d2; else return d1; else if (mode ==3) // greater_than if (d2 > compare) return d2; else return d1; else if (mode == 4) // less_or_equals_than if (d2 <= compare) return d2; else return d1; else if (mode == 5) // greater_or_equals_than if (d2 >= compare) return d2; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(d2) < compare) return d2; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(d2) > compare) return d2; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d2)) return d2; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d2)) return d2; else return d1; else if (mode == 10) if (d2 == compare) return d2; else return d1; else if (mode == 11) if (d2 != compare) return d2; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) >= compare) return d2; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) <= compare) return d2; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; template <typename X> class CompareAndSetTransform { public: no_op_exec_special_same no_op_exec_special_same_cuda // op definition for Transform op_def static X op(X d1, X *params) { auto compare = params[0]; auto set = params[1]; auto eps = params[2]; // with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1; else if (mode == 2) // less_than if (d1 < compare) return set; else return d1; else if (mode ==3) // greater_than if (d1 > compare) return set; else return d1; else if (mode == 4) // less_or_equals_than if (d1 <= compare) return set; else return d1; else if (mode == 5) // greater_or_equals_than if (d1 >= compare) return set; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<X>(d1) < compare) return set; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<X>(d1) > compare) return set; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d1)) return set; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d1)) return set; else return d1; else if (mode == 10) if (d1 == compare) return set; else return d1; else if (mode == 11) if (d1 != compare) return set; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) >= compare) return set; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) <= compare) return set; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; } #endif
GB_unop__ainv_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__ainv_fp64_fp64) // op(A') function: GB (_unop_tran__ainv_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = -aij #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = -z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = -z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = -z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_fp64_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
comm.h
/* * 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. */ /** * Copyright (c) 2015 by Contributors */ #ifndef MXNET_KVSTORE_COMM_H_ #define MXNET_KVSTORE_COMM_H_ #include <dmlc/omp.h> #include <string> #include <algorithm> #include <utility> #include <limits> #include <vector> #include <tuple> #include <thread> #include "mxnet/ndarray.h" #include "gradient_compression.h" #include "../ndarray/ndarray_function.h" #include "../operator/tensor/sparse_retain-inl.h" #include "./kvstore_utils.h" namespace mxnet { namespace kvstore { /** * \brief multiple device commmunication */ class Comm { public: Comm() { pinned_ctx_ = Context::CPUPinned(0); } virtual ~Comm() { } /** * \brief init key with the data shape and storage shape */ virtual void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) = 0; /** * \brief returns src[0] + .. + src[src.size()-1] */ virtual const NDArray& Reduce( int key, const std::vector<NDArray>& src, int priority) = 0; /** * \brief copy from src to dst[i] for every i */ virtual void Broadcast( int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) = 0; /** * \brief broadcast src to dst[i] with target row_ids for every i * \param dst a list of destination row_sparse NDArray and its target row_ids to broadcast, where the row_ids are expected to be unique and sorted * \param use_copy if set to true, directly copy src to dst[i] without looking up the provided row_ids */ virtual void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const bool use_copy, const int priority) = 0; /** * \brief return a pinned contex */ Context pinned_ctx() const { return pinned_ctx_; } /** * \brief Sets gradient compression parameters to be able to * perform reduce with compressed gradients */ void SetGradientCompression(std::shared_ptr<GradientCompression> gc) { gc_ = gc; } protected: Context pinned_ctx_; std::shared_ptr<GradientCompression> gc_; }; /** * \brief an implemention of Comm that first copy data to CPU memeory, and then * reduce there */ class CommCPU : public Comm { public: CommCPU() { nthread_reduction_ = dmlc::GetEnv("MXNET_KVSTORE_REDUCTION_NTHREADS", 4); bigarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_BIGARRAY_BOUND", 1000 * 1000); // TODO(junwu) delete the following data member, now for benchmark only is_serial_push_ = dmlc::GetEnv("MXNET_KVSTORE_SERIAL_PUSH", 0); } virtual ~CommCPU() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int type = mshadow::kFloat32) override { if (stype == kDefaultStorage) { merge_buf_[key].merged = NDArray(shape, pinned_ctx_, false, type); } else { merge_buf_[key].merged = NDArray(stype, shape, pinned_ctx_, true, type); } } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { auto& buf = merge_buf_[key]; // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { if (src[0].storage_type() == kDefaultStorage) { return src[0]; } else { // if sparse and only one GPU, always update weight on CPU CopyFromTo(src[0], &buf.merged, priority); return buf.merged; } } if (buf.merged.storage_type() == kDefaultStorage) { std::vector<Engine::VarHandle> const_vars(src.size() - 1); std::vector<NDArray> reduce(src.size()); CopyFromTo(src[0], &buf.merged, priority); reduce[0] = buf.merged; if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()-1); for (size_t j = 0; j < src.size() - 1; ++j) { // allocate NDArray based on storage type buf.copy_buf[j] = NDArray( src[0].shape(), pinned_ctx_, false, src[0].dtype()); } } for (size_t i = 1; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i-1]), priority); reduce[i] = buf.copy_buf[i-1]; const_vars[i-1] = reduce[i].var(); } Engine::Get()->PushAsync( [reduce, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { ReduceSumCPU(reduce); on_complete(); }, Context::CPU(), const_vars, {reduce[0].var()}, FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce")); } else { // buf.merged is a sparse ndarray. std::vector<Engine::VarHandle> const_vars(src.size()); std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray( src[0].storage_type(), src[0].shape(), pinned_ctx_, true, src[0].dtype()); } } for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; const_vars[i] = reduce[i].var(); } NDArray result = buf.merged; Resource rsc = ResourceManager::Get()->Request(result.ctx(), ResourceRequest(ResourceRequest::kTempSpace)); Engine::Get()->PushAsync( [reduce, result, rsc, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { NDArray out = result; is_serial_push_? ReduceSumCPUExSerial(reduce, &out) : mxnet::ndarray::ElementwiseSum(rctx.get_stream<cpu>(), rsc, reduce, &out); on_complete(); }, Context::CPU(), const_vars, {result.var(), rsc.var}, FnProperty::kCPUPrioritized, priority, PROFILER_MESSAGE("KVStoreReduce")); } return buf.merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { int mask = src.ctx().dev_mask(); if (mask == Context::kCPU) { for (auto d : dst) CopyFromTo(src, d, priority); } else { // first copy data to cpu, then broadcast auto& buf = merge_buf_[key]; CopyFromTo(src, &buf.merged, priority); for (auto d : dst) CopyFromTo(buf.merged, d, priority); } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const bool use_copy, const int priority) override { using namespace mshadow; CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; CHECK_EQ(src.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with src on gpu context not supported"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; if (use_copy) { CopyFromTo(src, out, priority); } else { CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; CHECK_EQ(row_id.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with row_indices on gpu context not supported"; // retain according to unique indices const bool use_sparse_retain = (src.shape()[0] != src.storage_shape()[0]) || (row_id.dtype() != out->aux_type(rowsparse::kIdx)) || (out->ctx().dev_mask() != Context::kGPU); if (use_sparse_retain) { // use sparse_retain op const bool is_to_gpu = out->ctx().dev_mask() == Context::kGPU; NDArray out_cpu = is_to_gpu? NDArray(kRowSparseStorage, src.shape(), src.ctx(), true, src.dtype(), src.aux_types()) : *out; Engine::Get()->PushAsync( [=](RunContext rctx, Engine::CallbackOnComplete on_complete) { const TBlob& indices = row_id.data(); NDArray temp = out_cpu; // get rid of const qualifier op::SparseRetainOpForwardRspImpl<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); on_complete(); }, Context::CPU(), {src.var(), row_id.var()}, {out_cpu.var()}, FnProperty::kNormal, priority, PROFILER_MESSAGE("KVStoreSparseRetain")); if (is_to_gpu) { CopyFromTo(out_cpu, out, priority); } } else { // direct copy rows Engine::Get()->PushAsync( [=](RunContext rctx, Engine::CallbackOnComplete on_complete) { CopyRetainedRowsToGPU(rctx.get_stream<cpu>(), rctx.get_stream<gpu>(), src, row_id, out); // wait for GPU operations to complete rctx.get_stream<gpu>()->Wait(); on_complete(); }, out->ctx(), {src.var(), row_id.var()}, {out->var()}, FnProperty::kCopyToGPU, priority, PROFILER_MESSAGE("KVStoreCopyRetainedRowsToGPU")); } } } } private: /*! * \brief When src is a rsp with full rows, * simply copy retained rows directly from cpu to gpu * without invoking sparse_retain op. */ void CopyRetainedRowsToGPU(mshadow::Stream<cpu>* cpu_stream, mshadow::Stream<gpu>* gpu_stream, const NDArray& src, const NDArray& indices, NDArray* dst) { #if MXNET_USE_CUDA == 1 CHECK_EQ(src.storage_type(), kRowSparseStorage) << "CopyRetainedRowsToGPU expects row-sparse src NDArray"; CHECK_EQ(src.ctx().dev_mask(), Context::kCPU) << "CopyRetainedRowsToGPU with src on gpu context not supported"; CHECK_EQ(src.storage_shape()[0], src.shape()[0]) << "CopyRetainedRowsToGPU only supports src rsp with full rows"; CHECK_EQ(indices.storage_type(), kDefaultStorage); CHECK_EQ(indices.ctx().dev_mask(), Context::kCPU); CHECK_EQ(dst->storage_type(), kRowSparseStorage); CHECK_EQ(dst->ctx().dev_mask(), Context::kGPU); CHECK_EQ(indices.dtype(), dst->aux_type(rowsparse::kIdx)) << "CopyRetainedRowsToGPU only supports same data type for idx array and dst aux_data(0)"; if (!src.storage_initialized() || indices.data().Size() == 0U) { op::FillZerosRspImpl(gpu_stream, *dst); return; } using namespace mshadow; const TBlob& src_data = src.data(); const TBlob& idx_data = indices.data(); const size_t row_length = src.shape().ProdShape(1, src.shape().ndim()); const size_t num_rows_retained = idx_data.Size(); dst->CheckAndAlloc({Shape1(num_rows_retained)}); TBlob dst_data = dst->data(); TBlob dst_idx_data = dst->aux_data(rowsparse::kIdx); MSHADOW_TYPE_SWITCH(src.dtype(), DType, { MSHADOW_IDX_TYPE_SWITCH(indices.dtype(), IType, { // copy idx array Tensor<gpu, 1, IType> dst_idx_tensor = dst_idx_data.FlatTo1D<gpu, IType>(gpu_stream); const Tensor<cpu, 1, IType> idx_tensor = idx_data.FlatTo1D<cpu, IType>(cpu_stream); Copy(dst_idx_tensor, idx_tensor, gpu_stream); // copy src data const Tensor<cpu, 2, DType> src_data_tensor = src_data.get_with_shape<cpu, 2, DType>( Shape2(src_data.shape_[0], row_length), cpu_stream); Tensor<gpu, 2, DType> dst_data_tensor = dst_data.get_with_shape<gpu, 2, DType>( Shape2(dst_data.shape_[0], row_length), gpu_stream); for (size_t i = 0; i < num_rows_retained; ++i) { Copy(dst_data_tensor[i], src_data_tensor[idx_tensor[i]], gpu_stream); } }) }) #else LOG(FATAL) << "GPU not enabled"; #endif } // reduce sum into val[0] inline void ReduceSumCPU(const std::vector<NDArray> &in_data) { MSHADOW_TYPE_SWITCH(in_data[0].dtype(), DType, { std::vector<DType*> dptr(in_data.size()); for (size_t i = 0; i < in_data.size(); ++i) { TBlob data = in_data[i].data(); CHECK(data.CheckContiguous()); dptr[i] = data.FlatTo2D<cpu, DType>().dptr_; } size_t total = in_data[0].shape().Size(); ReduceSumCPUImpl(dptr, total); }); } // serial implementation of reduce sum for row sparse NDArray. inline void ReduceSumCPUExSerial(const std::vector<NDArray> &in, NDArray *out) { using namespace rowsparse; using namespace mshadow; auto stype = out->storage_type(); CHECK_EQ(stype, kRowSparseStorage) << "Unexpected storage type " << stype; size_t total_num_rows = 0; size_t num_in = in.size(); // skip the ones with empty indices and values std::vector<bool> skip(num_in, false); // the values tensor of the inputs MSHADOW_TYPE_SWITCH(out->dtype(), DType, { MSHADOW_IDX_TYPE_SWITCH(out->aux_type(kIdx), IType, { std::vector<Tensor<cpu, 2, DType>> in_vals(num_in); std::vector<Tensor<cpu, 1, IType>> in_indices(num_in); // offset to the values tensor of all inputs std::vector<size_t> offsets(num_in, 0); std::vector<size_t> num_rows(num_in, 0); for (size_t i = 0; i < num_in; i++) { if (!in[i].storage_initialized()) { skip[i] = true; continue; } auto size = in[i].aux_shape(kIdx).Size(); num_rows[i] = size; total_num_rows += size; in_vals[i] = in[i].data().FlatTo2D<cpu, DType>(); in_indices[i] = in[i].aux_data(kIdx).FlatTo1D<cpu, IType>(); } std::vector<IType> indices; indices.reserve(total_num_rows); // gather indices from all inputs for (size_t i = 0; i < num_in; i++) { for (size_t j = 0; j < num_rows[i]; j++) { indices.emplace_back(in_indices[i][j]); } } CHECK_EQ(indices.size(), total_num_rows); // dedup indices std::sort(indices.begin(), indices.end()); indices.resize(std::unique(indices.begin(), indices.end()) - indices.begin()); // the one left are unique non-zero rows size_t nnr = indices.size(); // allocate memory for output out->CheckAndAlloc({Shape1(nnr)}); auto idx_data = out->aux_data(kIdx).FlatTo1D<cpu, IType>(); auto val_data = out->data().FlatTo2D<cpu, DType>(); for (size_t i = 0; i < nnr; i++) { // copy indices back idx_data[i] = indices[i]; bool zeros = true; for (size_t j = 0; j < num_in; j++) { if (skip[j]) continue; size_t offset = offsets[j]; if (offset < num_rows[j]) { if (indices[i] == in_indices[j][offset]) { if (zeros) { Copy(val_data[i], in_vals[j][offset], nullptr); zeros = false; } else { val_data[i] += in_vals[j][offset]; } offsets[j] += 1; } } } } }); }); } template<typename DType> inline static void ReduceSumCPU( const std::vector<DType*> &dptr, size_t offset, index_t size) { using namespace mshadow; // NOLINT(*) Tensor<cpu, 1, DType> in_0(dptr[0] + offset, Shape1(size)); for (size_t i = 1; i < dptr.size(); i+=4) { switch (dptr.size() - i) { case 1: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); in_0 += in_1; break; } case 2: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); in_0 += in_1 + in_2; break; } case 3: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3; break; } default: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_4(dptr[i+3] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3 + in_4; break; } } } } template<typename DType> inline void ReduceSumCPUImpl(std::vector<DType*> dptr, size_t total) { const size_t step = std::min(bigarray_bound_, static_cast<size_t>(4 << 10)); long ntask = (total + step - 1) / step; // NOLINT(*) if (total < bigarray_bound_ || nthread_reduction_ <= 1) { ReduceSumCPU(dptr, 0, total); } else { #pragma omp parallel for schedule(static) num_threads(nthread_reduction_) for (long j = 0; j < ntask; ++j) { // NOLINT(*) size_t k = static_cast<size_t>(j); size_t begin = std::min(k * step, total); size_t end = std::min((k + 1) * step, total); if (j == ntask - 1) CHECK_EQ(end, total); ReduceSumCPU(dptr, begin, static_cast<index_t>(end - begin)); } } } /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the merged value NDArray merged; /// \brief the cpu buffer for gpu data std::vector<NDArray> copy_buf; }; std::unordered_map<int, BufferEntry> merge_buf_; size_t bigarray_bound_; int nthread_reduction_; bool is_serial_push_; }; /** * \brief an implementation of Comm that performs reduction on device * directly. * * It is faster if the total device-to-device bandwidths is larger than * device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device * memory. */ class CommDevice : public Comm { public: CommDevice() { inited_ = false; } virtual ~CommDevice() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) override { sorted_key_attrs_.emplace_back(key, shape, dtype, stype); } void InitBuffersAndComm(const std::vector<NDArray>& src) { if (!inited_) { std::vector<Context> devs; for (const auto& a : src) { devs.push_back(a.ctx()); } InitMergeBuffer(devs); if (dmlc::GetEnv("MXNET_ENABLE_GPU_P2P", 1)) { EnableP2P(devs); } } } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { // when this reduce is called from kvstore_dist, gc is not set // we don't do compression twice in dist_sync_device if ((gc_ != nullptr) && (gc_->get_type() != CompressionType::kNone)) { return ReduceCompressed(key, src, priority); } // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { return src[0]; } InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); const NDArrayStorageType stype = buf.merged.storage_type(); if (stype == kDefaultStorage) { CopyFromTo(src[0], &(buf.merged), priority); reduce[0] = buf.merged; if (buf.copy_buf.empty()) { // TODO(mli) this results in large device memory usage for huge ndarray, // such as the largest fullc in VGG. consider to do segment reduce with // NDArray.Slice or gpu direct memory access. for the latter, we need to // remove some ctx check, and also it reduces 20% perf buf.copy_buf.resize(src.size()-1); for (size_t i = 0; i < src.size()-1; ++i) { buf.copy_buf[i] = NDArray( buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype()); } } for (size_t i = 0; i < src.size()-1; ++i) { CopyFromTo(src[i+1], &(buf.copy_buf[i]), priority); reduce[i+1] = buf.copy_buf[i]; } } else { if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray( buf.merged.storage_type(), buf.merged.shape(), buf.merged.ctx(), true, buf.merged.dtype()); } } for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } } ElementwiseSum(reduce, &buf.merged, priority); return buf.merged; } const NDArray& ReduceCompressed(int key, const std::vector<NDArray>& src, int priority) { InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { // one buf for each context buf.copy_buf.resize(src.size()); buf.compressed_recv_buf.resize(src.size()); buf.compressed_send_buf.resize(src.size()); buf.residual.resize(src.size()); for (size_t i = 0; i < src.size(); ++i) { buf.copy_buf[i] = NDArray(buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype()); buf.residual[i] = NDArray(buf.merged.shape(), src[i].ctx(), false, buf.merged.dtype()); buf.residual[i] = 0; int64_t small_size = gc_->GetCompressedSize(buf.merged.shape().Size()); buf.compressed_recv_buf[i] = NDArray(TShape{small_size}, buf.merged.ctx(), false, buf.merged.dtype()); buf.compressed_send_buf[i] = NDArray(TShape{small_size}, src[i].ctx(), false, buf.merged.dtype()); } } for (size_t i = 0; i < src.size(); ++i) { // compress before copy // this is done even if the data is on same context as copy_buf because // we don't want the training to be biased towards data on this GPU gc_->Quantize(src[i], &(buf.compressed_send_buf[i]), &(buf.residual[i]), priority); if (buf.compressed_send_buf[i].ctx() != buf.compressed_recv_buf[i].ctx()) { CopyFromTo(buf.compressed_send_buf[i], &(buf.compressed_recv_buf[i]), priority); } else { // avoid memory copy when they are on same context buf.compressed_recv_buf[i] = buf.compressed_send_buf[i]; } gc_->Dequantize(buf.compressed_recv_buf[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } ElementwiseSum(reduce, &buf.merged); return buf.merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { if (!inited_) { // copy to a random device first int dev_id = key % dst.size(); CopyFromTo(src, dst[dev_id], priority); for (size_t i = 0; i < dst.size(); ++i) { if (i != static_cast<size_t>(dev_id)) { CopyFromTo(*dst[dev_id], dst[i], priority); } } } else { auto& buf = merge_buf_[key]; CopyFromTo(src, &buf.merged, priority); for (auto d : dst) { CopyFromTo(buf.merged, d, priority); } } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const bool use_copy, const int priority) override { CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; if (use_copy) { CopyFromTo(src, out, priority); } else { CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; const bool is_diff_ctx = out->ctx() != src.ctx(); NDArray out_gpu = is_diff_ctx? NDArray(kRowSparseStorage, out->shape(), src.ctx(), true, out->dtype(), out->aux_types()) : *out; CHECK_EQ(row_id.ctx(), src.ctx()) << "row_id and src are expected to be on the same context"; Engine::Get()->PushAsync([=](RunContext rctx, Engine::CallbackOnComplete on_complete) { NDArray temp = out_gpu; const TBlob& indices = row_id.data(); switch (temp.ctx().dev_mask()) { case cpu::kDevMask: { mxnet::common::SparseRetainOpForwardRspWrapper<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); break; } #if MXNET_USE_CUDA case gpu::kDevMask: { mxnet::common::SparseRetainOpForwardRspWrapper<gpu>(rctx.get_stream<gpu>(), src, indices, kWriteTo, &temp); // wait for GPU operations to complete rctx.get_stream<gpu>()->Wait(); break; } #endif default: LOG(FATAL) << MXNET_GPU_NOT_ENABLED_ERROR; } on_complete(); }, out_gpu.ctx(), {src.var(), row_id.var()}, {out_gpu.var()}, FnProperty::kNormal, priority, PROFILER_MESSAGE("KVStoreSparseRetain")); if (is_diff_ctx) { CopyFromTo(out_gpu, out, priority); } } } } private: void EnableP2P(const std::vector<Context>& devs) { #if MXNET_USE_CUDA std::vector<int> gpus; for (const auto& d : devs) { if (d.dev_mask() == gpu::kDevMask) { gpus.push_back(d.dev_id); } } int n = static_cast<int>(gpus.size()); int enabled = 0; std::vector<int> p2p(n*n); for (int i = 0; i < n; ++i) { cudaSetDevice(gpus[i]); for (int j = 0; j < n; j++) { int access; cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]); if (access) { cudaError_t e = cudaDeviceEnablePeerAccess(gpus[j], 0); if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled) { ++enabled; p2p[i*n+j] = 1; } } } } if (enabled != n*(n-1)) { // print warning info if not fully enabled LOG(WARNING) << "only " << enabled << " out of " << n*(n-1) << " GPU pairs are enabled direct access. " << "It may affect the performance. " << "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off"; std::string access(n, '.'); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { access[j] = p2p[i*n+j] ? 'v' : '.'; } LOG(WARNING) << access; } } #endif } using KeyAttrs = std::tuple<int, TShape, int, NDArrayStorageType>; // try to allocate buff on device evenly void InitMergeBuffer(const std::vector<Context>& devs) { std::sort(sorted_key_attrs_.begin(), sorted_key_attrs_.end(), []( const KeyAttrs& a, const KeyAttrs& b) { return std::get<1>(a).Size() > std::get<1>(b).Size(); }); std::unordered_map<int, std::pair<Context, size_t>> ctx_info; for (auto d : devs) { ctx_info[d.dev_id] = std::make_pair(d, 0); } for (size_t i = 0; i < sorted_key_attrs_.size(); ++i) { const int key = std::get<0>(sorted_key_attrs_[i]); const TShape& shape = std::get<1>(sorted_key_attrs_[i]); const int type = std::get<2>(sorted_key_attrs_[i]); const NDArrayStorageType stype = std::get<3>(sorted_key_attrs_[i]); auto& buf = merge_buf_[key]; Context ctx; size_t min_size = std::numeric_limits<size_t>::max(); for (auto it = ctx_info.begin(); it != ctx_info.end(); ++it) { size_t size = it->second.second; if (size <= min_size) { ctx = it->second.first; min_size = size; } } if (stype == kDefaultStorage) { buf.merged = NDArray(shape, ctx, false, type); } else { buf.merged = NDArray(stype, shape, ctx, true, type); } ctx_info[ctx.dev_id].second += shape.Size(); } inited_ = true; } std::vector<KeyAttrs> sorted_key_attrs_; /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the merged value NDArray merged; /// \brief the gpu buffer std::vector<NDArray> copy_buf; /// \brief the residual buffer for gradient compression std::vector<NDArray> residual; /// \brief the small buffer for compressed data in sender std::vector<NDArray> compressed_send_buf; /// \brief the small buffer for compressed data in receiver std::vector<NDArray> compressed_recv_buf; }; std::unordered_map<int, BufferEntry> merge_buf_; bool inited_; }; } // namespace kvstore } // namespace mxnet #endif // MXNET_KVSTORE_COMM_H_
convolutiondepthwise_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void convdw3x3s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g=0; g<group; g++) { Mat out = top_blob.channel(g); const float bias0 = bias ? bias[g] : 0.f; const float* kernel0 = kernel + g*9; float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(g); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __AVX__ || __SSE__ __m128 k0_data = _mm_loadu_ps(k0); __m128 k1_data = _mm_loadu_ps(k1); __m128 k2_data = _mm_loadu_ps(k2); int i = 0; for (; i + 1 < outh; i += 2) { int remain = outw; for (; remain > 0; remain--) { __m128 r0_data = _mm_loadu_ps(r0); __m128 r1_data = _mm_loadu_ps(r1); __m128 r2_data = _mm_loadu_ps(r2); __m128 r3_data = _mm_loadu_ps(r3); __m128 sum = _mm_setzero_ps(); __m128 sum2 = _mm_setzero_ps(); float sum_sum = 0, sum_sum2 = 0; sum = _mm_add_ps(_mm_mul_ps(r0_data, k0_data), sum); sum = _mm_add_ps(_mm_mul_ps(r1_data, k1_data), sum); sum = _mm_add_ps(_mm_mul_ps(r2_data, k2_data), sum); sum_sum += sum.m128_f32[0] + sum.m128_f32[1] + sum.m128_f32[2] + bias0; sum2 = _mm_add_ps(_mm_mul_ps(r1_data, k0_data), sum2); sum2 = _mm_add_ps(_mm_mul_ps(r2_data, k1_data), sum2); sum2 = _mm_add_ps(_mm_mul_ps(r3_data, k2_data), sum2); sum_sum2 += sum2.m128_f32[0] + sum2.m128_f32[1] + sum2.m128_f32[2] + bias0; *outptr = sum_sum; *outptr2 = sum_sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { __m128 r0_data = _mm_loadu_ps(r0); __m128 r1_data = _mm_loadu_ps(r1); __m128 r2_data = _mm_loadu_ps(r2); __m128 sum = _mm_setzero_ps(); float sum_sum = 0; sum = _mm_add_ps(_mm_mul_ps(r0_data, k0_data), sum); sum = _mm_add_ps(_mm_mul_ps(r1_data, k1_data), sum); sum = _mm_add_ps(_mm_mul_ps(r2_data, k2_data), sum); sum_sum += sum.m128_f32[0] + sum.m128_f32[1] + sum.m128_f32[2] + bias0; *outptr = sum_sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } #else int i = 0; for (; i+1 < outh; i+=2) { int remain = outw; for (; remain>0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; float sum2 = bias0; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr = sum; *outptr2 = sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } #endif } } static void convdw3x3s2_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g=0; g<group; g++) { Mat out = top_blob.channel(g); const float bias0 = bias ? bias[g] : 0.f; const float* kernel0 = kernel + g*9; float* outptr = out; const float* img0 = bottom_blob.channel(g); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __AVX__ || __SSE__ __m128 k0_data = _mm_loadu_ps(k0); __m128 k1_data = _mm_loadu_ps(k1); __m128 k2_data = _mm_loadu_ps(k2); int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { __m128 r0_data = _mm_loadu_ps(r0); __m128 r1_data = _mm_loadu_ps(r1); __m128 r2_data = _mm_loadu_ps(r2); __m128 sum = _mm_setzero_ps(); float sum_sum = 0; sum = _mm_add_ps(_mm_mul_ps(r0_data, k0_data), sum); sum = _mm_add_ps(_mm_mul_ps(r1_data, k1_data), sum); sum = _mm_add_ps(_mm_mul_ps(r2_data, k2_data), sum); sum_sum += sum.m128_f32[0] + sum.m128_f32[1] + sum.m128_f32[2] + bias0; *outptr = sum_sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } #else int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain>0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } #endif } }
GB_unop__trunc_fc64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__trunc_fc64_fc64) // op(A') function: GB (_unop_tran__trunc_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_ctrunc (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_ctrunc (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_ctrunc (z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TRUNC || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__trunc_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_ctrunc (z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_ctrunc (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__trunc_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bicubic_interpolation.h
// This program is free software: you can use, modify and/or redistribute it // under the terms of the simplified BSD License. You should have received a // copy of this license along this program. If not, see // <http://www.opensource.org/licenses/bsd-license.html>. // // Copyright (C) 2012, Javier Sánchez Pérez <[email protected]> // Copyright (C) 2014, Nelson Monzón López <[email protected]> // All rights reserved. #ifndef BICUBIC_INTERPOLATION_H #define BICUBIC_INTERPOLATION_H #define BOUNDARY_CONDITION 0 //0 Neumann //1 Periodic //2 Symmetric /** * * Neumann boundary condition test * **/ int neumann_bc (int x, int nx, bool & out) { if (x < 0) { x = 0; out = true; } else if (x >= nx) { x = nx - 1; out = true; } return x; } /** * * Periodic boundary condition test * **/ int periodic_bc (int x, int nx, bool & out) { if (x < 0) { const int n = 1 - (int) (x / (nx + 1)); const int ixx = x + n * nx; x = ixx % nx; out = true; } else if (x >= nx) { x = x % nx; out = true; } return x; } /** * * Symmetric boundary condition test * **/ int symmetric_bc (int x, int nx, bool & out) { if (x < 0) { const int border = nx - 1; const int xx = -x; const int n = (int) (xx / border) % 2; if (n) x = border - (xx % border); else x = xx % border; out = true; } else if (x >= nx) { const int border = nx - 1; const int n = (int) (x / border) % 2; if (n) x = border - (x % border); else x = x % border; out = true; } return x; } /** * * Bicubic interpolation in one dimension * **/ double cubic_interpolation (double v[4], //interpolation points double x //point to be interpolated ) { return v[1] + 0.5 * x * (v[2] - v[0] + x * (2.0 * v[0] - 5.0 * v[1] + 4.0 * v[2] - v[3] + x * (3.0 * (v[1] - v[2]) + v[3] - v[0]))); } /** * * Bicubic interpolation in two dimension * **/ double bicubic_interpolation (double p[4][4], //array containing the interpolation points double x, //x position to be interpolated double y //y position to be interpolated ) { double v[4]; v[0] = cubic_interpolation (p[0], y); v[1] = cubic_interpolation (p[1], y); v[2] = cubic_interpolation (p[2], y); v[3] = cubic_interpolation (p[3], y); return cubic_interpolation (v, x); } /** * * Compute the bicubic interpolation of a point in an image. * Detects if the point goes outside the image domain * **/ float bicubic_interpolation (const float *input, //image to be interpolated const float uu, //x component of the vector field const float vv, //y component of the vector field const int nx, //width of the image const int ny, //height of the image const int nz, //number of channels of the image const int k, //actual channel const bool border_out = false //if true, put zeros outside the region ) { const int sx = (uu < 0) ? -1 : 1; const int sy = (vv < 0) ? -1 : 1; int x, y, mx, my, dx, dy, ddx, ddy; bool out = false; switch (BOUNDARY_CONDITION) { case 0: x = neumann_bc ((int) uu, nx, out); y = neumann_bc ((int) vv, ny, out); mx = neumann_bc ((int) uu - sx, nx, out); my = neumann_bc ((int) vv - sx, ny, out); dx = neumann_bc ((int) uu + sx, nx, out); dy = neumann_bc ((int) vv + sy, ny, out); ddx = neumann_bc ((int) uu + 2 * sx, nx, out); ddy = neumann_bc ((int) vv + 2 * sy, ny, out); break; case 1: x = periodic_bc ((int) uu, nx, out); y = periodic_bc ((int) vv, ny, out); mx = periodic_bc ((int) uu - sx, nx, out); my = periodic_bc ((int) vv - sx, ny, out); dx = periodic_bc ((int) uu + sx, nx, out); dy = periodic_bc ((int) vv + sy, ny, out); ddx = periodic_bc ((int) uu + 2 * sx, nx, out); ddy = periodic_bc ((int) vv + 2 * sy, ny, out); break; case 2: x = symmetric_bc ((int) uu, nx, out); y = symmetric_bc ((int) vv, ny, out); mx = symmetric_bc ((int) uu - sx, nx, out); my = symmetric_bc ((int) vv - sx, ny, out); dx = symmetric_bc ((int) uu + sx, nx, out); dy = symmetric_bc ((int) vv + sy, ny, out); ddx = symmetric_bc ((int) uu + 2 * sx, nx, out); ddy = symmetric_bc ((int) vv + 2 * sy, ny, out); break; default: x = neumann_bc ((int) uu, nx, out); y = neumann_bc ((int) vv, ny, out); mx = neumann_bc ((int) uu - sx, nx, out); my = neumann_bc ((int) vv - sx, ny, out); dx = neumann_bc ((int) uu + sx, nx, out); dy = neumann_bc ((int) vv + sy, ny, out); ddx = neumann_bc ((int) uu + 2 * sx, nx, out); ddy = neumann_bc ((int) vv + 2 * sy, ny, out); break; } if (out && border_out) return 0.0; else { //obtain the interpolation points of the image const float p11 = input[(mx + nx * my) * nz + k]; const float p12 = input[(x + nx * my) * nz + k]; const float p13 = input[(dx + nx * my) * nz + k]; const float p14 = input[(ddx + nx * my) * nz + k]; const float p21 = input[(mx + nx * y) * nz + k]; const float p22 = input[(x + nx * y) * nz + k]; const float p23 = input[(dx + nx * y) * nz + k]; const float p24 = input[(ddx + nx * y) * nz + k]; const float p31 = input[(mx + nx * dy) * nz + k]; const float p32 = input[(x + nx * dy) * nz + k]; const float p33 = input[(dx + nx * dy) * nz + k]; const float p34 = input[(ddx + nx * dy) * nz + k]; const float p41 = input[(mx + nx * ddy) * nz + k]; const float p42 = input[(x + nx * ddy) * nz + k]; const float p43 = input[(dx + nx * ddy) * nz + k]; const float p44 = input[(ddx + nx * ddy) * nz + k]; //create array double pol[4][4] = { {p11, p21, p31, p41}, {p12, p22, p32, p42}, {p13, p23, p33, p43}, {p14, p24, p34, p44} }; //return interpolation return bicubic_interpolation (pol, (float) uu - x, (float) vv - y); } } /** * * Compute the bicubic interpolation of an image. * **/ void bicubic_interpolation (const float *input, //image to be warped const float *u, //x component of the vector field const float *v, //y component of the vector field float *output, //warped output image with bicubic interpolation const int nx, //width of the image const int ny, //height of the image const int nz, //number of channels of the image bool border_out = false //if true, put zeros outside the region ) { for(int k = 0; k < nz; k++){ #pragma omp parallel for for (int i = 0; i < ny; i++) for (int j = 0; j < nx; j++){ const int p = i * nx + j; const float uu = (float) (j + u[p]); const float vv = (float) (i + v[p]); //obtain the bicubic interpolation at position (uu, vv) output[p * nz + k] = bicubic_interpolation (input, uu, vv, nx, ny, nz, k, border_out); } } // end multi-channel loop } #endif
LA2.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define N 500 long long int a[N][N], b[N][N], c[N][N],c1[N][N],c2[N][N],c3[N][N],c4[N][N],c5[N][N]; int main (int argc, char *argv[]) { omp_set_num_threads(4); int tid, nthreads, i, j, k; double start,end,start1,end1,start2,end2,start3,end3,start4,end4,start5,end5; FILE *fptr,*fptr1; fptr = fopen("matA_500.txt","r"); if(fptr==NULL){exit(1);} fptr1 = fopen("matB_500.txt","r"); if(fptr1==NULL){exit(1);} /*** Create a parallel region explicitly scoping all variables ***/ #pragma omp parallel shared(a,b,c,nthreads) private(tid,i,j,k) { tid = omp_get_thread_num(); #pragma omp single { nthreads = omp_get_num_threads(); printf("Starting matrix multiple example with %d threads\n",nthreads); printf("Initializing matrices...\n"); } /*** Initialize matrices ***/ #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ fscanf(fptr,"%lld",&a[i][j]); } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ fscanf(fptr1,"%lld",&b[i][j]); } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c[i][j]= 0; } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c1[i][j]= 0; } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c2[i][j]= 0; } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c3[i][j]= 0; } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c4[i][j]= 0; } } #pragma omp for for (i=0; i<N; i++){ for (j=0; j<N; j++){ c5[i][j]= 0; } } start = omp_get_wtime(); #pragma omp for for (i=0; i<N; i++) { //printf("Thread=%d did row=%d\n",tid,i); for(j=0; j<N; j++) for (k=0; k<N; k++) c[i][j] += a[i][k] * b[k][j]; } /*** End of parallel region ***/ end = omp_get_wtime() - start; start1 = omp_get_wtime(); #pragma omp for for (j=0; j<N; j++) { //printf("Thread=%d did row=%d\n",tid,i); for(k=0; k<N; k++) for (i=0; i<N; i++) c1[i][j] += a[i][k] * b[k][j]; } /*** End of parallel region ***/ end1 = omp_get_wtime() - start1; start2 = omp_get_wtime(); #pragma omp for for (k=0; k<N; k++) { //printf("Thread=%d did row=%d\n",tid,i); for(j=0; j<N; j++) for (i=0; i<N; i++) c2[i][j] += a[i][k] * b[k][j]; } /*** End of parallel region ***/ end2 = omp_get_wtime() - start2; start3 = omp_get_wtime(); #pragma omp for for (k=0; k<N; k++) { //printf("Thread=%d did row=%d\n",tid,i); for(i=0; i<N; i++) for (j=0; j<N; j++) c3[i][j] += a[i][k] * b[k][j]; } /*** End of parallel region ***/ end3 = omp_get_wtime() - start3; start4 = omp_get_wtime(); #pragma omp for for (j=0; j<N; j++) { //printf("Thread=%d did row=%d\n",tid,i); for(k=0; k<N; k++) for (i=0; i<N; i++) c4[i][j] += a[i][k] * b[k][j]; } /*** End of parallel region ***/ end4 = omp_get_wtime() - start4; start5 = omp_get_wtime(); #pragma omp for for (i=0; i<N; i++) { //printf("Thread=%d did row=%d\n",tid,i); for(k=0; k<N; k++) for (j=0; j<N; j++) c5[i][j] += a[i][k] * b[k][j]; }} /*** End of parallel region ***/ end5 = omp_get_wtime() - start5; /*printf("Result Matrix:\n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("%lld ", c1[i][j]); printf("\n"); } printf("******************************************************\n"); printf("Result Matrix:\n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("%lld ", c2[i][j]); printf("\n"); } printf("******************************************************\n");*/ printf("N : %d\n",N); printf("%.6g\n",end); printf("%.6g\n",end1); printf("%.6g\n",end2); printf("%.6g\n",end3); printf("%.6g\n",end4); printf("%.6g\n",end5); return(0); }
ops.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #pragma once #ifndef OPS_H_ #define OPS_H_ #include <op_boilerplate.h> #include <array/DataTypeUtils.h> #include <helpers/shape.h> #include <vector> #include <Environment.h> #include <loops/summarystatsreduce.h> #include <loops/ReduceType.h> #define MIN_V 1e-12 #define MAX_FLOAT 1e37 #define MIN_FLOAT 1e-37 #define MAX_INT 2147483647 #define MIN_CUTFOFF -3.79297773665f #define FLOAT_MIN_NORMAL 1.17549435e-38 #define EPS 1e-5 #define AFFINITY close #define DOUBLE_PI_T T(2.0 * 3.14159265358979323846) #define DOUBLE_PI_X X(2.0 * 3.14159265358979323846) #define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #ifdef __CUDACC__ #include <helpers/sharedmem.h> #define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #else // hacky fix for isnan/being being out of scope //#ifdef IOS //#define isinf(x) 0 // this isn't right. But std::isinf fails //#define isnan(x) 0 //#else //#define isnan std::isnan //#define isinf std::isinf //#endif #define no_op_exec_special_cuda #define no_op_exec_special_accumulation_cuda #define no_op_exec_special_accumulation_same_cuda #define no_op_exec_special_accumulation_long_cuda #define no_op_exec_special_any_cuda #define no_op_exec_special_bool_cuda #define no_op_exec_special_same_cuda #define no_op_exec_special_accumulation_same_cuda #endif #define SELU_ALPHA 1.6732632423543772848170429916717 #define SELU_LAMBDA 1.0507009873554804934193349852946 #ifdef _OPENMP #pragma omp declare reduction(maxTF : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\ initializer (omp_priv=-MAX_FLOAT) #pragma omp declare reduction(minTF : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\ initializer (omp_priv=MAX_FLOAT) #pragma omp declare reduction(maxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\ initializer (omp_priv=0) #pragma omp declare reduction(minT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\ initializer (omp_priv=0) #pragma omp declare reduction(amaxT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_max(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) ) #pragma omp declare reduction(aminT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_min(nd4j::math::nd4j_abs(omp_in), nd4j::math::nd4j_abs(omp_out)) ) #pragma omp declare reduction(asumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = nd4j::math::nd4j_abs(omp_in) + nd4j::math::nd4j_abs(omp_out))\ initializer (omp_priv=0) #pragma omp declare reduction(sumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = omp_in + omp_out)\ initializer (omp_priv=0) #pragma omp declare reduction(prodT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = omp_in * omp_out)\ initializer (omp_priv=1) #endif namespace functions { namespace indexreduce { template <typename T> struct IndexValue { T value; Nd4jLong index; _CUDA_HD IndexValue() = default; _CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {} }; } namespace summarystats { template <typename T> class SummaryStatsData; } } namespace simdOps { template <typename X, typename Y, typename Z> class Add { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 + params[0]); } op_def static X startingValue() { return static_cast<X>(0.f); } }; template <typename X, typename Y> class NewAdd { public: op_def static X op(X d1, Y d2, X *params) { return d1 + d2; } }; template <typename X, typename Y, typename Z> class Subtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 - params[0]); } }; template <typename X, typename Y, typename Z> class SquaredSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d1 - d2); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(d1 - params[0]); return d * d; } }; template <typename X, typename Y, typename Z> class SquaredReverseSubtract { public: op_def static Z op(X d1, Y d2) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1, Y d2, Z *params) { auto d = static_cast<Z>(d2 - d1); return d * d; } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto d = static_cast<Z>(params[0] - d1); return d * d; } }; template <typename X, typename Y, typename Z> class ReverseSubtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] - d1); } }; template <typename X, typename Y, typename Z> class LogPoissonLossFull { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z) { auto zz = static_cast<Z>(z); return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)); } // op for MetaOps op_def static X op(X z, Y *params) { return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z))); } }; template <typename X, typename Y, typename Z> class LogPoissonLoss { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z) { return static_cast<Z>(z); } // op for MetaOps op_def static Z op(X z, Y *params) { return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0])); } }; template <typename X, typename Y, typename Z> class Multiply { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 * params[0]); } op_def static X startingValue() { return static_cast<X>(1.f); } }; template <typename X, typename Y, typename Z> class Divide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class SafeDivide { public: op_def static Z op(X d1, Y d2) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if(params[0] == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / params[0]); } }; template <typename X, typename Y, typename Z> class FloorDiv { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1)); } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0])); } }; template <typename X, typename Y, typename Z> class TruncateDiv { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 / i2); } }; template <typename X, typename Y, typename Z> class TruncateMod { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 % i2); } }; template<typename X, typename Y, typename Z> class Remainder { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FMod { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FloorMod { public: op_def static Z op(X d1, Y d2) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1, Y d2, Z *params) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseDivide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] / d1); } }; template <typename X, typename Y, typename Z> class CopyPws { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X> class Copy { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X, typename Y, typename Z> class Copy2 { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X, typename Y, typename Z> class Axpy { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 + d1); } op_def static Z op(X d1, Y d2, Z *params) { auto alpha = params[0]; return alpha * static_cast<Z>(d1) + static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class Assign { public: no_op_exec_special_any no_op_exec_special_any_cuda op_def static Z op(X d1, X *params) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class And { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Or { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Xor { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Z> class Not { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0); } // this transform op should run only on boolean input op_def static Z op(X d1, X *params) { auto b1 = static_cast<bool>(d1); return !b1; } }; template <typename X, typename Y, typename Z> class LogicalNot { public: op_def static Z op(X d1, Y d2) { return !((int) d1 && (int) d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2))); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class LogicalXor { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return (i1 | i2) &~ (i1 & i2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalAnd { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) & static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(Y d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalOr { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) | static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class Mod { public: /* // just a optional note, feel free to remove later op_def static half op(half d1, half d2, half *params) { return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr)); } */ op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) % static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseMod { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d2) % static_cast<int>(d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; /** * Whether 2 elements in an array * are epsilion equal */ template <typename X, typename Z> class Epsilon { public: op_def static Z op(X d1, X d2) { X diff = d1 - d2; X absDiff = nd4j::math::nd4j_abs<X>(diff); if (absDiff <= static_cast<X>(MIN_V)) return static_cast<Z>(1); return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class EqualTo { public: op_def static Z op(X d1, X d2) { return d1 == d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class NotEqualTo { public: op_def static Z op(X d1, X d2) { return d1 != d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 >= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThan { public: op_def static Z op(X d1, X d2) { return d1 > d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThan { public: op_def static Z op(X d1, X d2) { return d1 < d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 <= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X> class Abs { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_abs<X>(d1); } }; template <typename X> class Ceiling { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_ceil<X,X>(d1); } }; template <typename X> class Cosine { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cos<X,X>(d1); } }; template <typename X> class Exp { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X> class HardTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f)); } }; template <typename X> class HardTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 < static_cast<X>(-1)) return static_cast<X>(-1); else if (d1 > static_cast<X>(1)) return static_cast<X>(1); else return d1; } }; template <typename X> class Floor { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_floor<X,X>(d1); } }; template <typename X> class Log { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(d1); } }; template <typename X> class Log1p { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(1 + d1); } }; template <typename X, typename Y, typename Z> class LogX { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ; } }; template <typename X> class StabilizeFP16 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return static_cast<X>(nd4j::DataTypeUtils::min<float16>()); else return d1; } }; template <typename X> class StabilizeX { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return nd4j::DataTypeUtils::min<X>(); else return d1; } }; template <typename X> class SpecialDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1.f) - d1); } }; template <typename X> class Neg { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return -d1; } }; template <typename X> class Erf { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erf<X,X>(d1); } }; template <typename X> class Erfc { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erfc<X,X>(d1); } }; template <typename X> class Reciprocal { public: no_op_exec_special_same no_op_exec_special_same_cuda // op_def static T op(T d1) { // return (T(1.0f) / d1); // } // op for MetaOps op_def static X op(X d1, X *params) { return (static_cast<X>(1) / d1); } }; template <typename X, typename Z> class Sqr { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } }; template <typename X, typename Y, typename Z> class RelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_re<X>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X threshold = params[0]; return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryMinimumAbsoluteRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, X *params) { X d2 = params[0]; X thresholdRelative = params[1]; X thresholdAbsolute = params[2]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1, Y d2, Z *params) { X thresholdRelative = params[0]; X thresholdAbsolute = params[1]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class ReversePow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(params[0], d1); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d2, d1); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class Pow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class PowDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1) { return d1; } }; template <typename X> class Round { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_round<X,X>(d1); } }; template <typename X, typename Z> class IsNan { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class Expm1 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1); } }; template <typename X, typename Z> class IsPositive { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return d1 > (X)0.f; } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInf { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInfOrNan{ public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsFinite { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ClipByValue { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 > params[1]) return params[1]; if (d1 < params[0]) return params[0]; return d1; } }; template <typename X, typename Y, typename Z> class LstmClip { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X _v = (X) d2; if (d1 > _v) return _v; else if (d1 < -_v) return -_v; else return d1; } }; template <typename X> class Swish { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1); } }; template <typename X> class GELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(static_cast<X>(1.702f) * d1); } }; template <typename X> class PreciseGELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto sp = nd4j::math::nd4j_sqrt<X, X>(static_cast<X>(2) / static_cast<X>(M_PI)); auto xp = d1 + nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(0.044715) * d1, static_cast<X>(3)); return (d1 / static_cast<X>(2)) * (static_cast<X>(1) + nd4j::math::nd4j_tanh<X, X>(sp * xp)); } }; template <typename X> class GELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x17 = static_cast<X>(1.702f) * d1; auto ep = nd4j::math::nd4j_pow<X,X,X>(static_cast<X>(M_E), x17); // (E^(1.702 x) (1. + E^(1.702 x) + 1.702 x))/(1. + E^(1.702 x))^2 return (ep * (static_cast<X>(1.f) + ep + x17)) / nd4j::math::nd4j_pow<X, int, X>((static_cast<X>(1.f) + ep), 2); } }; template <typename X> class PreciseGELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto x79 = static_cast<X>(0.797885) * d1; auto x03 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0356774) * d1, 3); auto x39 = static_cast<X>(0.398942) * d1; auto x05 = nd4j::math::nd4j_pow<X, int, X>(static_cast<X>(0.0535161) * d1, 3); auto scz = nd4j::math::nd4j_sech<X, X>(x79 + x03); // 0.5 + (0.398942 x + 0.0535161 x^3) Sech[0.797885 x + 0.0356774 x^3]^2 + 0.5 Tanh[0.797885 x + 0.0356774 x^3] return static_cast<X>(0.5) + (x39 + x05) * (scz * scz) + static_cast<X>(0.5) * nd4j::math::nd4j_tanh<X, X>(x79 + x03); } }; template <typename X> class SwishDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1); return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f)); } }; template <typename X> class LogSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1)); } }; template <typename X> class LogSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1); return static_cast<X>(1.f) / (ex + static_cast<X>(1.f)); } }; template <typename X> class Sigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoid<X, X>(d1); } }; template <typename X> class SigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoidderivative<X, X>(d1); } }; template <typename X> class HardSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f))); } }; template <typename X> class HardSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f); } }; /** * Scale to be between a min and max */ template <typename X> class SetRange { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto min = params[0]; auto max = params[1]; if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max) return d1; if (min == static_cast<X>(0) && max == static_cast<X>(1)) { auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1)); return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min); } return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min); } }; template <typename X> class Sin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sin<X,X>(d1); } }; template <typename X> class Square { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1; } }; template <typename X, typename Z> class Sqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X, typename Z> class RSqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X> class Rint { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_rint<X,X>(d1); } }; template <typename X> class SoftPlus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::softplus<X, X>(d1); } }; template <typename X> class Sign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0)); } }; template <typename X> class TimesOneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1) - d1); } }; template <typename X> class RationalTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { // keep 2/3 as runtime variable, to match precision auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1; auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) ))); return static_cast<X>(1.7159f) * tanh; } }; template <typename X> class RationalTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1; auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)); auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a); return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv; } }; template <typename X> class Tanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanh<X, X>(d1); } }; template <typename X> class RectifiedTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1)); } }; template <typename X> class RectifiedTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f); } }; template <typename X> class ATanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atanh<X,X>(d1); } }; template <typename X> class TanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanhderivative<X,X>(d1); } }; template <typename X> class Cube { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1 * d1; } }; template <typename X> class CubeDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(3) * d1 * d1; } }; template <typename X> class ACos { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acos<X, X>(d1); } }; template <typename X> class ASinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asinh<X, X>(d1); } }; template <typename X> class ASinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f))); } }; template <typename X> class ACosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acosh<X, X>(d1); } }; template <typename X> class ACoshDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f))); } }; template <typename X> class Ones { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.0f); } }; template <typename X> class SoftSign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsign<X, X>(d1); } }; template <typename X> class SoftSignDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsignderivative<X,X>(d1); } }; template <typename X, typename Z> class MatchConditionBool { public: no_op_exec_special_bool no_op_exec_special_bool_cuda // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false; case 2: // less_than return d1 < compare ? true : false; case 3: // greater_than return d1 > compare ? true : false; case 4: // less_or_equals_than return d1 <= compare ? true : false; case 5: // greater_or_equals_than return d1 >= compare ? true : false; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? true : false; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? true : false; case 10: return (d1 == compare) ? true : false; case 11: return (d1 != compare) ? true : false; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)); case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1); default: printf("Undefined match condition: [%i]\n", mode); } return d1; } }; template <typename X, typename Z> class MatchCondition { public: no_op_exec_special no_op_exec_special_cuda no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return old + opOutput; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return old + opOutput; } // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //printf("value: %f; comp: %f; eps: %f; mode: %i;\n", (float) d1, (float) compare, (float) eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0; case 2: // less_than return d1 < compare ? 1 : 0; case 3: // greater_than return d1 > compare ? 1 : 0; case 4: // less_or_equals_than return d1 <= compare ? 1 : 0; case 5: // greater_or_equals_than return d1 >= compare ? 1 : 0; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? 1 : 0; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? 1 : 0; case 10: return (d1 == compare) ? 1 : 0; case 11: return (d1 != compare) ? 1 : 0; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0; case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0; default: printf("Undefined match condition: [%i]\n", mode); } return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_elu<X,X>(d1); } }; template <typename X> class ELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_eluderivative<X,X>(d1); } }; template <typename X, typename Y, typename Z> class RELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto xt = static_cast<Z>(d1); auto xf = static_cast<Z>(d2); return xt < xf ? xf : xt; } }; template <typename X, typename Y, typename Z> class SXELogitsSmoother { public: op_def static Z op(X d1, Y d2, Z *params) { return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2; } }; template <typename X, typename Y, typename Z> class RELU6 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params); return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6); } }; template <typename X, typename Y, typename Z> class LeakyRELU { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { auto val = static_cast<Z>(d1); auto alpha = static_cast<Z>(d2); return val < 0.0f ? alpha * val : val; } }; template <typename X> class SELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA)); } }; template <typename X> class SELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X, typename Y, typename Z> class LeakyRELUDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { if (d1 >= static_cast<X>(0)) return static_cast<Z>(1); else return static_cast<Z>(d2); } }; template <typename X> class ASin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asin<X,X>(d1); } }; template <typename X> class Sinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sinh<X,X>(d1); } }; template <typename X> class SinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X, X>(d1); } }; template <typename X> class Cosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X,X>(d1); } }; template <typename X> class Tan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tan<X,X>(d1); } }; template <typename X> class TanDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f)); } }; template <typename X> class ATan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atan<X, X>(d1); } }; template <typename X, typename Y, typename Z> class Atan2 { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_atan2<X, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X> class Identity { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X> class Stabilize { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X k = params[0]; if (d1 * k > static_cast<X>(- MIN_CUTFOFF)) return static_cast<X>(- MIN_CUTFOFF) / k; else if (d1 * k < static_cast<X>(MIN_CUTFOFF)) return static_cast<X>(MIN_CUTFOFF) / k; return d1; } }; template <typename X, typename Y, typename Z> class Step { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0)); } }; template <typename X> class OneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1) - d1; } }; template <typename X> class Sum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ReduceSameBenchmarkOp { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<X>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class ShannonEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto p = d1 * d1; return static_cast<Z>(p) * nd4j::math::nd4j_log<X, Z>(p); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return -reduction; } }; template <typename X, typename Z> class LogEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { //entropy is -sum(p(x) * log(p(x))); log entropy is log of this return nd4j::math::nd4j_log<Z, Z>(-reduction); } }; template <typename X, typename Z> class Entropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x))) } }; template <typename X> class ASum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X, typename Z> class CountNonZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::ASUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class CountZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return static_cast<Z>(reduction); } }; template <typename X> class Prod { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Any { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ; } }; template <typename X, typename Z> class All { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::PRODUCT; op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0); } }; template <typename X, typename Z> class Mean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction / (Z) n; } }; template <typename X, typename Z> class ReduceFloatBenchmarkOp { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { auto f1 = static_cast<float>(d1); return static_cast<Z>(nd4j::math::nd4j_pow<float,float,float>(f1, 3) + nd4j::math::nd4j_log<float,float>(f1) * nd4j::math::nd4j_sin<float,float>(f1) / nd4j::math::nd4j_tanh<float,float>(static_cast<float>(M_E) * static_cast<float>(M_PI) * f1) * nd4j::math::nd4j_sqrt<float,float>(static_cast<float>(M_PI) / f1) - nd4j::math::nd4j_atan<float,float>(static_cast<float>(M_E) / f1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return (Z) reduction / (Z) n; } }; template <typename X, typename Z> class AMean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_abs<Z>(reduction) / static_cast<Z>(n); } }; template <typename X> class Max { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MAX; op_def static X startingValue(const X *input) { return -nd4j::DataTypeUtils::max<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class AMaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class AMinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class MaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X, typename Y, typename Z> class MinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X> class AMax { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMAX; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2; } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class AMin { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::AMIN; op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class Min { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda const static functions::ReduceType reduceType = functions::ReduceType::MIN; op_def static X startingValue(const X *input) { return nd4j::DataTypeUtils::max<X>(); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm1 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1)); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm2 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } }; template <typename X, typename Z> class SquaredNorm { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return reduction; } }; template <typename X, typename Z> class NormFrobenius { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { X v = nd4j::math::nd4j_abs<X>(d1); return static_cast<Z>(v * v); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<Z, Z>(reduction); } }; template <typename X, typename Z> class NormP { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_pow<Z, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]); } }; template <typename X, typename Z> class NormMax { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(Z old, Z opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(old), nd4j::math::nd4j_abs<Z>(opOutput)); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(reduction), nd4j::math::nd4j_abs<Z>(reduction)); } }; template <typename X, typename Z> class Variance { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static X op(X d1, Z *extraParams) { X mean = static_cast<X>(extraParams[0]); X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { // T bias = extraParams[1]; // return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1) return static_cast<Z>(reduction) / static_cast<Z>(n - 1); } }; /** * Standard deviation of a buffer */ template <typename X, typename Z> class StandardDeviation { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda const static functions::ReduceType reduceType = functions::ReduceType::SUM; op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z op(X d1, Z *extraParams) { X mean = extraParams[0]; X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams); Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret); return sqrtRet; } }; template <typename X, typename Y> class CosineSimilarity { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(d1 * d1); extraParams[1] += static_cast<Y>(d2 * d2); return static_cast<Y>(d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2)); return static_cast<Y>(d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class JaccardDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { // num / denom return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]); } op_def static Y num(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static Y denom(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(num(d1, d2)); extraParams[1] += static_cast<Y>(denom(d1, d2)); return static_cast<Y>(0.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2)); return static_cast<Y>(0.0f); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class SimpleHammingDistance { public: static const int extraParamsLen = 0; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return static_cast<Y>(reduction / n); } op_def static Y op(X d1, X d2, Y *extraParams) { return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f); } op_def static void aggregateExtraParams(X *extraParamsTotal, X *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { return op(d1, d2, extraParams); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class CosineDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]))); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1)); extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2)); return (d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2)); return (d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; /** * Dot product between 2 arrays */ template <typename X, typename Y> class Dot { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op //delete[] * extraParamsRef; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return static_cast<Y>(d1 * d2); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; /** * Op to check equality within arrays */ template <typename X, typename Z> class EqualsWithEps { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) { return reduction; } op_def static Z op(X d1, X d2, Z *extraParamsRef) { double eps = nd4j::math::nd4j_abs<double>(extraParamsRef[2]); return static_cast<Z>(!nd4j::math::nd4j_eq<X>(d1, d2, eps)); } #ifdef __CUDACC__ __device__ static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) { return opOutput + old; } op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {} }; template <typename X, typename Y> class EuclideanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return nd4j::math::nd4j_sqrt<Y, Y>(reduction); } op_def static Y op(X d1, X d2, Y *extraParamsRef) { X ret = d1 - d2; return static_cast<Y>(ret * ret); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; template <typename X, typename Y> class ManhattanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return nd4j::math::nd4j_abs<X>(d1 - d2); } op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return old + opOutput; } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif #ifndef __clang__ #pragma omp declare simd uniform(extraParamsRef) #endif op_def static Y merge(X old, X opOutput, X *extraParamsRef) { return update(old, opOutput, extraParamsRef); } }; template <typename X> class IndexAbsoluteMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return nd4j::math::nd4j_abs<X>(val); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value > old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return 0; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class FirstIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); //printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index > opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index > f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X> class LastIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index < opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index < f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X> class IndexMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value > old.value) { return opOutput; } #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value > f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(const X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class IndexAbsoluteMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class IndexMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(const X *input) { return nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value < f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsVariance { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { Z ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return static_cast<Z>(val.variance()); return ret; } return static_cast<Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsStandardDeviation { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { auto ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); else return nd4j::math::nd4j_sqrt<double, Z>(ret); } return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X> class DropOut { public: no_op_exec_special_same no_op_exec_special_same_cuda inline _CUDA_D static X op(X d1, X *params) { X prob = params[0]; #ifdef __CUDACC__ X length = params[1]; X tid = gridDim.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= prob ? static_cast<X>(0.0f) : d1; } }; template <typename X, typename Y, typename Z> class DropOutInverted { public: no_op_exec_special no_op_exec_special_cuda #ifdef __CUDACC__ __device__ #endif inline static Z op(X d1, Y d2, Z *params) { Y prob = d2; #ifdef __CUDACC__ X length = params[1]; X tid = gridDim.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob)); } }; template <typename X, typename Y, typename Z> class ReplaceNans { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ; } }; // this op is used for conditional pairwise transforms only template <typename X, typename Y, typename Z> class CompareAndReplace{ public: // op definition for PairWise Transform op_def static Z op(X d1, Y d2, Z *params) { auto zd1 = static_cast<Z>(d1); auto zd2 = static_cast<Z>(d2); auto compare = params[0]; auto eps = params[2]; int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps) return zd2; else return zd1; else if (mode == 1) // not equals eps if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps) return zd2; else return zd1; else if (mode == 2) // less_than eps if (zd1 < compare) return zd2; else return zd1; else if (mode ==3) // greater_than if (zd1 > compare) return zd2; else return zd1; else if (mode == 4) // less_or_equals_than if (zd1 <= compare) return zd2; else return zd1; else if (mode == 5) // greater_or_equals_than if (zd1 >= compare) return zd2; else return zd1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(zd1) < compare) return zd2; else return zd1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(zd1) > compare) return zd2; else return zd1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(zd1)) return zd2; else return zd1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(zd1)) return zd2; else return zd1; else if (mode == 10) if (zd1 == compare) return zd2; else return zd1; else if (mode == 11) if (zd1 != compare) return zd2; else return zd1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) >= compare) return zd2; else return zd1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) <= compare) return zd2; else return zd1; else printf("Undefined boolean operation: [%i]\n", mode); return zd1; } }; template <typename X, typename Y, typename Z> class CompareAndSet { public: // op definition for PairWise Transform op_def static Z op(X dX, Y dY, Z *params) { auto d1 = static_cast<Z>(dX); auto d2 = static_cast<Z>(dY); auto compare = params[0]; auto eps = params[2]; auto mode = static_cast<int>(params[3]); if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps) return d2; else return d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps) return d2; else return d1; else if (mode == 2) // less_than if (d2 < compare) return d2; else return d1; else if (mode ==3) // greater_than if (d2 > compare) return d2; else return d1; else if (mode == 4) // less_or_equals_than if (d2 <= compare) return d2; else return d1; else if (mode == 5) // greater_or_equals_than if (d2 >= compare) return d2; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(d2) < compare) return d2; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(d2) > compare) return d2; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d2)) return d2; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d2)) return d2; else return d1; else if (mode == 10) if (d2 == compare) return d2; else return d1; else if (mode == 11) if (d2 != compare) return d2; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) >= compare) return d2; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) <= compare) return d2; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; template <typename X> class CompareAndSetTransform { public: no_op_exec_special_same no_op_exec_special_same_cuda // op definition for Transform op_def static X op(X d1, X *params) { auto compare = params[0]; auto set = params[1]; auto eps = params[2]; // with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1; else if (mode == 2) // less_than if (d1 < compare) return set; else return d1; else if (mode ==3) // greater_than if (d1 > compare) return set; else return d1; else if (mode == 4) // less_or_equals_than if (d1 <= compare) return set; else return d1; else if (mode == 5) // greater_or_equals_than if (d1 >= compare) return set; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<X>(d1) < compare) return set; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<X>(d1) > compare) return set; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d1)) return set; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d1)) return set; else return d1; else if (mode == 10) if (d1 == compare) return set; else return d1; else if (mode == 11) if (d1 != compare) return set; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) >= compare) return set; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) <= compare) return set; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; } #endif
spgemm_utils.h
#ifndef UTILS_H_ #define UTILS_H_ #include <algorithm> #include <numeric> #include <unordered_map> #include <iostream> #include <chrono> #include <map> #include <sys/stat.h> #include <omp.h> #include "asserter.h" #include "hooks.h" #include "csr_matrix.h" #include "spgemm_defs.h" #include "helper_classes.h" #include "sparse_accumulator.h" #include "dense_accumulator.h" unsigned char MSB(uint32_t v) { // start counting from 1 for MSB, which means, for 4, will return 2 if (v == 0) return 0; unsigned char msb = 0, t; t = ((v >> 16) == 0) ? 0 : 16; v = (v >> msb); msb += t; t = (((v >> 8) == 0) ? 0 : 8); v = (v >> t); msb += t; t = (((v >> 4) == 0) ? 0 : 4); v = (v >> t); msb += t; t = (((v >> 2) == 0) ? 0 : 2); v = (v >> t); msb += t; t = (((v >> 1) == 0) ? 0 : 1); v = (v >> t); msb += t; return msb+v; } template<typename CSROrdinal, typename Value> NumBits getNumBits(CSROrdinal n) { // The inital value for lower and higher assumes : // ((long)1<<16) < B.ncols() <= ((long)1<<32) uint8_t num_bits_lower = 16; uint8_t num_bits_higher = 16; if (n <= ((long)1<<16)) { num_bits_lower = 8; num_bits_higher = 8; } if (n > ((long)1<<32)) { num_bits_lower = 32; num_bits_higher = 32; } // based on L2 cache size, the maximum width we can have for hashmap CSROrdinal width = L2_CACHE_SIZE/(sizeof(Value)); assert((width & (width - 1)) == 0); // check that width is power of 2 // IF L2 cache can store less than the given range if ( width < ((long)1<<(num_bits_lower)) ) { if (n <= (((long)1<<num_bits_higher)*width)) // Use the width if possible num_bits_lower = std::min((uint8_t)(MSB(width)-1), (uint8_t)MSB(n)); } CSROrdinal higher_range = (n >> num_bits_lower); num_bits_higher = MSB(higher_range) - ((n & (n - 1)) == 0); // twisting the bits to use small sized data type uint8_t total_bits = num_bits_higher + num_bits_lower; uint8_t sizes[] = {16, 16+8}; for (auto s : sizes) { if (total_bits <= s) { if (num_bits_higher > 8 || num_bits_lower > total_bits - 8) { num_bits_higher = 8; num_bits_lower = total_bits - 8; break; } } } // check the correctness assert( (long(1) << (num_bits_higher + num_bits_lower)) >= n ); assert( (long(1) << (num_bits_higher + num_bits_lower - 1)) < n ); return NumBits(num_bits_higher, num_bits_lower); } template<typename CSROrdinal, typename Value, typename HOrdType, typename LOrdType> void constructHL ( Matrix<CSROrdinal, CSROrdinal, Value> & B_org, TwoLevelMatrix<CSROrdinal, Value, HOrdType, LOrdType> & B, size_t chunk_size, bool statistic_verb = false) { CSROrdinal nrows = B_org.nrows(); CSROrdinal ncols = B_org.ncols(); CSROrdinal nnz = B_org.nnz(); CSROrdinal * ptr = B_org.Ptr(); CSROrdinal * colindices = B_org.ColIndices(); // In this implementation, we assume B_org is sorted within each row, // so values pointers are the same. B.values = B_org.Values(); /* Allocate ptr */ B.H.AllocatePtr(nrows+1); CSROrdinal * ptrH = B.H.Ptr(); ptrH[0] = 0; // Used for checking whether to use compression or not B.row_ptr_compress = (CSROrdinal *) malloc (sizeof(CSROrdinal) * (nrows+1)); B.row_ptr_compress[0] = 0; /* Calculate the row sizes of B.H and generate matrixL within the same round of visiting matrix */ CSROrdinal lower_bits = (1 << B.num_bits.lower) - 1; #pragma omp parallel for schedule(dynamic, chunk_size) for (CSROrdinal v=0; v<nrows; ++v) { CSROrdinal count = 0; // For compression CSROrdinal count_compress_edge = 0; CSROrdinal st=ptr[v]; CSROrdinal end=ptr[v+1]; HOrdType edgeH; if (st != end) { edgeH = ((colindices[st]) >> B.num_bits.lower); count++; //For compression CSROrdinal edge_comp = colindices[st] >> 5; count_compress_edge++; // generate row size with count for (CSROrdinal u_pos=st+1; u_pos<end; ++u_pos) { // neighbor list is supporsed to be sorted and no multi-colindices assert(colindices[u_pos] > colindices[u_pos-1]); count += (edgeH != (colindices[u_pos] >> B.num_bits.lower)); edgeH = (colindices[u_pos] >> B.num_bits.lower); //For compression count_compress_edge += (edge_comp != (colindices[u_pos] >> 5)); edge_comp = colindices[u_pos] >> 5; } } ptrH[v+1] = count; //For compression B.row_ptr_compress[v+1] = count_compress_edge; } std::partial_sum(ptrH, ptrH + nrows + 1, ptrH); //For compression std::partial_sum(B.row_ptr_compress, B.row_ptr_compress + nrows + 1, B.row_ptr_compress); float compression_ratio = (float)(B.row_ptr_compress[nrows])/nnz; if (compression_ratio < comp_ratio_maxium) USE_COMPRESSION = true; else USE_COMPRESSION = false; bool useHL = !(((USE_COMPRESSION && ((ncols >> 5) < (L2_CACHE_SIZE/sizeof(uint32_t)))) || (ncols < L2_CACHE_SIZE/sizeof(CSROrdinal))) && (ncols < L2_CACHE_SIZE/sizeof(Value))); /* Allocate colindices and values */ HOrdType * colindicesH; CSROrdinal * valuesH; if (useHL) { B.H.AllocateColIndices(ptrH[nrows]); B.H.AllocateValues(ptrH[nrows]+1); colindicesH = B.H.ColIndices(); valuesH = B.H.Values(); B.L = (LOrdType *) malloc (sizeof(LOrdType) * nnz); } if (USE_COMPRESSION) { B.seg_ptr_compress = (CSROrdinal *) malloc (sizeof(CSROrdinal) * (ptrH[nrows]+1)); B.LA_compress = (uint16_t *) malloc (sizeof(uint16_t) * (B.row_ptr_compress[nrows])); B.L_compress = (LOrdType *) malloc (sizeof(LOrdType) * (B.row_ptr_compress[nrows])); B.values_compress = (uint32_t *) malloc (sizeof(uint32_t) * (B.row_ptr_compress[nrows])); } /* get all colindices, get the data of B.H: colindices, and values */ #pragma omp parallel for schedule(dynamic, chunk_size) for (CSROrdinal v=0; v<nrows; ++v) { CSROrdinal st=ptr[v]; CSROrdinal end=ptr[v+1]; CSROrdinal stH=ptrH[v]; //For compression if (useHL || USE_COMPRESSION) { CSROrdinal stCompress, edge_comp; uint32_t compress; if (USE_COMPRESSION) stCompress = B.row_ptr_compress[v]; if (useHL) { // generate matrixL for (CSROrdinal u_pos=st; u_pos<end; ++u_pos) B.L[u_pos] = (colindices[u_pos] & lower_bits); } if (st != end) { if(USE_COMPRESSION) { edge_comp = colindices[st] >> 5; B.seg_ptr_compress[stH] = stCompress; compress = (1 << (colindices[st] & 31)); } HOrdType edgeH=((colindices[st]) >> B.num_bits.lower); if (useHL) { colindicesH[stH] = edgeH; valuesH[stH] = st; stH++; } for (CSROrdinal u_pos=st+1; u_pos<end; ++u_pos) { // neighbor list is supporsed to be sorted and no multi-colindices assert(colindices[u_pos] > colindices[u_pos-1]); if (USE_COMPRESSION) { if (edge_comp != (colindices[u_pos] >> 5)) { B.values_compress[stCompress] = compress; B.LA_compress[stCompress] = edge_comp; B.L_compress[stCompress] = edge_comp & (lower_bits >> 5); compress=(1 << (colindices[u_pos] & 31)); edge_comp=colindices[u_pos] >> 5; stCompress++; } else { compress |= (1<< (colindices[u_pos] & 31)); } } if (edgeH != (colindices[u_pos] >> B.num_bits.lower)) { edgeH = (colindices[u_pos] >> B.num_bits.lower); if (useHL) { colindicesH[stH] = edgeH; valuesH[stH] = u_pos; if(USE_COMPRESSION) B.seg_ptr_compress[stH] = stCompress; stH++; } } } if(USE_COMPRESSION) { B.values_compress[stCompress] = compress; B.LA_compress[stCompress] = edge_comp; B.L_compress[stCompress] = edge_comp & (lower_bits >> 5); stCompress++; } } if(USE_COMPRESSION) if (B.row_ptr_compress[v+1] != stCompress) throw -1; } } if (useHL) valuesH[ptrH[nrows]] = nnz; if(USE_COMPRESSION) { B.compressed_edge_num = B.row_ptr_compress[nrows]; B.seg_ptr_compress[ptrH[nrows]] = B.row_ptr_compress[nrows]; } if (statistic_verb) { std::cout << std::setw(STR_LEN) << "Compression Ratio is" << " : " << std::fixed << std::setprecision(6) << std::setw(NUM_LEN) << compression_ratio << ", and compression is"; if (!USE_COMPRESSION) std::cout << " Not"; std::cout << " applied." << std::endl; std::cout << std::setw(STR_LEN) << "S has non-zeros" << " : " << std::setw(NUM_LEN) << B.H.nnz(); if (USE_COMPRESSION && ((B_org.ncols()>> 5) < (L2_CACHE_SIZE/sizeof(uint32_t)))) std::cout << ", direct merging on dense array will be applied" << std::endl; else std::cout << std::endl; } } template<typename CSROrdinal, typename Value, typename HOrdType, typename LOrdType> UpperBounds<CSROrdinal, Value> getUpperBounds ( Matrix<CSROrdinal, CSROrdinal, Value> & A, Matrix<CSROrdinal, CSROrdinal, Value> & B_org, TwoLevelMatrix<CSROrdinal, Value, HOrdType, LOrdType> & B, size_t chunk_size, bool statistic_verb = false) { CSROrdinal max_widthComp=0, max_width=0, max_widthH=0, max_degA=0, max_collisions=0; long flops=0; CSROrdinal * ptrA = A.Ptr(); CSROrdinal * ptrBH = B.H.Ptr(); CSROrdinal * ptrBComp = B.row_ptr_compress; #pragma omp parallel for schedule(dynamic, chunk_size) reduction(max:max_widthComp) reduction(max:max_width) reduction(max:max_widthH) reduction(max:max_degA) reduction(max:max_collisions) reduction(+:flops) for (CSROrdinal v=0; v<A.nrows(); ++v) { CSROrdinal st=ptrA[v]; CSROrdinal end=ptrA[v+1]; max_degA = (max_degA > end-st) ? max_degA : end-st; CSROrdinal _widthComp = 0; CSROrdinal _widthH = 0; CSROrdinal _width = 0; CSROrdinal _max_deg = 0; for (CSROrdinal u_pos=st; u_pos<end; ++u_pos) { CSROrdinal u = A.ColIndices()[u_pos]; CSROrdinal u_degH = ptrBH[u+1] - ptrBH[u]; _max_deg = (_max_deg > u_degH) ? _max_deg : u_degH; _widthComp += (ptrBComp[u+1] - ptrBComp[u]); _widthH += u_degH; _width += B_org.Ptr()[u+1] - B_org.Ptr()[u]; } flops += _width; CSROrdinal _collisionH = _widthH - _max_deg; max_widthComp = (max_widthComp > _widthComp) ? max_widthComp : _widthComp; max_widthH = (max_widthH > _widthH) ? max_widthH : _widthH; max_width = (max_width > _width) ? max_width : _width; max_collisions = (max_collisions > _collisionH) ? max_collisions : _collisionH; } return UpperBounds<CSROrdinal, Value>(max_widthComp, max_widthH, max_width, max_collisions, max_degA, flops); } #endif
threading.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #ifndef LIGHTGBM_UTILS_THREADING_H_ #define LIGHTGBM_UTILS_THREADING_H_ #include <algorithm> #include <functional> #include <vector> #include <LightGBM/meta.h> #include <LightGBM/utils/common.h> #include <LightGBM/utils/openmp_wrapper.h> namespace LightGBM { class Threading { public: template <typename INDEX_T> static inline void BlockInfo(INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { int num_threads = OMP_NUM_THREADS(); BlockInfo<INDEX_T>(num_threads, cnt, min_cnt_per_block, out_nblock, block_size); } template <typename INDEX_T> static inline void BlockInfo(int num_threads, INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { *out_nblock = std::min<int>( num_threads, static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block)); if (*out_nblock > 1) { *block_size = SIZE_ALIGNED((cnt + (*out_nblock) - 1) / (*out_nblock)); } else { *block_size = cnt; } } template <typename INDEX_T> static inline void BlockInfoForceSize(int num_threads, INDEX_T cnt, INDEX_T min_cnt_per_block, int* out_nblock, INDEX_T* block_size) { *out_nblock = std::min<int>( num_threads, static_cast<int>((cnt + min_cnt_per_block - 1) / min_cnt_per_block)); if (*out_nblock > 1) { *block_size = (cnt + (*out_nblock) - 1) / (*out_nblock); // force the block size to the times of min_cnt_per_block *block_size = (*block_size + min_cnt_per_block - 1) / min_cnt_per_block * min_cnt_per_block; } else { *block_size = cnt; } } template <typename INDEX_T> static inline int For( INDEX_T start, INDEX_T end, INDEX_T min_block_size, const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) { int n_block = 1; INDEX_T num_inner = end - start; BlockInfo<INDEX_T>(end - start, min_block_size, &n_block, &num_inner); OMP_INIT_EX(); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < n_block; ++i) { OMP_LOOP_EX_BEGIN(); INDEX_T inner_start = start + num_inner * i; INDEX_T inner_end = std::min(end, inner_start + num_inner); inner_fun(i, inner_start, inner_end); OMP_LOOP_EX_END(); } OMP_THROW_EX(); return n_block; } }; template <typename INDEX_T, bool TWO_BUFFER> class ParallelPartitionRunner { public: ParallelPartitionRunner(INDEX_T num_data, INDEX_T min_block_size) : min_block_size_(min_block_size) { num_threads_ = OMP_NUM_THREADS(); left_.resize(num_data); if (TWO_BUFFER) { right_.resize(num_data); } offsets_.resize(num_threads_); left_cnts_.resize(num_threads_); right_cnts_.resize(num_threads_); left_write_pos_.resize(num_threads_); right_write_pos_.resize(num_threads_); } ~ParallelPartitionRunner() {} void ReSize(INDEX_T num_data) { left_.resize(num_data); if (TWO_BUFFER) { right_.resize(num_data); } } template<bool FORCE_SIZE> INDEX_T Run( INDEX_T cnt, const std::function<INDEX_T(int, INDEX_T, INDEX_T, INDEX_T*, INDEX_T*)>& func, INDEX_T* out) { int nblock = 1; INDEX_T inner_size = cnt; if (FORCE_SIZE) { Threading::BlockInfoForceSize<INDEX_T>(num_threads_, cnt, min_block_size_, &nblock, &inner_size); } else { Threading::BlockInfo<INDEX_T>(num_threads_, cnt, min_block_size_, &nblock, &inner_size); } OMP_INIT_EX(); #pragma omp parallel for schedule(static, 1) num_threads(num_threads_) for (int i = 0; i < nblock; ++i) { OMP_LOOP_EX_BEGIN(); INDEX_T cur_start = i * inner_size; INDEX_T cur_cnt = std::min(inner_size, cnt - cur_start); offsets_[i] = cur_start; if (cur_cnt <= 0) { left_cnts_[i] = 0; right_cnts_[i] = 0; continue; } auto left_ptr = left_.data() + cur_start; INDEX_T* right_ptr = nullptr; if (TWO_BUFFER) { right_ptr = right_.data() + cur_start; } // split data inner, reduce the times of function called INDEX_T cur_left_count = func(i, cur_start, cur_cnt, left_ptr, right_ptr); if (!TWO_BUFFER) { // reverse for one buffer std::reverse(left_ptr + cur_left_count, left_ptr + cur_cnt); } left_cnts_[i] = cur_left_count; right_cnts_[i] = cur_cnt - cur_left_count; OMP_LOOP_EX_END(); } OMP_THROW_EX(); left_write_pos_[0] = 0; right_write_pos_[0] = 0; for (int i = 1; i < nblock; ++i) { left_write_pos_[i] = left_write_pos_[i - 1] + left_cnts_[i - 1]; right_write_pos_[i] = right_write_pos_[i - 1] + right_cnts_[i - 1]; } data_size_t left_cnt = left_write_pos_[nblock - 1] + left_cnts_[nblock - 1]; auto right_start = out + left_cnt; #pragma omp parallel for schedule(static, 1) num_threads(num_threads_) for (int i = 0; i < nblock; ++i) { std::copy_n(left_.data() + offsets_[i], left_cnts_[i], out + left_write_pos_[i]); if (TWO_BUFFER) { std::copy_n(right_.data() + offsets_[i], right_cnts_[i], right_start + right_write_pos_[i]); } else { std::copy_n(left_.data() + offsets_[i] + left_cnts_[i], right_cnts_[i], right_start + right_write_pos_[i]); } } return left_cnt; } private: int num_threads_; INDEX_T min_block_size_; std::vector<INDEX_T> left_; std::vector<INDEX_T> right_; std::vector<INDEX_T> offsets_; std::vector<INDEX_T> left_cnts_; std::vector<INDEX_T> right_cnts_; std::vector<INDEX_T> left_write_pos_; std::vector<INDEX_T> right_write_pos_; }; } // namespace LightGBM #endif // LightGBM_UTILS_THREADING_H_
rose_Stress-1.c
//#include <float.h> //#include <math.h> #define MIN(a, b) ( (a < b) ? a : b) #define MAX(a, b) ( (a > b) ? a : b) #include "omp.h" typedef double real8; void StressCheckEpsFail(real8 *newSxx,real8 *newSyy,real8 *newSzz,real8 *newTxy,real8 *newTxz,real8 *newTyz,real8 *eps,real8 eps_failure_model,const int *zoneset,int length) { int i; int index; #pragma omp parallel for private (index,i) firstprivate (eps_failure_model,length) for (i = 0; i <= length - 1; i += 1) { index = zoneset[i]; if (eps[zoneset[i]] > eps_failure_model) { newSxx[i] = 0.0; newSyy[i] = 0.0; newSzz[i] = 0.0; newTxy[i] = 0.0; newTxz[i] = 0.0; newTyz[i] = 0.0; eps[zoneset[i]] = eps_failure_model * 1.01; } } } void StressStrainWork(real8 *deltz,real8 *delts,const real8 *newSxx,const real8 *newSyy,const real8 *newSzz,const real8 *newTxy,const real8 *newTxz,const real8 *newTyz,const real8 *sxx,const real8 *syy,const real8 *txy,const real8 *txz,const real8 *tyz,const real8 *dxx,const real8 *dyy,const real8 *dzz,const real8 *dxy,const real8 *dxz,const real8 *dyz,real8 deltaTime,const int *zoneset,const real8 *vc,const real8 *vnewc,int length) { int i; int index; real8 quarterDelta = 0.25 * deltaTime; real8 szz; #pragma omp parallel for private (index,szz,i) firstprivate (length,quarterDelta) for (i = 0; i <= length - 1; i += 1) { index = zoneset[i]; szz = -sxx[zoneset[i]] - syy[zoneset[i]]; deltz[zoneset[i]] += quarterDelta * (vnewc[i] + vc[i]) * (dxx[zoneset[i]] * (sxx[zoneset[i]] + newSxx[i]) + dyy[zoneset[i]] * (syy[zoneset[i]] + newSyy[i]) + dzz[zoneset[i]] * (szz + newSzz[i]) + 2. * dxy[zoneset[i]] * (txy[zoneset[i]] + newTxy[i]) + 2. * dxz[zoneset[i]] * (txz[zoneset[i]] + newTxz[i]) + 2. * dyz[zoneset[i]] * (tyz[zoneset[i]] + newTyz[i])); delts[i] += quarterDelta * (vnewc[i] + vc[i]) * (dxx[zoneset[i]] * sxx[zoneset[i]] + dyy[zoneset[i]] * syy[zoneset[i]] + dzz[zoneset[i]] * szz + 2. * dxy[zoneset[i]] * txy[zoneset[i]] + 2. * dxz[zoneset[i]] * txz[zoneset[i]] + 2. * dyz[zoneset[i]] * tyz[zoneset[i]]); } } void StressStrainHeat(const real8 *deltz,real8 *deltzh,real8 *deltrh,const real8 *shearMod,const real8 *shearRatio,const real8 *shearDer,const real8 *newSxx,const real8 *newSyy,const real8 *newSzz,const real8 *newTxy,const real8 *newTxz,const real8 *newTyz,const real8 *sxx,const real8 *syy,const real8 *txy,const real8 *txz,const real8 *tyz,real8 deltaTime,const int *zoneset,const real8 *vc,const real8 *vnewc,int length) { real8 shearr; real8 sheari; real8 avgMod; int nz; int i; /* Quiet the compiler - unused argument */ deltaTime = deltaTime; #pragma omp parallel for private (shearr,sheari,avgMod,nz,i) firstprivate (length) for (i = 0; i <= length - 1; i += 1) { nz = zoneset[i]; shearr = 0.5 * shearRatio[i]; if (shearMod[zoneset[i]] > 0.) { sheari = 0.5 / shearMod[zoneset[i]]; deltrh[zoneset[i]] = .25 * (vnewc[i] + vc[i]) * ((newSxx[i] * sheari - sxx[zoneset[i]] * shearr) * (sxx[zoneset[i]] + newSxx[i]) + (newSyy[i] * sheari - syy[zoneset[i]] * shearr) * (syy[zoneset[i]] + newSyy[i]) + (newSzz[i] * sheari + (syy[zoneset[i]] + sxx[zoneset[i]]) * shearr) * (newSzz[i] - sxx[zoneset[i]] - syy[zoneset[i]]) + 2. * (newTxy[i] * sheari - txy[zoneset[i]] * shearr) * (txy[zoneset[i]] + newTxy[i]) + 2. * (newTxz[i] * sheari - txz[zoneset[i]] * shearr) * (txz[zoneset[i]] + newTxz[i]) + 2. * (newTyz[i] * sheari - tyz[zoneset[i]] * shearr) * (tyz[zoneset[i]] + newTyz[i])); } else { deltrh[zoneset[i]] = - .25 * (vnewc[i] + vc[i]) * (sxx[zoneset[i]] * (sxx[zoneset[i]] + newSxx[i]) + syy[zoneset[i]] * (syy[zoneset[i]] + newSyy[i]) - (syy[zoneset[i]] + sxx[zoneset[i]]) * (newSzz[i] - sxx[zoneset[i]] - syy[zoneset[i]]) + 2. * txy[zoneset[i]] * (txy[zoneset[i]] + newTxy[i]) + 2. * txz[zoneset[i]] * (txz[zoneset[i]] + newTxz[i]) + 2. * tyz[zoneset[i]] * (tyz[zoneset[i]] + newTyz[i])) * shearr; } deltzh[zoneset[i]] = deltz[zoneset[i]] - deltrh[zoneset[i]]; avgMod = 0.5 * shearMod[zoneset[i]]; if (shearRatio[i] > 0.0) avgMod = avgMod + 0.5 / shearRatio[i]; if (avgMod > 0.0) deltrh[zoneset[i]] = shearDer[i] * deltrh[zoneset[i]] / avgMod; else deltrh[zoneset[i]] = 0.0; } }
offload_table.h
/* Copyright (c) 2014-2016 Intel Corporation. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*! \file \brief Function and Variable tables used by the runtime library */ #ifndef OFFLOAD_TABLE_H_INCLUDED #define OFFLOAD_TABLE_H_INCLUDED #include "offload_util.h" #define OFFLOAD_VERSION_16 1600 #define OFFLOAD_VERSION_17 1700 // Template representing double linked list of tables template <typename T> class TableList { public: // table type typedef T Table; // List node struct Node { Table table; Node* prev; Node* next; }; public: explicit TableList(Node *node = 0) : m_head(node) {} void add_table(Node *node) { m_lock.lock(); if (m_head != 0) { node->next = m_head; m_head->prev = node; } m_head = node; m_lock.unlock(); } void remove_table(Node *node) { if (node->next != 0) { node->next->prev = node->prev; } if (node->prev != 0) { node->prev->next = node->next; } if (m_head == node) { m_head = node->next; } } protected: Node* m_head; mutex_t m_lock; }; // Function lookup table. struct FuncTable { //! Function table entry /*! This table contains functions created from offload regions. */ /*! Each entry consists of a pointer to the function's "key" and the function address. */ /*! Each shared library or executable may contain one such table. */ /*! The end of the table is marked with an entry whose name field has value -1. */ struct Entry { const char* name; //!< Name of the function void* func; //!< Address of the function }; // entries const Entry *entries; // max name length int64_t max_name_len; }; // Function table class DLL_LOCAL FuncList : public TableList<FuncTable> { public: explicit FuncList(Node *node = 0) : TableList<Table>(node), m_max_name_len(-1) {} // add table to the list void add_table(Node *node) { // recalculate max function name length m_max_name_len = -1; // add table TableList<Table>::add_table(node); } // find function address for the given name const void* find_addr(const char *name); // find function name for the given address const char* find_name(const void *addr); // max name length from all tables in the list int64_t max_name_length(void); // debug dump void dump(void); private: // max name length within from all tables int64_t m_max_name_len; }; #define VAR_ALLOC_TYPE uint64_t #define OPENMP_IMPLICIT 1 // Compiler promoted openmp declare var // due to implicit use without openmp declare #define OPENMP_LINK 2 // Openmp link clause in openmp declare #define IS_OPENMP_IMPLICIT(var_alloc_type) (var_alloc_type & 1) #define IS_OPENMP_LINK(var_alloc_type) (var_alloc_type & 2) #define IS_OPENMP_IMPLICIT_OR_LINK(var_alloc_type) (var_alloc_type & 3) // Table entry for static variables struct VarTable { //! Variable table entry /*! This table contains statically allocated variables marked with __declspec(target(mic) or #pragma omp declare target. */ /*! Each entry consists of a pointer to the variable's "key", the variable address and its size in bytes. */ /*! Because memory allocation is done from the host, the MIC table does not need the size of the variable. */ /*! Padding to make the table entry size a power of 2 is necessary to avoid "holes" between table contributions from different object files on Windows when debug information is specified with /Zi. */ struct Entry { const char* name; //!< Name of the variable void* addr; //!< Address of the variable #if HOST_LIBRARY VAR_ALLOC_TYPE var_alloc_type; uint64_t size; #endif }; // Table terminated by an entry with name == -1 const Entry *entries; }; // List of var tables class DLL_LOCAL VarList : public TableList<VarTable> { public: VarList() : TableList<Table>() {} // debug dump void dump(); public: Node * get_head() { return m_head; } public: // Entry representation in a copy buffer struct BufEntry { intptr_t name; intptr_t addr; }; // Calculate the number of elements in the table and // returns the size of buffer for the table int64_t table_size(int64_t &nelems); // Copy table contents to given buffer. It is supposed to be large // enough to hold all elements as string table. void table_copy(void *buf, int64_t nelems); // Patch name offsets in a table after it's been copied to other side static void table_patch_names(void *buf, int64_t nelems); }; DLL_LOCAL extern FuncList __offload_entries; DLL_LOCAL extern FuncList __offload_funcs; DLL_LOCAL extern VarList __offload_vars; // Section names where the lookup tables are stored #ifdef TARGET_WINNT #define OFFLOAD_ENTRY_TABLE_SECTION_START ".OffloadEntryTable$a" #define OFFLOAD_ENTRY_TABLE_SECTION_END ".OffloadEntryTable$z" #define OFFLOAD_FUNC_TABLE_SECTION_START ".OffloadFuncTable$a" #define OFFLOAD_FUNC_TABLE_SECTION_END ".OffloadFuncTable$z" #define OFFLOAD_VAR_TABLE_SECTION_START ".OffloadVarTable$a" #define OFFLOAD_VAR_TABLE_SECTION_END ".OffloadVarTable$z" #define OFFLOAD_CRTINIT_SECTION_START ".CRT$XCT" #pragma section(OFFLOAD_CRTINIT_SECTION_START, read) #else // TARGET_WINNT #define OFFLOAD_ENTRY_TABLE_SECTION_START ".OffloadEntryTable." #define OFFLOAD_ENTRY_TABLE_SECTION_END ".OffloadEntryTable." #define OFFLOAD_FUNC_TABLE_SECTION_START ".OffloadFuncTable." #define OFFLOAD_FUNC_TABLE_SECTION_END ".OffloadFuncTable." #define OFFLOAD_VAR_TABLE_SECTION_START ".OffloadVarTable." #define OFFLOAD_VAR_TABLE_SECTION_END ".OffloadVarTable." #endif // TARGET_WINNT #pragma section(OFFLOAD_ENTRY_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_ENTRY_TABLE_SECTION_END, read, write) #pragma section(OFFLOAD_FUNC_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_FUNC_TABLE_SECTION_END, read, write) #pragma section(OFFLOAD_VAR_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_VAR_TABLE_SECTION_END, read, write) // Set library version extern "C" void __offload_set_version(int v); // register/unregister given tables extern "C" void __offload_register_tables( FuncList::Node *entry_table, FuncList::Node *func_table, VarList::Node *var_table ); extern "C" void __offload_unregister_tables( FuncList::Node *entry_table, FuncList::Node *func_table, VarList::Node *var_table ); #ifdef MYO_SUPPORT #include <myotypes.h> #include <myoimpl.h> #include <myo.h> #ifdef TARGET_WINNT #define MYO_TABLE_END_MARKER() reinterpret_cast<const char*>(-1) #else // TARGET_WINNT #define MYO_TABLE_END_MARKER() reinterpret_cast<const char*>(0) #endif // TARGET_WINNT // Host and Target-side MYO shared variable table entry layout typedef MyoiSharedVarEntry SharedTableEntry; #if HOST_LIBRARY // Host-side MYO function table entry layout typedef struct { //! Function Name const char *funcName; //! Function Address void *funcAddr; //! Local Thunk Address void *localThunkAddr; #ifdef TARGET_WINNT // Dummy to pad up to 32 bytes void *dummy; #endif // TARGET_WINNT } FptrTableEntry; // Host-side MYO init routine table entry layout typedef struct { #ifdef TARGET_WINNT // Dummy to pad up to 16 bytes // Function Name const char *funcName; #endif // TARGET_WINNT void (*func)(MyoArena); } InitTableEntry; #else // HOST_LIBRARY // Target-side MYO function table entry layout typedef MyoiTargetSharedFptrEntry FptrTableEntry; // Target-side MYO init routine table entry layout struct InitTableEntry { void (*func)(void); }; #endif // HOST_LIBRARY #ifdef TARGET_WINNT #define OFFLOAD_MYO_SHARED_TABLE_SECTION_START ".MyoSharedTable$a" #define OFFLOAD_MYO_SHARED_TABLE_SECTION_END ".MyoSharedTable$z" #define OFFLOAD_MYO_SHARED_VTABLE_SECTION_START ".MyoSharedVTable$a" #define OFFLOAD_MYO_SHARED_VTABLE_SECTION_END ".MyoSharedVTable$z" #define OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_START ".MyoSharedInitTable$a" #define OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_END ".MyoSharedInitTable$z" #define OFFLOAD_MYO_FPTR_TABLE_SECTION_START ".MyoFptrTable$a" #define OFFLOAD_MYO_FPTR_TABLE_SECTION_END ".MyoFptrTable$z" #else // TARGET_WINNT #define OFFLOAD_MYO_SHARED_TABLE_SECTION_START ".MyoSharedTable." #define OFFLOAD_MYO_SHARED_TABLE_SECTION_END ".MyoSharedTable." #define OFFLOAD_MYO_SHARED_VTABLE_SECTION_START ".MyoSharedVTable." #define OFFLOAD_MYO_SHARED_VTABLE_SECTION_END ".MyoSharedVTable." #define OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_START ".MyoSharedInitTable." #define OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_END ".MyoSharedInitTable." #define OFFLOAD_MYO_FPTR_TABLE_SECTION_START ".MyoFptrTable." #define OFFLOAD_MYO_FPTR_TABLE_SECTION_END ".MyoFptrTable." #endif // TARGET_WINNT #pragma section(OFFLOAD_MYO_SHARED_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_MYO_SHARED_TABLE_SECTION_END, read, write) #pragma section(OFFLOAD_MYO_SHARED_VTABLE_SECTION_START, read, write) #pragma section(OFFLOAD_MYO_SHARED_VTABLE_SECTION_END, read, write) #pragma section(OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_MYO_SHARED_INIT_TABLE_SECTION_END, read, write) #pragma section(OFFLOAD_MYO_FPTR_TABLE_SECTION_START, read, write) #pragma section(OFFLOAD_MYO_FPTR_TABLE_SECTION_END, read, write) // List of MYO shared variable tables struct MYOVarTable { typedef SharedTableEntry Entry; const Entry *entries; }; class MYOVarTableList : public TableList<MYOVarTable> { public: MYOVarTableList() : TableList<Table>() {} // add table to the list void add_table(Node *node) { // add table TableList<Table>::add_table(node); } // debug dump void dump(void); // check if any shared variables bool is_empty(); // process the table contents for ordinary variables void process(); // process the table contents for vtable objects void process_vtable(); }; // List of MYO shared function tables struct MYOFuncTable { typedef FptrTableEntry Entry; const Entry *entries; }; class MYOFuncTableList : public TableList<MYOFuncTable> { public: MYOFuncTableList() : TableList<Table>() {} // add table to the list void add_table(Node *node) { // add table TableList<Table>::add_table(node); } // debug dump void dump(void); // check if any shared functions bool is_empty(); // process the table contents void process(); }; // List of MYO shared variable initialization routine tables struct MYOInitTable { typedef InitTableEntry Entry; const Entry *entries; }; class MYOInitTableList : public TableList<MYOInitTable> { public: MYOInitTableList() : TableList<Table>() {} // add table to the list void add_table(Node *node) { // add table TableList<Table>::add_table(node); } // debug dump void dump(void); // check if any init routines bool is_empty(); // process the table contents void process(); }; extern MYOVarTableList __offload_myo_var_tables; extern MYOVarTableList __offload_myo_vtable_tables; extern MYOFuncTableList __offload_myo_func_tables; extern MYOInitTableList __offload_myo_init_tables; extern "C" void __offload_myoRegisterTables1( MYOInitTableList::Node *init_table, MYOVarTableList::Node *shared_table, MYOVarTableList::Node *shared_vtable, MYOFuncTableList::Node *fptr_table ); extern "C" void __offload_myoRemoveTables( MYOInitTableList::Node *init_table, MYOVarTableList::Node *shared_table, MYOVarTableList::Node *shared_vtable, MYOFuncTableList::Node *fptr_table ); #endif // MYO_SUPPORT #endif // OFFLOAD_TABLE_H_INCLUDED
schedule-claused.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(int argc, char **argv) { int i, n = 16,chunk, a[n],suma=0; if(argc < 2) { fprintf(stderr,"\nFalta chunk \n"); exit(-1); } chunk = atoi(argv[1]); for (i=0; i<n; i++) a[i] = i; #pragma omp parallel for firstprivate(suma) \ lastprivate(suma) schedule(dynamic,chunk) for (i=0; i<n; i++) { suma = suma + a[i]; printf(" thread %d suma a[%d] suma=%d \n", omp_get_thread_num(),i,suma); } printf("Fuera de 'parallel for' suma=%d\n",suma); }
calculate_embedded_nodal_variable_from_skin_process.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Ruben Zorrilla // // #if !defined(KRATOS_CALCULATE_EMBEDDED_VARIABLE_FROM_SKIN_PROCESS_INCLUDED ) #define KRATOS_CALCULATE_EMBEDDED_VARIABLE_FROM_SKIN_PROCESS_INCLUDED // System includes // External includes // Project includes #include "containers/model.h" #include "includes/define.h" #include "includes/key_hash.h" #include "includes/kratos_flags.h" #include "factories/linear_solver_factory.h" #include "elements/embedded_nodal_variable_calculation_element_simplex.h" #include "processes/process.h" #include "processes/find_intersected_geometrical_objects_process.h" #include "solving_strategies/builder_and_solvers/residualbased_block_builder_and_solver.h" #include "solving_strategies/schemes/residualbased_incrementalupdate_static_scheme.h" #include "solving_strategies/strategies/residualbased_linear_strategy.h" #include "utilities/intersection_utilities.h" #include "utilities/variable_utils.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ template< class TVarType > class EmbeddedNodalVariableFromSkinTypeHelperClass { public: ///@name Type Definitions ///@{ ///@} ///@name Pointer Definitions /// Pointer definition of EmbeddedNodalVariableFromSkinTypeHelperClass KRATOS_CLASS_POINTER_DEFINITION(EmbeddedNodalVariableFromSkinTypeHelperClass); ///@} ///@name Life Cycle ///@{ ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Get the Unknown Variable object * This method returns a reference to the unknown variable. For double embedded nodal * variables this is a reference to NODAL_MAUX. In case of array type embedded nodal * variables, it returns a reference to NODAL_VAUX. These are the variables used when * solving the embedded nodal values least squares minimization problem. * @return const Variable<TVarType>& Reference to the unknown variable */ static inline const Variable<TVarType> &GetUnknownVariable(); /** * @brief Add the unknown variable to a model part * This method adds the unknown variable to the model part of interest. * @param rModelPart Reference to the model part to which the variable is added */ static inline void AddUnknownVariable(ModelPart &rModelPart); /** * @brief Add the unknown variable DOFs to a model part * This method adds the unknown variable DOFs to the model part of interest * @param rModelPart Reference to the model part to which the variable DOFs are added */ static inline void AddUnknownVariableDofs(ModelPart &rModelPart); ///@} }; template <> inline const Variable<double> &EmbeddedNodalVariableFromSkinTypeHelperClass<double>::GetUnknownVariable() { return KratosComponents<Variable<double>>::Get("NODAL_MAUX"); } template <> inline const Variable<array_1d<double,3>> &EmbeddedNodalVariableFromSkinTypeHelperClass<array_1d<double,3>>::GetUnknownVariable() { return KratosComponents<Variable<array_1d<double, 3>>>::Get("NODAL_VAUX"); } template <> inline void EmbeddedNodalVariableFromSkinTypeHelperClass<double>::AddUnknownVariable(ModelPart &rModelPart) { rModelPart.AddNodalSolutionStepVariable(NODAL_MAUX); } template <> inline void EmbeddedNodalVariableFromSkinTypeHelperClass<array_1d<double,3>>::AddUnknownVariable(ModelPart &rModelPart) { rModelPart.AddNodalSolutionStepVariable(NODAL_VAUX); } template <> inline void EmbeddedNodalVariableFromSkinTypeHelperClass<double>::AddUnknownVariableDofs(ModelPart &rModelPart) { VariableUtils().AddDof(NODAL_MAUX, rModelPart); } template <> inline void EmbeddedNodalVariableFromSkinTypeHelperClass<array_1d<double, 3>>::AddUnknownVariableDofs(ModelPart &rModelPart) { VariableUtils().AddDof(NODAL_VAUX_X, rModelPart); VariableUtils().AddDof(NODAL_VAUX_Y, rModelPart); VariableUtils().AddDof(NODAL_VAUX_Z, rModelPart); } template <class TVarType, class TSparseSpace, class TDenseSpace, class TLinearSolver> class CalculateEmbeddedNodalVariableFromSkinProcess : public Process { public: ///@name Type Definitions ///@{ typedef typename TLinearSolver::Pointer LinearSolverPointerType; typedef typename Scheme<TSparseSpace,TDenseSpace>::Pointer SchemePointerType; typedef typename BuilderAndSolver<TSparseSpace,TDenseSpace,TLinearSolver>::Pointer BuilderSolverPointerType; typedef typename SolvingStrategy<TSparseSpace, TDenseSpace, TLinearSolver>::UniquePointer SolvingStrategyPointerType; typedef typename FindIntersectedGeometricalObjectsProcess::UniquePointer FindIntersectedGeometricalObjectsProcessPointerType; typedef std::unordered_set<std::pair<std::size_t, std::size_t>, PairHasher<std::size_t, std::size_t>, PairComparor<std::size_t, std::size_t>> EdgesSetType; ///@} ///@name Pointer Definitions /// Pointer definition of CalculateEmbeddedNodalVariableFromSkinProcess KRATOS_CLASS_POINTER_DEFINITION(CalculateEmbeddedNodalVariableFromSkinProcess); ///@} ///@name Life Cycle ///@{ /** * @brief Get the Default Settings object * This method returns the default parameters for this proces. * Note that it is required to be static since it is called during * the construction of the object so no instantation exists yet. * @return Parameters Default parameters json string */ static Parameters GetDefaultSettings() { Parameters default_settings(R"( { "base_model_part_name": "", "skin_model_part_name": "", "skin_variable_name": "", "embedded_nodal_variable_name": "", "buffer_position": 0, "gradient_penalty_coefficient": 0.0, "aux_model_part_name": "IntersectedElementsModelPart", "linear_solver_settings": { "preconditioner_type": "amg", "solver_type": "amgcl", "smoother_type": "ilu0", "krylov_type": "cg", "max_iteration": 1000, "verbosity": 0, "tolerance": 1e-8, "scaling": false, "block_size": 1, "use_block_matrices_if_possible": true } } )"); return default_settings; } /** * @brief Construct a new Calculate Embedded Nodal Variable From Skin Process object * Constructor with model and json settings * @param rModel Model container * @param rSettings Settings json string */ CalculateEmbeddedNodalVariableFromSkinProcess( Model &rModel, Parameters rSettings) : CalculateEmbeddedNodalVariableFromSkinProcess( rModel.GetModelPart(rSettings["base_model_part_name"].GetString()), rModel.GetModelPart(rSettings["skin_model_part_name"].GetString()), [] (Parameters x) -> Parameters {x.ValidateAndAssignDefaults(GetDefaultSettings()); return x;} (rSettings)) { } /** * @brief Construct a new Calculate Embedded Nodal Variable From Skin Process object * * @param rBaseModelPart Background mesh model part reference * @param rSkinModelPart Embedded skin model part reference * @param LinearSolverSettings Linear solver json settings * @param rSkinVariable Skin variable to take the values from * @param rEmbeddedNodalVariable Background mesh destination variable * @param LevelSetType Level set type (continuous or discontinuous) * @param BufferPosition Position in the buffer to take and save the values * @param AuxPartName Auxiliary intersections model part name */ CalculateEmbeddedNodalVariableFromSkinProcess( ModelPart &rBaseModelPart, ModelPart &rSkinModelPart, Parameters LinearSolverSettings, const Variable<TVarType> &rSkinVariable, const Variable<TVarType> &rEmbeddedNodalVariable, const double GradientPenaltyCoefficient = 0.0, const unsigned int BufferPosition = 0, const std::string AuxPartName = "IntersectedElementsModelPart") : Process(), mBufferPosition(BufferPosition), mAuxModelPartName(AuxPartName), mGradientPenaltyCoefficient(GradientPenaltyCoefficient), mrBaseModelPart(rBaseModelPart), mrSkinModelPart(rSkinModelPart), mrSkinVariable(rSkinVariable), mrEmbeddedNodalVariable(rEmbeddedNodalVariable) { KRATOS_TRY // Check the process settings KRATOS_ERROR_IF(!(mBufferPosition < rBaseModelPart.GetBufferSize())) << "Asked for buffer position " << mBufferPosition << " buf base model part buffer size is " << rBaseModelPart.GetBufferSize() << std::endl; KRATOS_ERROR_IF(!(mBufferPosition < rSkinModelPart.GetBufferSize())) << "Asked for buffer position " << mBufferPosition << " buf skin model part buffer size is " << rSkinModelPart.GetBufferSize() << std::endl; // Check that there is at least one element and node in the model int n_loc_mesh_nodes = mrBaseModelPart.GetCommunicator().pLocalMesh()->NumberOfNodes(); int n_loc_mesh_elements = mrBaseModelPart.GetCommunicator().pLocalMesh()->NumberOfElements(); KRATOS_ERROR_IF(mrBaseModelPart.GetCommunicator().GetDataCommunicator().SumAll(n_loc_mesh_nodes) == 0) << "The base model part has no nodes." << std::endl; KRATOS_ERROR_IF(mrBaseModelPart.GetCommunicator().GetDataCommunicator().SumAll(n_loc_mesh_elements) == 0) << "The base model Part has no elements." << std::endl; // Check that the base model part is conformed by simplex elements const auto &r_aux_geom = (mrBaseModelPart.ElementsBegin())->GetGeometry(); const unsigned int dim = r_aux_geom.Dimension(); if(dim == 2){ KRATOS_ERROR_IF(r_aux_geom.GetGeometryFamily() != GeometryData::Kratos_Triangle) << "In 2D the element type is expected to be a triangle." << std::endl; } else if(dim == 3) { KRATOS_ERROR_IF(r_aux_geom.GetGeometryFamily() != GeometryData::Kratos_Tetrahedra) << "In 3D the element type is expected to be a tetrahedron" << std::endl; } else { KRATOS_ERROR << "Wrong geometry Dimension(). Expected 2 or 3 and obtained: " << dim; } // Construct the linear solver pointer LinearSolverFactory<TSparseSpace, TDenseSpace> linear_solver_factory; mpLinearSolver = linear_solver_factory.Create(LinearSolverSettings); KRATOS_CATCH("") } /// Destructor. ~CalculateEmbeddedNodalVariableFromSkinProcess() override { Model& current_model = mrBaseModelPart.GetModel(); if(current_model.HasModelPart(mAuxModelPartName)) { current_model.DeleteModelPart(mAuxModelPartName); } }; ///@} ///@name Operators ///@{ void operator()() { Execute(); } ///@} ///@name Operations ///@{ ModelPart &GetIntersectedEdgesModelPart() const { Model &current_model = mrBaseModelPart.GetModel(); return current_model.GetModelPart(mAuxModelPartName); } void Execute() override { KRATOS_TRY; // Generate an auxilary model part and populate it by elements of type DistanceCalculationElementSimplex this->GenerateIntersectedEdgesElementsModelPart(); // Set the linear strategy to solve the regression problem this->SetLinearStrategy(); // Solve the regression problem mpSolvingStrategy->Solve(); // Copy the obtained values from the unknown variable to the user-defined variable this->SetObtainedEmbeddedNodalValues(); KRATOS_CATCH("") } virtual void Clear() { Model& current_model = mrBaseModelPart.GetModel(); ModelPart& r_intersected_edges_model_part = current_model.GetModelPart( mAuxModelPartName ); r_intersected_edges_model_part.Nodes().clear(); r_intersected_edges_model_part.Elements().clear(); r_intersected_edges_model_part.Conditions().clear(); mpSolvingStrategy->Clear(); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "CalculateEmbeddedNodalVariableFromSkinProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "CalculateEmbeddedNodalVariableFromSkinProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ const unsigned int mBufferPosition; const std::string mAuxModelPartName; const double mGradientPenaltyCoefficient; ModelPart& mrBaseModelPart; ModelPart& mrSkinModelPart; const Variable<TVarType> &mrSkinVariable; const Variable<TVarType> &mrEmbeddedNodalVariable; LinearSolverPointerType mpLinearSolver = nullptr; SolvingStrategyPointerType mpSolvingStrategy = nullptr; FindIntersectedGeometricalObjectsProcessPointerType mpFindIntersectedGeometricalObjectsProcess; ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ virtual void GenerateIntersectedEdgesElementsModelPart() { KRATOS_TRY // Compute element intersections this->CalculateIntersections(); Model& current_model = mrBaseModelPart.GetModel(); if(current_model.HasModelPart(mAuxModelPartName)) { current_model.DeleteModelPart(mAuxModelPartName); } // Generate the auxiliary model part ModelPart& r_int_elems_model_part = current_model.CreateModelPart(mAuxModelPartName); r_int_elems_model_part.Nodes().clear(); r_int_elems_model_part.Elements().clear(); r_int_elems_model_part.Conditions().clear(); r_int_elems_model_part.SetBufferSize(1); r_int_elems_model_part.CreateNewProperties(0, 0); // Set the gradient penalty coefficient in the auxiliary model part process info r_int_elems_model_part.GetProcessInfo()[GRADIENT_PENALTY_COEFFICIENT] = mGradientPenaltyCoefficient; // Add the minimization problem auxiliary variables this->AddIntersectedElementsVariables(r_int_elems_model_part); // Add intersected elements this->AddIntersectedElementsModelPartElements(r_int_elems_model_part); // Add DOFs to intersected elements model part this->AddIntersectedElementsModelPartDOFs(r_int_elems_model_part); KRATOS_CATCH("") } void SetObtainedEmbeddedNodalValues() const { const auto &rUnknownVariable = EmbeddedNodalVariableFromSkinTypeHelperClass<TVarType>::GetUnknownVariable(); const auto &r_int_elems_model_part = (mrBaseModelPart.GetModel()).GetModelPart(mAuxModelPartName); #pragma omp parallel for for (int i_node = 0; i_node < static_cast<int>(r_int_elems_model_part.NumberOfNodes()); ++i_node) { const auto it_node = r_int_elems_model_part.NodesBegin() + i_node; auto &r_emb_nod_val = (mrBaseModelPart.GetNode(it_node->Id())).FastGetSolutionStepValue(mrEmbeddedNodalVariable, mBufferPosition); r_emb_nod_val = it_node->FastGetSolutionStepValue(rUnknownVariable); } } inline void AddIntersectedElementsVariables(ModelPart &rModelPart) const { EmbeddedNodalVariableFromSkinTypeHelperClass<TVarType>::AddUnknownVariable(rModelPart); } void AddIntersectedElementsModelPartDOFs(ModelPart &rModelPart) const { EmbeddedNodalVariableFromSkinTypeHelperClass<TVarType>::AddUnknownVariableDofs(rModelPart); } void AddIntersectedElementsModelPartElements(ModelPart &rModelPart) const { // Initialize the VISITED flag in the origin model part // It will be used to mark the nodes already added to the intersected elements model part VariableUtils().SetFlag(VISITED, false, mrBaseModelPart.Nodes()); // Initialize the INTERFACE flag in the origin model part // It will be used to mark the elements that have any intersection with the skin model part VariableUtils().SetFlag(INTERFACE, false, mrBaseModelPart.Elements()); // Create element edges map EdgesSetType edges_set; // Get the base model part intersections auto &r_int_obj_vect = mpFindIntersectedGeometricalObjectsProcess->GetIntersections(); // Get the unknown variable from Kratos components const auto &rUnknownVariable = EmbeddedNodalVariableFromSkinTypeHelperClass<TVarType>::GetUnknownVariable(); // Loop the base model part elements std::size_t new_elem_id = 1; for (unsigned int i_elem = 0; i_elem < mrBaseModelPart.NumberOfElements(); ++i_elem) { auto it_elem = mrBaseModelPart.ElementsBegin() + i_elem; // Check if the current element has intersections if (r_int_obj_vect[i_elem].size() != 0) { // Initialize the element values auto &r_geom = it_elem->GetGeometry(); const auto edges = r_geom.Edges(); // Loop the edges for (unsigned int i_edge = 0; i_edge < r_geom.EdgesNumber(); ++i_edge) { // Check if the current edge is already stored auto &r_i_edge_geom = edges[i_edge]; auto i_edge_pair = this->SetEdgePair(r_i_edge_geom); if (edges_set.find(i_edge_pair) == edges_set.end()) { // Initialize edge values double i_edge_d = 0.0; // Average normalized distance from lower id. node unsigned int n_int_obj = 0; // Number edge of intersecting entities TVarType i_edge_val = mrEmbeddedNodalVariable.Zero(); // Average edge variable value // Check the edge intersection against all the candidates for (auto &r_int_obj : r_int_obj_vect[i_elem]) { Point intersection_point; const bool is_intersected = this->ComputeEdgeIntersection( r_int_obj.GetGeometry(), r_i_edge_geom[0], r_i_edge_geom[1], intersection_point); // Compute the variable value in the intersection point if (is_intersected) { n_int_obj++; Vector int_obj_N; array_1d<double,3> local_coords; r_int_obj.GetGeometry().PointLocalCoordinates(local_coords, intersection_point); r_int_obj.GetGeometry().ShapeFunctionsValues(int_obj_N, local_coords); for (unsigned int i_node = 0; i_node < r_int_obj.GetGeometry().PointsNumber(); ++i_node) { i_edge_val += r_int_obj.GetGeometry()[i_node].FastGetSolutionStepValue(mrSkinVariable, mBufferPosition) * int_obj_N[i_node]; } i_edge_d += norm_2(intersection_point - r_i_edge_geom[0]) / r_i_edge_geom.Length(); } } // Check if the edge is intersected if (n_int_obj != 0) { // Flag the edge parent element if the edge is intersected by any entity it_elem->Set(INTERFACE, true); // Add the average edge value (there might exist cases in where // more than one geometry intersects the edge of interest). i_edge_d /= n_int_obj; i_edge_val /= n_int_obj; // If not added yet, add the edge nodes this->AddEdgeNodes(r_i_edge_geom, rModelPart); // Create a new element with the intersected edge geometry and fake properties auto p_element = Kratos::make_intrusive<EmbeddedNodalVariableCalculationElementSimplex<TVarType>>( new_elem_id, this->pSetEdgeElementGeometry(rModelPart, r_i_edge_geom, i_edge_pair), rModelPart.pGetProperties(0)); // Save the edge values in the new element p_element->SetValue(DISTANCE, i_edge_d); p_element->SetValue(rUnknownVariable, i_edge_val); // Update the id. counter new_elem_id++; // Add the new edge element to the hash map edges_set.insert(i_edge_pair); // Add the new edge element to the intersected elements model part rModelPart.Elements().push_back(p_element); } } } } } } void SetLinearStrategy() { // Create the linear strategy SchemePointerType p_scheme = Kratos::make_shared<ResidualBasedIncrementalUpdateStaticScheme<TSparseSpace, TDenseSpace>>(); bool calculate_norm_dx = false; bool calculate_reactions = false; bool reform_dof_at_each_iteration = false; BuilderSolverPointerType p_builder_and_solver = Kratos::make_shared<ResidualBasedBlockBuilderAndSolver<TSparseSpace, TDenseSpace, TLinearSolver>>(mpLinearSolver); Model &current_model = mrBaseModelPart.GetModel(); ModelPart &r_aux_model_part = current_model.GetModelPart(mAuxModelPartName); mpSolvingStrategy = Kratos::make_unique<ResidualBasedLinearStrategy<TSparseSpace, TDenseSpace, TLinearSolver>>( r_aux_model_part, p_scheme, mpLinearSolver, p_builder_and_solver, calculate_reactions, reform_dof_at_each_iteration, calculate_norm_dx); mpSolvingStrategy->Check(); } ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ /** * @brief Construct a new Calculate Embedded Nodal Variable From Skin Process object * Constructor with background and skin model parts as well as json settings. This * constructor is intentionally protected to avoid exposing it to the user since it * is intended to serve as an auxiliar constructor to bridge from the model and * parameters one, which checks the provided settings with the defaults, to the "old * fashioned" one. This allows keeping the member variables as const as well as to * have a unique implementation of the constructor required checks and operations. * @param rBaseModelPart Background mesh model part reference * @param rSkinModelPart Embedded skin model part reference * @param rSettings Settings json string */ CalculateEmbeddedNodalVariableFromSkinProcess( ModelPart &rBaseModelPart, ModelPart &rSkinModelPart, Parameters rSettings) : CalculateEmbeddedNodalVariableFromSkinProcess( rBaseModelPart, rSkinModelPart, rSettings["linear_solver_settings"], KratosComponents<Variable<TVarType>>::Get(rSettings["skin_variable_name"].GetString()), KratosComponents<Variable<TVarType>>::Get(rSettings["embedded_nodal_variable_name"].GetString()), rSettings["gradient_penalty_coefficient"].GetDouble(), rSettings["buffer_position"].GetInt(), rSettings["aux_model_part_name"].GetString()) { } ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ void CalculateIntersections() { mpFindIntersectedGeometricalObjectsProcess = Kratos::make_unique<FindIntersectedGeometricalObjectsProcess>(mrBaseModelPart, mrSkinModelPart); mpFindIntersectedGeometricalObjectsProcess->Initialize(); mpFindIntersectedGeometricalObjectsProcess->FindIntersections(); } void ClearIntersections() { mpFindIntersectedGeometricalObjectsProcess->Clear(); } bool ComputeEdgeIntersection( const Element::GeometryType& rIntObjGeometry, const Element::NodeType& rEdgePoint1, const Element::NodeType& rEdgePoint2, Point& rIntersectionPoint) const { bool intersection_flag = false; const unsigned int work_dim = rIntObjGeometry.WorkingSpaceDimension(); if (work_dim == 2){ const unsigned int intersection_status = IntersectionUtilities::ComputeLineLineIntersection<Element::GeometryType>( rIntObjGeometry, rEdgePoint1.Coordinates(), rEdgePoint2.Coordinates(), rIntersectionPoint.Coordinates()); if (intersection_status == 1 || intersection_status == 3) { intersection_flag = true; } } else if (work_dim == 3){ const unsigned int intersection_status = IntersectionUtilities::ComputeTriangleLineIntersection<Element::GeometryType>( rIntObjGeometry, rEdgePoint1.Coordinates(), rEdgePoint2.Coordinates(), rIntersectionPoint.Coordinates()); if (intersection_status == 1) { intersection_flag = true; } } else { KRATOS_ERROR << "Working space dimension value equal to " << work_dim << ". Check your skin geometry implementation." << std::endl; } return intersection_flag; } void AddEdgeNodes( const Geometry<Node<3>> &rEdgeGeometry, ModelPart &rModelPart) const { // Loop the edge nodes for (std::size_t i = 0; i < 2; ++i) { auto p_i_node = rEdgeGeometry(i); // Check if the node has been already added if (!p_i_node->Is(VISITED)) { p_i_node->Set(VISITED, true); rModelPart.CreateNewNode(p_i_node->Id(), *p_i_node); } } } Element::GeometryType::Pointer pSetEdgeElementGeometry( ModelPart &rModelPart, const Element::GeometryType &rCurrentEdgeGeometry, const std::pair<std::size_t, std::size_t> NewEdgeIds) const { Element::GeometryType::PointsArrayType points_array; points_array.push_back(rModelPart.pGetNode(std::get<0>(NewEdgeIds))); points_array.push_back(rModelPart.pGetNode(std::get<1>(NewEdgeIds))); return rCurrentEdgeGeometry.Create(points_array); } inline std::pair<std::size_t, std::size_t> SetEdgePair(const Geometry<Node<3>> &rEdgeGeom) const { std::pair<std::size_t, std::size_t> edge_pair( (rEdgeGeom[0].Id() < rEdgeGeom[1].Id()) ? rEdgeGeom[0].Id() : rEdgeGeom[1].Id(), (rEdgeGeom[0].Id() > rEdgeGeom[1].Id()) ? rEdgeGeom[0].Id() : rEdgeGeom[1].Id()); return edge_pair; } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. CalculateEmbeddedNodalVariableFromSkinProcess& operator=(CalculateEmbeddedNodalVariableFromSkinProcess const& rOther) = delete; /// Copy constructor. CalculateEmbeddedNodalVariableFromSkinProcess(CalculateEmbeddedNodalVariableFromSkinProcess const& rOther) = delete; ///@} }; // Class CalculateEmbeddedNodalVariableFromSkinProcess ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template< class TVarType, class TSparseSpace, class TDenseSpace, class TLinearSolver> inline std::istream& operator >> ( std::istream& rIStream, CalculateEmbeddedNodalVariableFromSkinProcess<TVarType, TSparseSpace, TDenseSpace, TLinearSolver>& rThis); /// output stream function template< class TVarType, class TSparseSpace, class TDenseSpace, class TLinearSolver> inline std::ostream& operator << ( std::ostream& rOStream, const CalculateEmbeddedNodalVariableFromSkinProcess<TVarType, TSparseSpace, TDenseSpace, TLinearSolver>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_CALCULATE_EMBEDDED_VARIABLE_FROM_SKIN_PROCESS_INCLUDED defined
cryptocontext.h
/** * @file cryptocontext.h -- Control for encryption operations. * @author TPOC: [email protected] * * @section LICENSE * * Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * 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 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. */ #ifndef SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #define SRC_DEMO_PRE_CRYPTOCONTEXT_H_ #include "palisade.h" #include "cryptocontexthelper.h" #include "cryptotiming.h" namespace lbcrypto { template<typename Element> class CryptoContextFactory; template<typename Element> class CryptoContextImpl; template<typename Element> using CryptoContext = shared_ptr<CryptoContextImpl<Element>>; /** * @brief CryptoContextImpl * * A CryptoContextImpl is the object used to access the PALISADE library * * All PALISADE functionality is accessed by way of an instance of a CryptoContextImpl; we say that various objects are * "created in" a context, and can only be used in the context in which they were created * * All PALISADE methods are accessed through CryptoContextImpl methods. Guards are implemented to make certain that * only valid objects that have been created in the context are used * * Contexts are created using the CryptoContextFactory, and can be serialized and recovered from a serialization */ template<typename Element> class CryptoContextImpl : public Serializable { friend class CryptoContextFactory<Element>; private: shared_ptr<LPCryptoParameters<Element>> params; /*!< crypto parameters used for this context */ shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme; /*!< algorithm used; accesses all crypto methods */ static std::map<string,std::vector<LPEvalKey<Element>>> evalMultKeyMap; /*!< cached evalmult keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalSumKeyMap; /*!< cached evalsum keys, by secret key UID */ static std::map<string,shared_ptr<std::map<usint,LPEvalKey<Element>>>> evalAutomorphismKeyMap; /*!< cached evalautomorphism keys, by secret key UID */ bool doTiming; vector<TimingInfo>* timeSamples; /** * Private methods to compare two contexts; this is only used internally and is not generally available * @param a - shared pointer in the object * @param b - this object, usually * @return true if the shared pointer is a pointer to "this" */ friend bool operator==(const CryptoContext<Element>& a, const CryptoContext<Element>& b) { if( a->params.get() != b->params.get() ) return false; return true; } friend bool operator!=(const CryptoContext<Element>& a, const CryptoContext<Element>& b) { return !( a == b ); } /** * Private methods to compare two contexts; this is only used internally and is not generally available * @param a - shared pointer in the object * @param b - this object, usually * @return true if the shared pointer is a pointer to "this" */ friend bool operator==(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { if( a.params.get() != b.params.get() ) return false; return true; } friend bool operator!=(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) { return !( a == b ); } /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstCiphertext<Element> b) const { if( a == NULL || b == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetCryptoContext() != b->GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContext"); if( a->GetKeyTag() != b->GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding types " << a->GetEncodingType(); ss << " and " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(ConstCiphertext<Element> a, ConstPlaintext b) const { if( a == NULL ) PALISADE_THROW( type_error, "Null Ciphertext"); if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContext"); if( a->GetEncodingType() != b->GetEncodingType() ) { stringstream ss; ss << "Ciphertext encoding type " << a->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between two ciphertexts is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, const RationalCiphertext<Element>& b) const { if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetCryptoContext() != b.GetCryptoContext() ) PALISADE_THROW( type_error, "Ciphertexts were not created in the same CryptoContextImpl"); if( a.GetKeyTag() != b.GetKeyTag() ) PALISADE_THROW( type_error, "Ciphertexts were not encrypted with same keys" ); if( a.GetNumerator()->GetEncodingType() != b.GetNumerator()->GetEncodingType() ) { stringstream ss; ss << "RationalCiphertext encoding types " << a.GetNumerator()->GetEncodingType(); ss << " and " << b.GetNumerator()->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } /** * TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted * @param a * @param b */ void TypeCheck(const RationalCiphertext<Element>& a, ConstPlaintext b) const { if( b == NULL ) PALISADE_THROW( type_error, "Null Plaintext"); if( a.GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( a.GetNumerator()->GetEncodingType() != b->GetEncodingType() ){ stringstream ss; ss << "RationalCiphertext encoding type " << a.GetNumerator()->GetEncodingType(); ss << " and Plaintext encoding type " << b->GetEncodingType(); ss << " do not match"; PALISADE_THROW( type_error, ss.str() ); } } bool Mismatched(const CryptoContext<Element> a) const { if( a.get() != this ) { return true; } return false; } public: /** * CryptoContextImpl constructor from pointers to parameters and scheme * @param params - pointer to CryptoParameters * @param scheme - pointer to Crypto Scheme */ CryptoContextImpl(LPCryptoParameters<Element> *params = 0, LPPublicKeyEncryptionScheme<Element> *scheme = 0) { this->params.reset(params); this->scheme.reset(scheme); this->doTiming = false; this->timeSamples = 0; } /** * CryptoContextImpl constructor from shared pointers to parameters and scheme * @param params - shared pointer to CryptoParameters * @param scheme - sharedpointer to Crypto Scheme */ CryptoContextImpl(shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme) { this->params = params; this->scheme = scheme; this->doTiming = false; this->timeSamples = 0; } /** * Copy constructor * @param c - source */ CryptoContextImpl(const CryptoContextImpl<Element>& c) { params = c.params; scheme = c.scheme; doTiming = c.doTiming; timeSamples = c.timeSamples; } /** * Assignment * @param rhs - assigning from * @return this */ CryptoContextImpl<Element>& operator=(const CryptoContextImpl<Element>& rhs) { params = rhs.params; scheme = rhs.scheme; doTiming = rhs.doTiming; timeSamples = rhs.timeSamples; return *this; } /** * A CryptoContextImpl is only valid if the shared pointers are both valid */ operator bool() const { return bool(params) && bool(scheme); } // TIMING METHODS /** * StartTiming method activates timing of CryptoMethods * * @param timeSamples points to a vector in which timing samples will be stored */ void StartTiming(vector<TimingInfo>* timeSamples) { this->timeSamples = timeSamples; doTiming = true; } /* * StopTiming - turns off timing */ void StopTiming() { doTiming = false; } /** * ResumeTiming - re-enables timing with existing TimingInfo vector */ void ResumeTiming() { doTiming = true; } /** * ResetTiming - erases measurements */ void ResetTiming() { this->timeSamples->clear(); } // SERIALIZATION METHODS /** * Serialize the CryptoContextImpl * * @param serObj - rapidJson object for the serializaion * @return true on success */ bool Serialize(Serialized* serObj) const; /** * Deserialize the context AND initialize the algorithm * * @param serObj * @return true on success */ bool Deserialize(const Serialized& serObj) { throw std::logic_error("Deserialize by using CryptoContextFactory::DeserializeAndCreateContext"); } /** * SerializeEvalMultKey for all EvalMult keys * method will serialize each CryptoContextImpl only once * * @param serObj - serialization * @return true on success */ static bool SerializeEvalMultKey(Serialized* serObj); /** * SerializeEvalMultKey for a single EvalMult key * method will serialize entire key AND cryptocontext * * @param serObj - serialization * @param id for key to serialize * @return true on success (false on failure or key id not found) */ static bool SerializeEvalMultKey(Serialized* serObj, const string& id); /** * SerializeEvalMultKey for all EvalMultKeys made in a given context * method will serialize the context only once * * @param serObj - serialization * @param cc whose keys should be serialized * @return true on success (false on failure or no keys found) */ static bool SerializeEvalMultKey(Serialized* serObj, const CryptoContext<Element> cc); /** * DeserializeEvalMultKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param serObj - serialization * @return true on success */ static bool DeserializeEvalMultKey(const Serialized& serObj); /** * ClearEvalMultKeys - flush EvalMultKey cache */ static void ClearEvalMultKeys(); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given id * @param id */ static void ClearEvalMultKeys(const string& id); /** * ClearEvalMultKeys - flush EvalMultKey cache for a given context * @param cc */ static void ClearEvalMultKeys(const CryptoContext<Element> cc); /** * InsertEvalMultKey - add the given vector of keys to the map, replacing the existing vector if there * @param vectorToInsert */ static void InsertEvalMultKey(const std::vector<LPEvalKey<Element>>& vectorToInsert); /** * SerializeEvalSumKey for all EvalSum keys * method will serialize each CryptoContextImpl only once * * @param serObj - serialization * @return true on success */ static bool SerializeEvalSumKey(Serialized* serObj); /** * SerializeEvalSumKey for a single EvalSum key * method will serialize entire key AND cryptocontext * * @param serObj - serialization * @param id for key to serialize * @return true on success (false on failure or key id not found) */ static bool SerializeEvalSumKey(Serialized* serObj, const string& id); /** * SerializeEvalSumKey for all EvalSumKeys made in a given context * method will serialize the context only once * * @param serObj - serialization * @param cc whose keys should be serialized * @return true on success (false on failure or no keys found) */ static bool SerializeEvalSumKey(Serialized* serObj, const CryptoContext<Element> cc); /** * DeserializeEvalSumKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param serObj - serialization * @return true on success */ static bool DeserializeEvalSumKey(const Serialized& serObj); /** * ClearEvalSumKeys - flush EvalSumKey cache */ static void ClearEvalSumKeys(); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given id * @param id */ static void ClearEvalSumKeys(const string& id); /** * ClearEvalSumKeys - flush EvalSumKey cache for a given context * @param cc */ static void ClearEvalSumKeys(const CryptoContext<Element> cc); /** * InsertEvalSumKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalSumKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); /** * SerializeEvalAutomorphismKey for all EvalAutomorphism keys * method will serialize each CryptoContextImpl only once * * @param serObj - serialization * @return true on success */ static bool SerializeEvalAutomorphismKey(Serialized* serObj); /** * SerializeEvalAutomorphismKey for a single EvalAutomorphism key * method will serialize entire key AND cryptocontext * * @param serObj - serialization * @param id for key to serialize * @return true on success (false on failure or key id not found) */ static bool SerializeEvalAutomorphismKey(Serialized* serObj, const string& id); /** * SerializeEvalAutomorphismKey for all EvalAutomorphismKeys made in a given context * method will serialize the context only once * * @param serObj - serialization * @param cc whose keys should be serialized * @return true on success (false on failure or no keys found) */ static bool SerializeEvalAutomorphismKey(Serialized* serObj, const CryptoContext<Element> cc); /** * DeserializeEvalAutomorphismKey deserialize all keys in the serialization * deserialized keys silently replace any existing matching keys * deserialization will create CryptoContextImpl if necessary * * @param serObj - serialization * @return true on success */ static bool DeserializeEvalAutomorphismKey(const Serialized& serObj); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache */ static void ClearEvalAutomorphismKeys(); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given id * @param id */ static void ClearEvalAutomorphismKeys(const string& id); /** * ClearEvalAutomorphismKeys - flush EvalAutomorphismKey cache for a given context * @param cc */ static void ClearEvalAutomorphismKeys(const CryptoContext<Element> cc); /** * InsertEvalAutomorphismKey - add the given map of keys to the map, replacing the existing map if there * @param mapToInsert */ static void InsertEvalAutomorphismKey(const shared_ptr<std::map<usint,LPEvalKey<Element>>> mapToInsert); // TURN FEATURES ON /** * Enable a particular feature for use with this CryptoContextImpl * @param feature - the feature that should be enabled */ void Enable(PKESchemeFeature feature) { scheme->Enable(feature); } /** * Enable several features at once * @param featureMask - bitwise or of several PKESchemeFeatures */ void Enable(usint featureMask) { scheme->Enable(featureMask); } // GETTERS /** * Getter for Scheme * @return scheme */ const shared_ptr<LPPublicKeyEncryptionScheme<Element>> GetEncryptionAlgorithm() const { return scheme; } /** * Getter for CryptoParams * @return params */ const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return params; } /** * Getter for element params * @return */ const shared_ptr<typename Element::Params> GetElementParams() const { return params->GetElementParams(); } /** * Getter for encoding params * @return */ const EncodingParams GetEncodingParams() const { return params->GetEncodingParams(); } /** * Get the cyclotomic order used for this context * * @return */ const usint GetCyclotomicOrder() const { return params->GetElementParams()->GetCyclotomicOrder(); } /** * Get the ring dimension used for this context * * @return */ const usint GetRingDimension() const { return params->GetElementParams()->GetRingDimension(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetModulus() const { return params->GetElementParams()->GetModulus(); } /** * Get the ciphertext modulus used for this context * * @return */ const typename Element::Integer& GetRootOfUnity() const { return params->GetElementParams()->GetRootOfUnity(); } /** * KeyGen generates a key pair using this algorithm's KeyGen method * @return a public/secret key pair */ LPKeyPair<Element> KeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeyGen, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using this algorithm's KeyGen method from two keys * @param pk first public key used to coordinate the creation of later public keys. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const LPPublicKey<Element> pk, bool makeSparse=false, bool pre=false) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), pk, makeSparse, pre); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKey, TOC_US(t)) ); } return r; } /** * KeyGen generates a Multiparty key pair using a vector of secret keys * @param secretKeys a vector of the secret keys to be used for multiparty computation. * @return a public/secret key pair */ LPKeyPair<Element> MultipartyKeyGen( const vector<LPPrivateKey<Element>>& secretKeys) { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->MultipartyKeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), secretKeys, false); if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyKeyGenKeyvec, TOC_US(t)) ); } return r; } /** * Lead Multiparty Decryption method for PALISADE multiparty operations. * This should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param privateKey the secret key of the lead decryption client * @param ciphertext vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptLead( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptLead was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptLead was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptLead(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptLead, TOC_US(t)) ); } return newCiphertext; } /** * Multiparty decryption method for PALISADE multiparty operations. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform this MultipartyDecryptMain operation. * @param privateKey - for decryption * @param ciphertext - vector of encrypted ciphertext * @return vector of partially decrypted ciphertexts */ vector<Ciphertext<Element>> MultipartyDecryptMain( const LPPrivateKey<Element> privateKey, const vector<Ciphertext<Element>>& ciphertext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to MultipartyDecryptMain was not generated with this crypto context"); vector<Ciphertext<Element>> newCiphertext; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < ciphertext.size(); i++ ) { if( ciphertext[i] == NULL || Mismatched(ciphertext[i]->GetCryptoContext()) ) throw std::logic_error("A ciphertext passed to MultipartyDecryptMain was not generated with this crypto context"); newCiphertext.push_back( GetEncryptionAlgorithm()->MultipartyDecryptMain(privateKey, ciphertext[i]) ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptMain, TOC_US(t)) ); } return newCiphertext; } /** * Final multiparty decryption method to fuse the partially decrypted ciphertexts into a decrypted plaintext. * The lead multiparty decryption operation should be performed by exactly one of the clients. * All other clients should perform the MultipartyDecryptMain operation. * @param partialCiphertextVec - vector of partially decrypted ciphertexts. * @param plaintext - pointer to destination for the result of decryption * @param doPadding - true if input plaintext was padded; causes unpadding on last piece of ciphertext * @return size of plaintext */ DecryptResult MultipartyDecryptFusion( const vector<Ciphertext<Element>>& partialCiphertextVec, Plaintext *plaintext) const { DecryptResult result; //Make sure we're processing ciphertexts. size_t last_ciphertext = partialCiphertextVec.size(); if ( last_ciphertext < 1 ) return result; TimeVar t; if( doTiming ) TIC(t); for( size_t i = 0; i < last_ciphertext; i++ ) { if (partialCiphertextVec[i] == NULL || Mismatched(partialCiphertextVec[i]->GetCryptoContext())) throw std::logic_error("A ciphertext passed to MultipartyDecryptFusion was not generated with this crypto context"); if (partialCiphertextVec[i]->GetEncodingType() != partialCiphertextVec[0]->GetEncodingType()) throw std::logic_error("Ciphertexts passed to MultipartyDecryptFusion have mismatched encoding types"); } // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(partialCiphertextVec[0]->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); result = GetEncryptionAlgorithm()->MultipartyDecryptFusion(partialCiphertextVec, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); *plaintext = decrypted; if( doTiming ) { timeSamples->push_back( TimingInfo(OpMultiPartyDecryptFusion, TOC_US(t)) ); } return result; } /** * SparseKeyGen generates a key pair with special structure, and without full entropy, * for use in special cases like Ring Reduction * @return a public/secret key pair */ LPKeyPair<Element> SparseKeyGen() { TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeyGen(CryptoContextFactory<Element>::GetContextForPointer(this), true); if( doTiming ) { timeSamples->push_back( TimingInfo(OpSparseKeyGen, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * @param newKey (public) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPublicKey<Element> newKey, const LPPrivateKey<Element> oldKey) const { if( newKey == NULL || oldKey == NULL || Mismatched(newKey->GetCryptoContext()) || Mismatched(oldKey->GetCryptoContext()) ) throw std::logic_error("Keys passed to ReKeyGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->ReKeyGen(newKey, oldKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReKeyGenPubPri, TOC_US(t)) ); } return r; } /** * ReKeyGen produces an Eval Key that PALISADE can use for Proxy Re Encryption * @param newKey (private) * @param oldKey (private) * @return new evaluation key */ LPEvalKey<Element> ReKeyGen( const LPPrivateKey<Element> newKey, const LPPrivateKey<Element> oldKey) const { if (newKey == NULL || oldKey == NULL || Mismatched(newKey->GetCryptoContext()) || Mismatched(oldKey->GetCryptoContext()) ) throw std::logic_error("Keys passed to ReKeyGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->ReKeyGen(newKey, oldKey); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReKeyGenPriPri, TOC_US(t)) ); } return r; } /** * EvalMultKeyGen creates a key that can be used with the PALISADE EvalMult operator * @param key * @return new evaluation key */ void EvalMultKeyGen(const LPPrivateKey<Element> key); /** * EvalMultsKeyGen creates a vector evalmult keys that can be used with the PALISADE EvalMult operator * 1st key (for s^2) is used for multiplication of ciphertexts of depth 1 * 2nd key (for s^3) is used for multiplication of ciphertexts of depth 2, etc. * * @param key * @return a vector of evaluation keys */ void EvalMultKeysGen(const LPPrivateKey<Element> key); /** * GetEvalMultKeyVector fetches the eval mult keys for a given KeyID * @param keyID * @return key vector from ID */ static const vector<LPEvalKey<Element>>& GetEvalMultKeyVector(const string& keyID); /** * GetEvalMultKeys * @return map of all the keys */ static const std::map<string,std::vector<LPEvalKey<Element>>>& GetAllEvalMultKeys(); /** * KeySwitchGen creates a key that can be used with the PALISADE KeySwitch operation * @param key1 * @param key2 * @return new evaluation key */ LPEvalKey<Element> KeySwitchGen( const LPPrivateKey<Element> key1, const LPPrivateKey<Element> key2) const { if( key1 == NULL || key2 == NULL || Mismatched(key1->GetCryptoContext()) || Mismatched(key2->GetCryptoContext()) ) throw std::logic_error("Keys passed to KeySwitchGen were not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto r = GetEncryptionAlgorithm()->KeySwitchGen(key1, key2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitchGen, TOC_US(t)) ); } return r; } /** * Encrypt a plaintext using a given public key * @param publicKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPublicKey<Element> publicKey, Plaintext plaintext) { if( publicKey == NULL ) throw std::logic_error("null key passed to Encrypt"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); if( Mismatched(publicKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPub, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a plaintext using a given private key * @param privateKey * @param plaintext * @return ciphertext (or null on failure) */ Ciphertext<Element> Encrypt( const LPPrivateKey<Element> privateKey, Plaintext plaintext) const { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("key passed to Encrypt was not generated with this crypto context"); if( plaintext == NULL ) throw std::logic_error("null plaintext passed to Encrypt"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(privateKey, plaintext->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext->GetEncodingType() ); } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptPriv, TOC_US(t)) ); } return ciphertext; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ shared_ptr<Matrix<RationalCiphertext<Element>>> EncryptMatrix( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return RationalCiphertext<Element>(publicKey->GetCryptoContext(), true); }; shared_ptr<Matrix<RationalCiphertext<Element>>> cipherResults(new Matrix<RationalCiphertext<Element>> (zeroAlloc, plaintext.GetRows(), plaintext.GetCols())); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) return 0; Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } (*cipherResults)(row, col).SetNumerator(ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Encrypt a matrix of Plaintext * @param publicKey - for encryption * @param plaintext - to encrypt * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return a vector of pointers to Ciphertexts created by encrypting the plaintext */ Matrix<Ciphertext<Element>> EncryptMatrixCiphertext( const LPPublicKey<Element> publicKey, Matrix<Plaintext> &plaintext) { if (publicKey == NULL || Mismatched(publicKey->GetCryptoContext())) throw std::logic_error("key passed to EncryptMatrix was not generated with this crypto context"); auto zeroAlloc = [=]() { return Ciphertext<Element>(new CiphertextImpl<Element>(publicKey->GetCryptoContext())); }; Matrix<Ciphertext<Element>> cipherResults(zeroAlloc, plaintext.GetRows(), plaintext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < plaintext.GetRows(); row++) { for (size_t col = 0; col < plaintext.GetCols(); col++) { if( plaintext(row,col)->Encode() == false ) throw std::logic_error("Plaintext is not encoded"); Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, plaintext(row,col)->GetElement<Element>()); if (ciphertext) { ciphertext->SetEncodingType( plaintext(row,col)->GetEncodingType() ); } cipherResults(row, col) = (ciphertext); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpEncryptMatrixPlain, TOC_US(t)) ); } return cipherResults; } /** * Perform an encryption by reading plaintext from a stream, serializing each piece of ciphertext, * and writing the serializations to an output stream * @param publicKey - the encryption key in use * @param instream - where to read the input from * @param ostream - where to write the serialization to * @param doEncryption encrypts if true, embeds (encodes) the plaintext into cryptocontext if false * @return */ void EncryptStream( const LPPublicKey<Element> publicKey, std::istream& instream, std::ostream& outstream) const { // NOTE timing this operation is not supported if( publicKey == NULL || Mismatched(publicKey->GetCryptoContext()) ) throw std::logic_error("key passed to EncryptStream was not generated with this crypto context"); bool padded = false; Plaintext px; size_t chunkSize = this->GetRingDimension(); char *ptxt = new char[chunkSize]; while (instream.good()) { instream.read(ptxt, chunkSize); size_t nRead = instream.gcount(); if (nRead <= 0 && padded) break; px = this->MakeStringPlaintext(std::string(ptxt,nRead)); if (nRead < chunkSize) { padded = true; } Ciphertext<Element> ciphertext = GetEncryptionAlgorithm()->Encrypt(publicKey, px->GetElement<Element>()); if (!ciphertext) { break; } ciphertext->SetEncodingType( px->GetEncodingType() ); Serialized cS; if (ciphertext->Serialize(&cS)) { if (!SerializableHelper::SerializationToStream(cS, outstream)) { break; } } else { break; } } delete [] ptxt; return; } // PLAINTEXT FACTORY METHODS // FIXME to be deprecated in 2.0 /** * MakeScalarPlaintext constructs a ScalarEncoding in this context * @param value * @param isSigned * @return plaintext */ Plaintext MakeScalarPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Scalar, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeStringPlaintext constructs a StringEncoding in this context * @param str * @return plaintext */ Plaintext MakeStringPlaintext(const string& str) const { auto p = PlaintextFactory::MakePlaintext( String, this->GetElementParams(), this->GetEncodingParams(), str ); return p; } /** * MakeIntegerPlaintext constructs an IntegerEncoding in this context * @param value * @return plaintext */ Plaintext MakeIntegerPlaintext(int64_t value) const { auto p = PlaintextFactory::MakePlaintext( Integer, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakeIntegerPlaintext constructs a FractionalEncoding in this context * @param value * @param truncatedBits limit on fractional * @return plaintext */ Plaintext MakeFractionalPlaintext(int64_t value, size_t truncatedBits = 0) const { auto p = PlaintextFactory::MakePlaintext( Fractional, this->GetElementParams(), this->GetEncodingParams(), value, truncatedBits ); return p; } /** * MakeCoefPackedPlaintext constructs a CoefPackedEncoding in this context * @param value * @return plaintext */ Plaintext MakeCoefPackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( CoefPacked, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePackedPlaintext constructs a PackedEncoding in this context * @param value * @return plaintext */ Plaintext MakePackedPlaintext(const vector<int64_t>& value) const { auto p = PlaintextFactory::MakePlaintext( Packed, this->GetElementParams(), this->GetEncodingParams(), value ); return p; } /** * MakePlaintext static that takes a cc and calls the Plaintext Factory * @param encoding * @param cc * @param value * @return */ template<typename Value1> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value ); } template<typename Value1, typename Value2> static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value, const Value2& value2) { return PlaintextFactory::MakePlaintext( encoding, cc->GetElementParams(), cc->GetEncodingParams(), value, value2 ); } private: static Plaintext GetPlaintextForDecrypt(PlaintextEncodings pte, shared_ptr<typename Element::Params> evp, EncodingParams ep) { shared_ptr<typename NativePoly::Params> vp( new typename NativePoly::Params(evp->GetCyclotomicOrder(), ep->GetPlaintextModulus(), 1) ); return PlaintextFactory::MakePlaintext(pte, vp, ep); } public: /** * Decrypt a single ciphertext into the appropriate plaintext * * @param privateKey - decryption key * @param ciphertext - ciphertext to decrypt * @param plaintext - resulting plaintext object pointer is here * @return */ DecryptResult Decrypt( const LPPrivateKey<Element> privateKey, ConstCiphertext<Element> ciphertext, Plaintext* plaintext) { if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to Decrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); // determine which type of plaintext that you need to decrypt into Plaintext decrypted = GetPlaintextForDecrypt(ciphertext->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult result = GetEncryptionAlgorithm()->Decrypt(privateKey, ciphertext, &decrypted->GetElement<NativePoly>()); if (result.isValid == false) return result; decrypted->Decode(); if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecrypt, TOC_US(t)) ); } *plaintext = decrypted; return result; } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrix( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator, shared_ptr<Matrix<Plaintext>> *denominator) const { // edge case if ((ciphertext->GetCols()== 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build matrices for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); *denominator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext->GetRows(); row++) { for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (Mismatched((*ciphertext)(row, col).GetCryptoContext())) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(row,col) = decryptedNumerator; (**numerator)(row,col)->Decode(); Plaintext decryptedDenominator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); if( (*ciphertext)(row,col).GetIntegerFlag() == true ) { decryptedDenominator->GetElement<Poly>().SetValuesToZero(); decryptedDenominator->GetElement<Poly>().at(0) = 1; } else { const Ciphertext<Element> ctD = (*ciphertext)(row, col).GetDenominator(); DecryptResult resultD = GetEncryptionAlgorithm()->Decrypt(privateKey, ctD, &decryptedDenominator->GetElement<NativePoly>()); if (resultD.isValid == false) return resultD; (**denominator)(row,col) = decryptedDenominator; } (**denominator)(row, col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((**numerator)((*numerator)->GetRows()-1,(*numerator)->GetCols()-1)->GetLength()); } /** * Decrypt method for a matrix of ciphertexts * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixCiphertext( const LPPrivateKey<Element> privateKey, const Matrix<Ciphertext<Element>> ciphertext, Matrix<Plaintext> *numerator) const { // edge case if ((ciphertext.GetCols()== 0) && (ciphertext.GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(0, 0); // need to build matrices for the result // Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); // auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; // numerator = new Matrix<Plaintext>(zeroPackingAlloc, ciphertext.GetRows(), ciphertext.GetCols()); TimeVar t; if( doTiming ) TIC(t); for (size_t row = 0; row < ciphertext.GetRows(); row++) { for (size_t col = 0; col < ciphertext.GetCols(); col++) { if (Mismatched( (ciphertext(row, col))->GetCryptoContext() )) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (ciphertext)(row, col); // determine which type of plaintext that you need to decrypt into Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (*numerator)(row,col) = decryptedNumerator; (*numerator)(row,col)->Decode(); } } if( doTiming ) { timeSamples->push_back( TimingInfo(OpDecryptMatrixPlain, TOC_US(t)) ); } return DecryptResult((*numerator)( numerator->GetRows()-1, numerator->GetCols()-1)->GetLength()); } /** * Decrypt method for numerators in a matrix of ciphertexts (packed encoding) * @param privateKey - for decryption * @param ciphertext - matrix of encrypted ciphertexts * @param plaintext - pointer to the destination martrix of plaintexts * @return size of plaintext */ DecryptResult DecryptMatrixNumerator( const LPPrivateKey<Element> privateKey, const shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext, shared_ptr<Matrix<Plaintext>> *numerator) const { // edge case if ((ciphertext->GetCols() == 0) && (ciphertext->GetRows() == 0)) return DecryptResult(); if (privateKey == NULL || Mismatched(privateKey->GetCryptoContext())) throw std::runtime_error("Information passed to DecryptMatrix was not generated with this crypto context"); TimeVar t; if (doTiming) TIC(t); //force all precomputations to take place in advance if( Mismatched((*ciphertext)(0, 0).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(0, 0).GetNumerator(); // need to build a numerator matrix for the result Plaintext ptx = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); auto zeroPackingAlloc = [=]() { return Plaintext(ptx); }; *numerator = shared_ptr<Matrix<Plaintext>>( new Matrix<Plaintext>(zeroPackingAlloc, ciphertext->GetRows(), ciphertext->GetCols()) ); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult resultN = GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); if (resultN.isValid == false) return resultN; (**numerator)(0, 0) = decryptedNumerator; (**numerator)(0, 0)->Decode(); for (size_t row = 0; row < ciphertext->GetRows(); row++) { #pragma omp parallel for for (size_t col = 0; col < ciphertext->GetCols(); col++) { if (row + col > 0) { if( Mismatched((*ciphertext)(row, col).GetCryptoContext()) ) throw std::runtime_error("A ciphertext passed to DecryptMatrix was not generated with this crypto context"); const Ciphertext<Element> ctN = (*ciphertext)(row, col).GetNumerator(); Plaintext decryptedNumerator = GetPlaintextForDecrypt(ctN->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); GetEncryptionAlgorithm()->Decrypt(privateKey, ctN, &decryptedNumerator->GetElement<NativePoly>()); (**numerator)(row, col) = decryptedNumerator; (**numerator)(row, col)->Decode(); } } } if (doTiming) { timeSamples->push_back(TimingInfo(OpDecryptMatrixPacked, TOC_US(t))); } return DecryptResult((**numerator)((*numerator)->GetRows() - 1, (*numerator)->GetCols() - 1)->GetLength()); } /** * read instream for a sequence of serialized ciphertext; deserialize it, decrypt it, and write it to outstream * @param privateKey - reference to the decryption key * @param instream - input stream with sequence of serialized ciphertexts * @param outstream - output stream for plaintext * @return total bytes processed */ size_t DecryptStream( const LPPrivateKey<Element> privateKey, std::istream& instream, std::ostream& outstream) { // NOTE timing this operation is not supported if( privateKey == NULL || Mismatched(privateKey->GetCryptoContext()) ) throw std::logic_error("Information passed to DecryptStream was not generated with this crypto context"); Serialized serObj; size_t tot = 0; bool firstTime = true; Plaintext pte[2]; bool whichArray = false; while( SerializableHelper::StreamToSerialization(instream, &serObj) ) { Ciphertext<Element> ct; if( (ct = deserializeCiphertext(serObj)) != NULL ) { if( ct->GetEncodingType() != String ) { throw std::logic_error("Library can only stream string encodings"); } pte[whichArray] = GetPlaintextForDecrypt(ct->GetEncodingType(), this->GetElementParams(), this->GetEncodingParams()); DecryptResult res = GetEncryptionAlgorithm()->Decrypt(privateKey, ct, &pte[whichArray]->GetElement<NativePoly>()); if( !res.isValid ) return tot; tot += res.messageLength; pte[whichArray]->Decode(); if( !firstTime ) { outstream << pte[!whichArray]->GetStringValue(); } firstTime = false; whichArray = !whichArray; } else return tot; } outstream << pte[!whichArray]->GetStringValue(); return tot; } /** * ReEncrypt - Proxy Re Encryption mechanism for PALISADE * @param evalKey - evaluation key from the PRE keygen method * @param ciphertext - vector of shared pointers to encrypted Ciphertext * @return vector of shared pointers to re-encrypted ciphertexts */ Ciphertext<Element> ReEncrypt( LPEvalKey<Element> evalKey, ConstCiphertext<Element> ciphertext) const { if( evalKey == NULL || Mismatched(evalKey->GetCryptoContext()) ) throw std::logic_error("Information passed to ReEncrypt was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("The ciphertext passed to ReEncrypt was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> newCiphertext = GetEncryptionAlgorithm()->ReEncrypt(evalKey, ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpReEncrypt, TOC_US(t)) ); } return newCiphertext; } /** * read instream for a serialized ciphertext. deserialize, re-encrypt, serialize, and write to outstream * @param evalKey - reference to the re-encryption key * @param instream - input stream with sequence of serialized ciphertext * @param outstream - output stream with sequence of serialized re-encrypted ciphertext */ void ReEncryptStream( const LPEvalKey<Element> evalKey, std::istream& instream, std::ostream& outstream) { // NOTE timing this operation is not supported if( evalKey == NULL || Mismatched(evalKey->GetCryptoContext()) ) throw std::logic_error("Information passed to ReEncryptStream was not generated with this crypto context"); Serialized serObj; while( SerializableHelper::StreamToSerialization(instream, &serObj) ) { Ciphertext<Element> ct; ct = deserializeCiphertext(serObj); if( ct ) { Ciphertext<Element> reCt = ReEncrypt(evalKey, ct); Serialized serReObj; if( reCt->Serialize(&serReObj) ) { SerializableHelper::SerializationToStream(serReObj, outstream); } else { return; } } else { return; } } } /** * EvalAdd - PALISADE EvalAdd method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 + ct2 */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAdd(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAdd, TOC_US(t)) ); } return rv; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalAddMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 + *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalAddMatrix - PALISADE EvalAdd method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalAddMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 + ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddMatrix, TOC_US(t)) ); } // Matrix<Ciphertext<Element>> a(rv); return rv; } /** * EvalSub - PALISADE EvalSub method for a pair of ciphertexts * @param ct1 * @param ct2 * @return new ciphertext for ct1 - ct2 */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSub, TOC_US(t)) ); } return rv; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalSubMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 - *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSubMatrix - PALISADE EvalSub method for a pair of matrices of ciphertexts * @param ct1 * @param ct2 * @return new matrix for ct1 + ct2 */ Matrix<Ciphertext<Element>> EvalSubMatrix(const Matrix<Ciphertext<Element>> &ct1, const Matrix<Ciphertext<Element>> &ct2) const { TypeCheck(ct1(0,0), ct2(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<Ciphertext<Element>> rv = ct1 - ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubMatrix, TOC_US(t)) ); } Matrix<Ciphertext<Element>> a(rv); return a; } /** * EvalAdd - PALISADE EvalAdd method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext + plaintext */ Ciphertext<Element> EvalAdd(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); plaintext->SetFormat(EVALUATION); auto rv = GetEncryptionAlgorithm()->EvalAdd(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAddPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalAdd(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalAdd(ciphertext, plaintext); } /** * EvalSubPlain - PALISADE EvalSub method for a ciphertext and plaintext * @param ciphertext * @param plaintext * @return new ciphertext for ciphertext - plaintext */ Ciphertext<Element> EvalSub(ConstCiphertext<Element> ciphertext, ConstPlaintext plaintext) const { TypeCheck(ciphertext, plaintext); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalSub(ciphertext, plaintext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalSubPlain, TOC_US(t)) ); } return rv; } inline Ciphertext<Element> EvalSub(ConstPlaintext plaintext, ConstCiphertext<Element> ciphertext) const { return EvalSub(ciphertext, plaintext); } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - with key switching * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for a pair of ciphertexts - no key switching (relinearization) * @param ct1 * @param ct2 * @return new ciphertext for ct1 * ct2 */ Ciphertext<Element> EvalMultNoRelin(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { TypeCheck(ct1, ct2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, ct2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMany - PALISADE function for evaluating multiplication on ciphertext followed by relinearization operation (at the end). * It computes the multiplication in a binary tree manner. Also, it reduces the number of * elements in the ciphertext to two after each multiplication. * Currently it assumes that the consecutive two input arguments have * total depth smaller than the supported depth. Otherwise, it throws an error. * * @param cipherTextList is the ciphertext list. * * @return new ciphertext. */ Ciphertext<Element> EvalMultMany(const vector<Ciphertext<Element>>& ct) const{ const auto ek = GetEvalMultKeyVector(ct[0]->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultMany(ct, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMany, TOC_US(t)) ); } return rv; } /** * Function for evaluating multiplication on ciphertext followed by relinearization operation. * Currently it assumes that the input arguments have total depth smaller than the supported depth. Otherwise, it throws an error. * * @param ct1 first input ciphertext. * @param ct2 second input ciphertext. * * @return new ciphertext */ Ciphertext<Element> EvalMultAndRelinearize(ConstCiphertext<Element> ct1, ConstCiphertext<Element> ct2) const { const auto ek = GetEvalMultKeyVector(ct1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMultAndRelinearize(ct1, ct2, ek); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ inline Ciphertext<Element> EvalMult(ConstPlaintext pt2, ConstCiphertext<Element> ct1) const { return EvalMult(ct1, pt2); } /** * EvalShiftRight - works only for Fractional Encoding * @param pt2 * @param ct1 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalRightShift(ConstCiphertext<Element> ct1, size_t divisor) const { if( ct1 && ct1->GetEncodingType() != Fractional ) { stringstream ss; ss << "A " << Fractional << " encoded ciphertext is required for the EvalRightShift operation"; PALISADE_THROW( type_error, ss.str() ); } Plaintext plaintextShift = MakeFractionalPlaintext(0,divisor); TypeCheck(ct1, plaintextShift); double start = 0; if( doTiming ) start = currentDateTime(); auto rv = EvalMult(ct1, plaintextShift); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalRightShift, currentDateTime() - start) ); } return rv; } /** * EvalMult - PALISADE EvalMult method for plaintext * ciphertext * @param ct1 * @param pt2 * @return new ciphertext for ct1 * pt2 */ Ciphertext<Element> EvalMult(ConstCiphertext<Element> ct1, ConstPlaintext pt2) const { TypeCheck(ct1, pt2); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalMult(ct1, pt2); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMult, TOC_US(t)) ); } return rv; } /** * EvalMultMatrix - PALISADE EvalMult method for two matrices of ciphertext * @param ct1 * @param ct2 * @return new matrix for ct1 * ct2 */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalMultMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct1, const shared_ptr<Matrix<RationalCiphertext<Element>>> ct2) const { TypeCheck((*ct1)(0,0), (*ct2)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); Matrix<RationalCiphertext<Element>> rv = *ct1 * *ct2; if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalMultMatrix, TOC_US(t)) ); } shared_ptr<Matrix<RationalCiphertext<Element>>> a(new Matrix<RationalCiphertext<Element>>(rv)); return a; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ Ciphertext<Element> EvalNegate(ConstCiphertext<Element> ct) const { if (ct == NULL || Mismatched(ct->GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegate was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalNegate(ct); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNeg, TOC_US(t)) ); } return rv; } /** * EvalSub - PALISADE Negate method for a ciphertext * @param ct * @return new ciphertext -ct */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalNegateMatrix(const shared_ptr<Matrix<RationalCiphertext<Element>>> ct) const { if (ct == NULL || Mismatched((*ct)(0,0).GetCryptoContext()) ) throw std::logic_error("Information passed to EvalNegateMatrix was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ct->GetAllocator(), ct->GetRows(), ct->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = -((*ct)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalNegMatrix, TOC_US(t)) ); } return m; } /** * Generate automophism keys for a given private key * * @param publicKey original public key. * @param origPrivateKey original private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys; index 0 of the vector corresponds to plaintext index 2, index 1 to plaintex index 3, etc. */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPublicKey<Element> publicKey, const LPPrivateKey<Element> origPrivateKey, const std::vector<usint> &indexList) const { if( publicKey == NULL || origPrivateKey == NULL ) PALISADE_THROW( type_error, "Null Keys"); if( publicKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); if( publicKey->GetCryptoContext() != origPrivateKey->GetCryptoContext() ) PALISADE_THROW( type_error, "Keys were not created in the same CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(publicKey, origPrivateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismKeyGen, TOC_US(t)) ); } return rv; } /** * Function for evaluating automorphism of ciphertext at index i * * @param ciphertext the input ciphertext. * @param i automorphism index * @param &evalKeys - reference to the vector of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalAutomorphism(ConstCiphertext<Element> ciphertext, usint i, const std::map<usint, LPEvalKey<Element>> &evalKeys) const { auto mf = evalKeys.begin(); if( mf == evalKeys.end() ) PALISADE_THROW( type_error, "Empty key map"); auto tk = mf->second; if( ciphertext == NULL || tk == NULL ) PALISADE_THROW( type_error, "Null inputs"); if( ciphertext->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Ciphertext was not created in this CryptoContextImpl"); if( ciphertext->GetCryptoContext() != tk->GetCryptoContext() ) PALISADE_THROW( type_error, "Items were not created in the same CryptoContextImpl"); if( ciphertext->GetKeyTag() != tk->GetKeyTag() ) PALISADE_THROW( type_error, "Items were not encrypted with same keys" ); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphism(ciphertext, i, evalKeys); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismI, TOC_US(t)) ); } return rv; } /** * Generate automophism keys for a given private key; Uses the private key for encryption * * @param privateKey private key. * @param indexList list of automorphism indices to be computed * @return returns the evaluation keys */ shared_ptr<std::map<usint, LPEvalKey<Element>>> EvalAutomorphismKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<usint> &indexList) const { if( privateKey == NULL ) PALISADE_THROW( type_error, "Null input"); if( privateKey->GetCryptoContext().get() != this ) PALISADE_THROW( type_error, "Key was not created in this CryptoContextImpl"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalAutomorphismKeyGen(privateKey, indexList); if( doTiming ) { timeSamples->push_back( TimingInfo(OpEvalAutomorphismK, TOC_US(t)) ); } return rv; } /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param publicKey public key (used in NTRU schemes). */ void EvalSumKeyGen( const LPPrivateKey<Element> privateKey, const LPPublicKey<Element> publicKey = nullptr); /** * GetEvalSumKey returns the map * * @return the EvalSum key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalSumKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalSumKeys(); /** * Function for evaluating a sum of all components * * @param ciphertext the input ciphertext. * @param batchSize size of the batch * @return resulting ciphertext */ Ciphertext<Element> EvalSum(ConstCiphertext<Element> ciphertext, usint batchSize) const; /** * EvalSumKeyGen Generates the key map to be used by evalsum * * @param privateKey private key. * @param indexList list of indices. * @param publicKey public key (used in NTRU schemes). */ void EvalAtIndexKeyGen(const LPPrivateKey<Element> privateKey, const std::vector<int32_t> &indexList, const LPPublicKey<Element> publicKey = nullptr); /** * Merges multiple ciphertexts with encrypted results in slot 0 into a single ciphertext * The slot assignment is done based on the order of ciphertexts in the vector * * @param ciphertextVector vector of ciphertexts to be merged. * @param &evalKeys - reference to the map of evaluation keys generated by EvalAutomorphismKeyGen. * @return resulting ciphertext */ Ciphertext<Element> EvalMerge(const vector<Ciphertext<Element>> &ciphertextVector) const; /** * GetEvalAutomorphismKey returns the map * * @return the EvalAutomorphism key map */ static const std::map<usint, LPEvalKey<Element>>& GetEvalAutomorphismKeyMap(const string& id); static const std::map<string,shared_ptr<std::map<usint, LPEvalKey<Element>>>>& GetAllEvalAutomorphismKeys(); /** * Moves i-th slot to slot 0 * * @param ciphertext. * @param i the index. * @return resulting ciphertext */ Ciphertext<Element> EvalAtIndex(ConstCiphertext<Element> ciphertext, int32_t index) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2, usint batchSize) const; /** * Evaluates inner product in batched encoding * * @param ciphertext1 first vector. * @param ciphertext2 second vector. * @param batchSize size of the batch to be summed up * @return resulting ciphertext */ Ciphertext<Element> EvalInnerProduct(ConstCiphertext<Element> ciphertext1, ConstPlaintext ciphertext2, usint batchSize) const; /** * EvalCrossCorrelation - Computes the sliding sum of inner products (known as * as cross-correlation, sliding inner product, or sliding dot product in * image processing * @param x - first vector of row vectors * @param y - second vector of row vectors * @param batchSize - batch size for packed encoding * @param indexStart - starting index in the vectors of row vectors * @param length - length of the slice in the vectors of row vectors; default is 0 meaning to use the full length of the vector * @return sum(x_i*y_i), i.e., a sum of inner products */ Ciphertext<Element> EvalCrossCorrelation(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize, usint indexStart = 0, usint length = 0) const; /** * EvalLinRegressBatched- Computes the parameter vector for linear regression using the least squares method * Supported only in batched mode; currently works only for two regressors * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegressBatched(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y, usint batchSize) const; /** * EvalLinRegression - Computes the parameter vector for linear regression using the least squares method * @param x - matrix of regressors * @param y - vector of dependent variables * @return the parameter vector using (x^T x)^{-1} x^T y (using least squares method) */ shared_ptr<Matrix<RationalCiphertext<Element>>> EvalLinRegression(const shared_ptr<Matrix<RationalCiphertext<Element>>> x, const shared_ptr<Matrix<RationalCiphertext<Element>>> y) const { TypeCheck((*x)(0,0), (*y)(0,0)); // TODO only checking one; when Matrix is refactored, this should be revisited TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->EvalLinRegression(x, y); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLinRegression, TOC_US(t)) ); } return rv; } /** * KeySwitch - PALISADE KeySwitch method * @param keySwitchHint - reference to KeySwitchHint * @param ciphertext - vector of ciphertext * @return new CiphertextImpl after applying key switch */ Ciphertext<Element> KeySwitch( const LPEvalKey<Element> keySwitchHint, ConstCiphertext<Element> ciphertext) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to KeySwitch was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to KeySwitch was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->KeySwitch(keySwitchHint, ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpKeySwitch, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ Ciphertext<Element> ModReduce(ConstCiphertext<Element> ciphertext) const { if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Information passed to ModReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ModReduce(ciphertext); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return rv; } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ RationalCiphertext<Element> ModReduceRational(RationalCiphertext<Element> ciphertext) const { TimeVar t; if( doTiming ) TIC(t); Ciphertext<Element> n = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetNumerator()); Ciphertext<Element> d = GetEncryptionAlgorithm()->ModReduce(ciphertext.GetDenominator()); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduce, TOC_US(t)) ); } return RationalCiphertext<Element>(n,d); } /** * ModReduce - PALISADE ModReduce method * @param ciphertext - vector of ciphertext * @return vector of mod reduced ciphertext */ shared_ptr<Matrix<RationalCiphertext<Element>>> ModReduceMatrix(shared_ptr<Matrix<RationalCiphertext<Element>>> ciphertext) const { // needs context check TimeVar t; if( doTiming ) TIC(t); shared_ptr<Matrix<RationalCiphertext<Element>>> m( new Matrix<RationalCiphertext<Element>>(ciphertext->GetAllocator(), ciphertext->GetRows(), ciphertext->GetCols())); for( size_t r = 0; r < m->GetRows(); r++ ) for( size_t c = 0; c < m->GetCols(); c++ ) (*m)(r,c) = ModReduceRational((*ciphertext)(r,c)); if( doTiming ) { timeSamples->push_back( TimingInfo(OpModReduceMatrix, TOC_US(t)) ); } return m; } /** * LevelReduce - PALISADE LevelReduce method * @param cipherText1 * @param linearKeySwitchHint * @return vector of level reduced ciphertext */ Ciphertext<Element> LevelReduce(ConstCiphertext<Element> cipherText1, const LPEvalKeyNTRU<Element> linearKeySwitchHint) const { if( cipherText1 == NULL || linearKeySwitchHint == NULL || Mismatched(cipherText1->GetCryptoContext()) || Mismatched(linearKeySwitchHint->GetCryptoContext()) ) { throw std::logic_error("Information passed to LevelReduce was not generated with this crypto context"); } TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->LevelReduce(cipherText1, linearKeySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpLevelReduce, TOC_US(t)) ); } return rv; } /** * RingReduce - PALISADE RingReduce method * @param ciphertext - vector of ciphertext * @param keySwitchHint - the keySwitchHint from original private key to sparse private key * @return vector of ring-reduced ciphertexts */ Ciphertext<Element> RingReduce( ConstCiphertext<Element> ciphertext, const LPEvalKey<Element> keySwitchHint) const { if( keySwitchHint == NULL || Mismatched(keySwitchHint->GetCryptoContext()) ) throw std::logic_error("Key passed to RingReduce was not generated with this crypto context"); if( ciphertext == NULL || Mismatched(ciphertext->GetCryptoContext()) ) throw std::logic_error("Ciphertext passed to RingReduce was not generated with this crypto context"); TimeVar t; if( doTiming ) TIC(t); auto newCiphertext = GetEncryptionAlgorithm()->RingReduce(ciphertext, keySwitchHint); if( doTiming ) { timeSamples->push_back( TimingInfo(OpRingReduce, TOC_US(t)) ); } return newCiphertext; } /** * ComposedEvalMult - PALISADE composed evalmult * @param ciphertext1 - vector for first cipher text * @param ciphertext2 - vector for second cipher text * @param quadKeySwitchHint - is the quadratic key switch hint from original private key to the quadratic key * return vector of resulting ciphertext */ Ciphertext<Element> ComposedEvalMult( ConstCiphertext<Element> ciphertext1, ConstCiphertext<Element> ciphertext2) const { if( ciphertext1 == NULL || ciphertext2 == NULL || ciphertext1->GetKeyTag() != ciphertext2->GetKeyTag() || Mismatched(ciphertext1->GetCryptoContext()) ) throw std::logic_error("Ciphertexts passed to ComposedEvalMult were not generated with this crypto context"); auto ek = GetEvalMultKeyVector(ciphertext1->GetKeyTag()); TimeVar t; if( doTiming ) TIC(t); auto rv = GetEncryptionAlgorithm()->ComposedEvalMult(ciphertext1, ciphertext2, ek[0]); if( doTiming ) { timeSamples->push_back( TimingInfo(OpComposedEvalMult, TOC_US(t)) ); } return rv; } /** * Deserialize into a Public Key * @param serObj * @return deserialized object */ static LPPublicKey<Element> deserializePublicKey(const Serialized& serObj); /** * Deserialize into a Private Key * @param serObj * @return deserialized object */ static LPPrivateKey<Element> deserializeSecretKey(const Serialized& serObj); /** * Deserialize into a Ciphertext * @param serObj * @return deserialized object */ static Ciphertext<Element> deserializeCiphertext(const Serialized& serObj); /** * Deserialize into an Eval Key in a given context * @param serObj * @return deserialized object */ static LPEvalKey<Element> deserializeEvalKey(const Serialized& serObj); /** * Deserialize into an Eval Key * @param serObj * @return deserialized object */ static LPEvalKey<Element> deserializeEvalKeyInContext(const Serialized& serObj, CryptoContext<Element> cc); }; /** * @brief CryptoObject * * A class to aid in referring to the crypto context that an object belongs to */ template<typename Element> class CryptoObject { protected: CryptoContext<Element> context; /*!< crypto context this object belongs to */ string keyTag; /*!< tag used to find the evaluation key needed for SHE/FHE operations */ public: CryptoObject(CryptoContext<Element> cc = 0, const string& tag = "") : context(cc), keyTag(tag) {} CryptoObject(const CryptoObject& rhs) { context = rhs.context; keyTag = rhs.keyTag; } CryptoObject(const CryptoObject&& rhs) { context = std::move(rhs.context); keyTag = std::move(rhs.keyTag); } virtual ~CryptoObject() {} const CryptoObject& operator=(const CryptoObject& rhs) { this->context = rhs.context; this->keyTag = rhs.keyTag; return *this; } const CryptoObject& operator=(const CryptoObject&& rhs) { this->context = std::move(rhs.context); this->keyTag = std::move(rhs.keyTag); return *this; } bool operator==(const CryptoObject& rhs) const { return context.get() == rhs.context.get() && keyTag == rhs.keyTag; } CryptoContext<Element> GetCryptoContext() const { return context; } const shared_ptr<LPCryptoParameters<Element>> GetCryptoParameters() const { return context->GetCryptoParameters(); } const EncodingParams GetEncodingParameters() const { return context->GetCryptoParameters()->GetEncodingParams(); } const string GetKeyTag() const { return keyTag; } void SetKeyTag(const string& tag) { keyTag = tag; } /** * SerializeCryptoObject serializes this header into a Serialized * @param serObj is used to store the serialized result. * @return true if successfully serialized */ bool SerializeCryptoObject(Serialized* serObj, bool includeContext = true) const; /** * DeserializeCryptoObject Populates this header from the deserialization of the Serialized * @param serObj contains the serialized object * @return true on success */ bool DeserializeCryptoObject(const Serialized& serObj, bool includesContext = true); }; /** * @brief CryptoContextFactory * * A class that contains static methods to generate new crypto contexts from user parameters * */ template<typename Element> class CryptoContextFactory { static vector<CryptoContext<Element>> AllContexts; public: static void ReleaseAllContexts(); static int GetContextCount(); static CryptoContext<Element> GetSingleContext(); static CryptoContext<Element> GetContext( shared_ptr<LPCryptoParameters<Element>> params, shared_ptr<LPPublicKeyEncryptionScheme<Element>> scheme); static CryptoContext<Element> GetContextForPointer( CryptoContextImpl<Element>* cc); static const vector<CryptoContext<Element>>& GetAllContexts() { return AllContexts; } /** * construct a PALISADE CryptoContextImpl for the LTV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextLTV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the LTV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextLTV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the LTV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param security level - root Hermite factor * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist sigma - distribution parameter for error distribution * @param numAdds - number/depth of homomorphic additions (assuming no other homomorphic operations are performed) * @param numMults - multiplicative depth (assuming no other homomorphic operations are performed) * @param numKeyswitches - depth of key switching/number of hops in proxy re-encryption (assuming no other homomorphic operations are performed) * @return new context */ static CryptoContext<Element> genCryptoContextLTV( const PlaintextModulus plaintextModulus, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches); /** * construct a PALISADE CryptoContextImpl for the LTV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param security level - root Hermite factor * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist sigma - distribution parameter for error distribution * @param numAdds - number/depth of homomorphic additions (assuming no other homomorphic operations are performed) * @param numMults - multiplicative depth (assuming no other homomorphic operations are performed) * @param numKeyswitches - depth of key switching/number of hops in proxy re-encryption (assuming no other homomorphic operations are performed) * @return new context */ static CryptoContext<Element> genCryptoContextLTV( EncodingParams encodingParams, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param delta - the plaintext scaling parameter floor(q/t) in BFV * @param mode - mode for generating secret keys (RLWE vs OPTIMIZED) * @param bigmodulus - large modulus used in tensoring of homomorphic multiplication * @param bigrootofunity - root of unity for bigmodulus * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @param bigmodulusarb - additional large modulus for bigmoduls for the case of general (non-power-of-two) cyclotomics * @param bigrootofunityarb - root of unity for bigmodulusarb * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, const std::string& delta, MODE mode = RLWE, const std::string& bigmodulus = "0", const std::string& bigrootofunity = "0", int depth = 0, int assuranceMeasure = 0, float securityLevel = 0, const std::string& bigmodulusarb = "0", const std::string& bigrootofunityarb = "0", int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param relinWindow bits in the base of digits in key switching/relinearization * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, float securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFV Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @return new context */ static CryptoContext<Element> genCryptoContextBFV( EncodingParams encodingParams, SecurityLevel securityLevel, usint relinWindow, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard secuirity level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window (bits in the base for digits) used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrns Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrns( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param plaintextModulus plaintext modulus * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( const PlaintextModulus plaintextModulus, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel root Hermite factor (lattice security parameter) * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, float securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BFVrnsB Scheme using the scheme's ParamsGen methods * @param encodingParams plaintext encoding parameters * @param securityLevel standard security level * @param dist distribution parameter for Gaussian noise generation * @param numAdds additive depth for homomorphic computations (assumes numMults and numKeySwitches are set to zero) * @param numMults multiplicative depth for homomorphic computations (assumes numAdds and numKeySwitches are set to zero) * @param numKeyswitches key-switching depth for homomorphic computations (assumes numAdds and numMults are set to zero) * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param maxDepth the maximum power of secret key for which the relinearization key is generated (by default, it is 2); setting it to a value larger than 2 adds support for homomorphic multiplication w/o relinearization * @param relinWindow the key switching window used for digit decomposition (0 - means to use only CRT decomposition) * @param dcrtBits size of "small" CRT moduli * @return new context */ static CryptoContext<Element> genCryptoContextBFVrnsB( EncodingParams encodingParams, SecurityLevel securityLevel, float dist, unsigned int numAdds, unsigned int numMults, unsigned int numKeyswitches, MODE mode = OPTIMIZED, int maxDepth = 2, uint32_t relinWindow = 0, size_t dcrtBits = 60); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the BGV Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param mode secret key distribution mode (RLWE [Gaussian noise] or OPTIMIZED [ternary uniform distribution]) * @param depth of supported computation circuit (not used; for future use) * @return new context */ static CryptoContext<Element> genCryptoContextBGV(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, MODE mode = RLWE, int depth = 1); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param plaintextModulus plaintext modulus * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, const PlaintextModulus plaintextmodulus, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the StehleSteinfeld Scheme * @param params ring parameters * @param encodingParams plaintext encoding parameters * @param relinWindow bits in the base of digits in key switching/relinearization * @param stdDev sigma - distribution parameter for error distribution * @param stdDev distribution parameter for secret key distribution * @param depth of supported computation circuit (not used; for future use) * @param assuranceMeasure alpha - effective bound for gaussians: - sqrt{alpha}*sigma..sqrt{alpha}*sigma * @param security level - root Hermite factor * @return new context */ static CryptoContext<Element> genCryptoContextStehleSteinfeld(shared_ptr<typename Element::Params> params, EncodingParams encodingParams, usint relinWindow, float stDev, float stDevStSt, int depth = 1, int assuranceMeasure = 9, float securityLevel = 1.006); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param plaintextModulus plaintext modulus * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, const PlaintextModulus ptModulus); /** * construct a PALISADE CryptoContextImpl for the Null Scheme * @param m cyclotomic order (ring dimension n = m/2 for power-of-two cyclotomics) * @param encodingParams plaintext encoding parameters * @return */ static CryptoContext<Element> genCryptoContextNull(unsigned int m, EncodingParams encodingParams); /** * Create a PALISADE CryptoContextImpl from a serialization * @param serObj * @return new context */ static CryptoContext<Element> DeserializeAndCreateContext(const Serialized& serObj); }; } #endif /* SRC_DEMO_PRE_CRYPTOCONTEXT_H_ */
DRB008-indirectaccess4-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: [email protected], [email protected], [email protected], [email protected], [email protected]) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* Two pointers have a distance of 12 (xa2 - xa1 = 12). They are used as base addresses for indirect array accesses using an index set (another array). The index set has two indices with distance of 12 : indexSet[1]- indexSet[0] = 533 - 521 = 12 So xa1[idx] and xa2[idx] may cause loop carried dependence for N=0 and N=3. We use the default loop scheduling (static even) in OpenMP. It is possible that two dependent iterations will be scheduled within a same chunk to a same thread. So there is no runtime data races. N is 180, two iteraions with N=0 and N= 1 have loop carried dependences. For static even scheduling, we must have at least 180 threads (180/180=1 iterations) so iteration 0 and 1 will be scheduled to two different threads. Data race pair: xa1[idx]@128:5 vs. xa2[idx]@129:5 */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #define N 180 int indexSet[N] = { 521, 533, 525, 527, 529, 531, // 521+12=533 547, 549, 551, 553, 555, 557, 573, 575, 577, 579, 581, 583, 599, 601, 603, 605, 607, 609, 625, 627, 629, 631, 633, 635, 651, 653, 655, 657, 659, 661, 859, 861, 863, 865, 867, 869, 885, 887, 889, 891, 893, 895, 911, 913, 915, 917, 919, 921, 937, 939, 941, 943, 945, 947, 963, 965, 967, 969, 971, 973, 989, 991, 993, 995, 997, 999, 1197, 1199, 1201, 1203, 1205, 1207, 1223, 1225, 1227, 1229, 1231, 1233, 1249, 1251, 1253, 1255, 1257, 1259, 1275, 1277, 1279, 1281, 1283, 1285, 1301, 1303, 1305, 1307, 1309, 1311, 1327, 1329, 1331, 1333, 1335, 1337, 1535, 1537, 1539, 1541, 1543, 1545, 1561, 1563, 1565, 1567, 1569, 1571, 1587, 1589, 1591, 1593, 1595, 1597, 1613, 1615, 1617, 1619, 1621, 1623, 1639, 1641, 1643, 1645, 1647, 1649, 1665, 1667, 1669, 1671, 1673, 1675, 1873, 1875, 1877, 1879, 1881, 1883, 1899, 1901, 1903, 1905, 1907, 1909, 1925, 1927, 1929, 1931, 1933, 1935, 1951, 1953, 1955, 1957, 1959, 1961, 1977, 1979, 1981, 1983, 1985, 1987, 2003, 2005, 2007, 2009, 2011, 2013}; int main (int argc, char* argv[]) { double * base = (double*) malloc(sizeof(double)* (2013+12+1)); if (base == 0) { printf ("Error in malloc(). Aborting ...\n"); return 1; } double * xa1 = base; double * xa2 = xa1 + 12; int i; // initialize segments touched by indexSet #pragma omp parallel for private(i ) for (i =521; i<= 2025; ++i) { base[i]=0.5*i; } for (i =0; i< N; ++i) { int idx = indexSet[i]; xa1[idx]+= 1.0; xa2[idx]+= 3.0; } printf("x1[999]=%f xa2[1285]=%f\n", xa1[999], xa2[1285]); free (base); return 0; }
GB_unop__identity_fp32_int64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_fp32_int64 // op(A') function: GB_unop_tran__identity_fp32_int64 // C type: float // A type: int64_t // cast: float cij = (float) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ float z = (float) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = (float) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FP32 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_fp32_int64 ( float *Cx, // Cx and Ax may be aliased const int64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; float z = (float) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_fp32_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
schedule.c
#include <stdio.h> #include <omp.h> int main() { omp_set_num_threads(4); #pragma omp parallel for schedule(static, 2) for (int i = 0; i < 10; i++) { printf("%d %d\n", i, omp_get_thread_num()); // The extra 2 iteration is assigned to thread 0 } printf("\n\n"); #pragma omp parallel for schedule(dynamic, 2) for (int i = 0; i < 10; i++) { printf("%d %d\n", i, omp_get_thread_num()); } printf("\n\n"); #pragma omp parallel for schedule(guided, 2) for (int i = 0; i < 10; i++) { printf("%d %d\n", i, omp_get_thread_num()); } }
FastTree-2.1.10.c
/* * FastTree -- inferring approximately-maximum-likelihood trees for large * multiple sequence alignments. * * Morgan N. Price * http://www.microbesonline.org/fasttree/ * * Thanks to Jim Hester of the Cleveland Clinic Foundation for * providing the first parallel (OpenMP) code, Siavash Mirarab of * UT Austin for implementing the WAG option, Samuel Shepard * at the CDC for suggesting and helping with the -quote option, and * Aaron Darling (University of Technology, Sydney) for numerical changes * for wide alignments of closely-related sequences. * * Copyright (C) 2008-2015 The Regents of the University of California * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * or visit http://www.gnu.org/copyleft/gpl.html * * Disclaimer * * NEITHER THE UNITED STATES NOR THE UNITED STATES DEPARTMENT OF ENERGY, * NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, * OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, * COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, APPARATUS, PRODUCT, * OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE * PRIVATELY OWNED RIGHTS. */ /* * To compile FastTree, do: * gcc -Wall -O3 -finline-functions -funroll-loops -o FastTree -lm FastTree.c * Use -DNO_SSE to turn off use of SSE3 instructions * (should not be necessary because compiler should not set __SSE__ if * not available, and modern mallocs should return 16-byte-aligned values) * Use -DOPENMP -fopenmp to use multiple threads (note, old versions of gcc * may not support -fopenmp) * Use -DTRACK_MEMORY if you want detailed reports of memory usage, * but results are not correct above 4GB because mallinfo stores int values. * It also makes FastTree run significantly slower. * * To get usage guidance, do: * FastTree -help * * FastTree uses profiles instead of a distance matrix, and computes * support values for each split from the profiles of the 4 nodes * around the split. It stores a profile for each node and a average * profile over all active nodes (the "out-profile" for computing the * total sum of distance to other nodes). The neighbor joining phase * requires O(N*L*a) space, where N is the number of sequences, L is * the alignment width, and a is the alphabet size. The top-hits * heuristic requires an additional O(N sqrt(N)) memory. After * neighbor-joining, FastTree improves the topology with * nearest-neighbor interchanges (NNIs) and subtree-prune-regraft * moves (SPRs), which does not have a significant additional memory * requirement. (We need only store "up-profiles" on the path from our * current traversal point to the root.) These take O(NLa) time per * round, and with default settings, O(N log(N) L a) time total. * FastTree further improves the topology with maximum-likelihood * NNIs, using similar data structures and complexity, but with a * higher constant factor, and now the "profiles" are actually * posterior distributions for that subtree. Finally, FastTree * resamples the site likelihoods around each NNI and uses * the Shimodaira Hasegawa test to estimate the reliability of each split. * * Overview of the neighbor-joining phase: * * Although FastTree uses a log correction on profile distances to * account for multiple substitutions when doing NNIs and SPRs, the * operations on the profiles themselves involve "additive" distances * -- either %different (for nucleotide) or by using an amino acid * similarity matrix (for proteins). If we are using %different as * our distance matrix then * * Profile_distance(A,B) = 1 - sum over characters of freq(A)*freq(B) * * and we can average this value over positions. Positions with gaps * are weighted by %ungapped(A) * %ungapped(B). * * If we are using an amino acid dissimilarity matrix D(i,j) then at * each position * * Profile_distance(A,B) = sum(i,j) freq(A==i) * freq(B==j) * D(i,j) * = sum(k) Ak * Bk * Lambda(k) * * where k iterates over 20 eigenvectors, Lambda(k) is the eigenvalue, * and if A==i, then Ak is the kth column of the inverse of the * eigenvector matrix. * * The exhaustive approach (-slow) takes O(N**3*L*a) time, but * this can be reduced to as little as O(N**(3/2)*log(N)*L*a) time * by using heuristics. * * It uses a combination of three heuristics: a visible set similar to * that of FastTree (Elias & Lagergren 2005), a local hill-climbing * search for a better join (as in relaxed neighbor-joining, Evans et * al. 2006), and a top-hit list to reduce the search space (see * below). * * The "visible" set stores, for each node, the best join for that * node, as identified at some point in the past * * If top-hits are not being used, then the neighbor-joining phase can * be summarized as: * * Compute the out-profile by averaging the leaves * Compute the out-distance of each leaf quickly, using the out-profile * Compute the visible set (or approximate it using top-hits, see below) * Until we're down to 3 active nodes: * Find the best join in the visible set * (This involves recomputing the neighbor-joining criterion, * as out-distances and #active nodes may have changed) * Follow a chain of best hits (again recomputing the criterion) * until we find a locally best join, as in relaxed neighbor joining * Create a profile of the parent node, either using simple averages (default) * or using weighted joining as in BIONJ (if -bionj was specified) * Update the out-profile and the out-distances * Update the visible set: * find the best join for the new joined node * replace hits to the joined children with hits to the parent * if we stumble across a join for the new node that is better * than the corresponding entry in the visible set, "reset" * that entry. * * For each iteration, this method does * O(N) work to find the best hit in the visible set * O(L*N*a*log(N)) work to do the local search, where log(N) * is a pessimistic estimate of the number of iterations. In * practice, we average <1 iteration for 2,000 sequences. * With -fastest, this step is omitted. * O(N*a) work to compute the joined profile and update the out-profile * O(L*N*a) work to update the out-distances * O(L*N*a) work to compare the joined profile to the other nodes * (to find the new entry in the visible set) * * and there are N-3 iterations, so it takes O(N**2 * L * log(N) * a) time. * * The profile distances give exactly the same result as matrix * distances in neighbor-joining or BIONJ would if there are no gaps * in the alignment. If there are gaps, then it is an * approximation. To get the same result we also store a "diameter" * for each node (diameter is 0 for leaves). * * In the simpler case (NJ rather than BIONJ), when we join A and B to * give a new node AB, * * Profile(AB) = (A+B)/2 * Profile_distance(AB,C) = (Profile_distance(A,C)+Profile_distance(B,C))/2 * because the formulas above are linear * * And according to the neighor-joining rule, * d(AB,C) = (d(A,C)+d(B,C)-d(A,B))/2 * * and we can achieve the same value by writing * diameter(AB) = pd(A,B)/2 * diameter(leaf) = 0 * d(A,B) = pd(A,B) - diameter(A) - diameter(B) * * because * d(AB,C) = (d(A,C)+d(B,C)-d(A,B))/2 * = (pd(A,C)-diam(A)-diam(C)+pd(B,C)-diam(B)-diam(C)-d(A,B)+diam(A)+diam(B))/2 * = (pd(A,C)+pd(B,C))/2 - diam(C) - pd(A,B) * = pd(AB,C) - diam(AB) - diam(C) * * If we are using BIONJ, with weight lambda for the join: * Profile(AB) = lambda*A + (1-lambda)*B * then a similar argument gives * diam(AB) = lambda*diam(A) + (1-lambda)*diam(B) + lambda*d(A,AB) + (1-lambda)*d(B,AB), * * where, as in neighbor joining, * d(A,AB) = d(A,B) + (total out_distance(A) - total out_distance(B))/(n-2) * * A similar recursion formula works for the "variance" matrix of BIONJ, * var(AB,C) = lambda*var(A,C) + (1-lambda)*var(B,C) - lambda*(1-lambda)*var(A,B) * is equivalent to * var(A,B) = pv(A,B) - vd(A) - vd(B), where * pv(A,B) = pd(A,B) * vd(A) = 0 for leaves * vd(AB) = lambda*vd(A) + (1-lambda)*vd(B) + lambda*(1-lambda)*var(A,B) * * The top-hist heuristic to reduce the work below O(N**2*L) stores a top-hit * list of size m=sqrt(N) for each active node. * * The list can be initialized for all the leaves in sub (N**2 * L) time as follows: * Pick a "seed" sequence and compare it to all others * Store the top m hits of the seed as its top-hit list * Take "close" hits of the seed(within the top m, and see the "close" parameter), * and assume that their top m hits lie within the top 2*m hits of the seed. * So, compare them to the seed's neighors (if they do not already * have a top hit list) and set their top hits. * * This method does O(N*L) work for each seed, or O(N**(3/2)*L) work total. * * To avoid doing O(N*L) work at each iteration, we need to avoid * updating the visible set and the out-distances. So, we use "stale" * out-distances, and when searching the visible set for the best hit, * we only inspect the top m=sqrt(N) entries. We then update those * out-distances (up to 2*m*L*a work) and then find the best hit. * * To avoid searching the entire visible set, FastTree keeps * and updates a list of the top sqrt(N) entries in the visible set. * This costs O(sqrt(N)) time per join to find the best entry and to * update, or (N sqrt(N)) time overall. * * Similarly, when doing the local hill-climbing, we avoid O(N*L) work * by only considering the top-hits for the current node. So this adds * O(m*a*log(N)) work per iteration. * * When we join two nodes, we compute profiles and update the * out-profile as before. We need to compute the best hits of the node * -- we merge the lists for the children and select the best up-to-m * hits. If the top hit list contains a stale node we replace it with * its parent. If we still have <m/2 entries, we do a "refresh". * * In a "refresh", similar to the fast top-hit computation above, we * compare the "seed", in this case the new joined node, to all other * nodes. We compare its close neighbors (the top m hits) to all * neighbors (the top 2*m hits) and update the top-hit lists of all * neighbors (by merging to give a list of 3*m entries and then * selecting the best m entries). * * Finally, during these processes we update the visible sets for * other nodes with better hits if we find them, and we set the * visible entry for the new joined node to the best entry in its * top-hit list. (And whenever we update a visible entry, we * do O(sqrt(N)) work to update the top-visible list.) * These udpates are not common so they do not alter the * O(N sqrt(N) log(N) L a) total running time for the joining phase. * * Second-level top hits * * With -fastest or with -2nd, FastTree uses an additional "2nd-level" top hits * heuristic to reduce the running time for the top-hits phase to * O(N**1.25 L) and for the neighbor-joining phase to O(N**1.25 L a). * This also reduces the memory usage for the top-hits lists to * O(N**1.25), which is important for alignments with a million * sequences. The key idea is to store just q = sqrt(m) top hits for * most sequences. * * Given the neighbors of A -- either for a seed or for a neighbor * from the top-hits heuristic, if B is within the top q hits of A, we * set top-hits(B) from the top 3*q top-hits of A. And, we record that * A is the "source" of the hits for B, so if we run low on hits for * B, instead of doing a full refresh, we can do top-hits(B) := * top-hits(B) union top-hits(active_ancestor(A)). * During a refresh, these "2nd-level" top hits are updated just as * normal, but the source is maintained and only q entries are stored, * until we near the end of the neighbor joining phase (until the * root as 2*m children or less). * * Parallel execution with OpenMP * * If you compile FastTree with OpenMP support, it will take * advantage of multiple CPUs on one machine. It will parallelize: * * The top hits phase * Comparing one node to many others during the NJ phase (the simplest kind of join) * The refresh phase * Optimizing likelihoods for 3 alternate topologies during ML NNIs and ML supports * (only 3 threads can be used) * * This accounts for most of the O(N L a) or slower steps except for * minimum-evolution NNIs (which are fast anyway), minimum-evolution SPRs, * selecting per-site rates, and optimizing branch lengths outside of ML NNIs. * * Parallelizing the top hits phase may lead to a slight change in the tree, * as some top hits are computed from different (and potentially less optimal source). * This means that results on repeated runs may not be 100% identical. * However, this should not have any significant effect on tree quality * after the NNIs and SPRs. * * The OpenMP code also turns off the star-topology test during ML * NNIs, which may lead to slight improvements in likelihood. */ #include <stdio.h> #include <stdbool.h> #include <string.h> #include <assert.h> #include <math.h> #include <stdlib.h> #include <sys/time.h> #include <ctype.h> #include <unistd.h> #ifdef TRACK_MEMORY /* malloc.h apparently doesn't exist on MacOS */ #include <malloc.h> #endif /* Compile with -DOPENMP to turn on multithreading */ #ifdef OPENMP #include <omp.h> #endif /* By default, tries to compile with SSE instructions for greater speed. But if compiled with -DUSE_DOUBLE, uses double precision instead of single-precision floating point (2x memory required), does not use SSE, and allows much shorter branch lengths. */ #ifdef __SSE__ #if !defined(NO_SSE) && !defined(USE_DOUBLE) #define USE_SSE3 #endif #endif #ifdef USE_DOUBLE #define SSE_STRING "Double precision (No SSE3)" typedef double numeric_t; #define ScanNumericSpec "%lf" #else typedef float numeric_t; #define ScanNumericSpec "%f" #endif #ifdef USE_SSE3 #define SSE_STRING "SSE3" #define ALIGNED __attribute__((aligned(16))) #define IS_ALIGNED(X) ((((unsigned long) new) & 15L) == 0L) #include <xmmintrin.h> #else #define ALIGNED #define IS_ALIGNED(X) 1 #ifndef USE_DOUBLE #define SSE_STRING "No SSE3" #endif #endif /* USE_SSE3 */ #define FT_VERSION "2.1.10" char *usage = " FastTree protein_alignment > tree\n" " FastTree < protein_alignment > tree\n" " FastTree -out tree protein_alignment\n" " FastTree -nt nucleotide_alignment > tree\n" " FastTree -nt -gtr < nucleotide_alignment > tree\n" " FastTree < nucleotide_alignment > tree\n" "FastTree accepts alignments in fasta or phylip interleaved formats\n" "\n" "Common options (must be before the alignment file):\n" " -quiet to suppress reporting information\n" " -nopr to suppress progress indicator\n" " -log logfile -- save intermediate trees, settings, and model details\n" " -fastest -- speed up the neighbor joining phase & reduce memory usage\n" " (recommended for >50,000 sequences)\n" " -n <number> to analyze multiple alignments (phylip format only)\n" " (use for global bootstrap, with seqboot and CompareToBootstrap.pl)\n" " -nosupport to not compute support values\n" " -intree newick_file to set the starting tree(s)\n" " -intree1 newick_file to use this starting tree for all the alignments\n" " (for faster global bootstrap on huge alignments)\n" " -pseudo to use pseudocounts (recommended for highly gapped sequences)\n" " -gtr -- generalized time-reversible model (nucleotide alignments only)\n" " -lg -- Le-Gascuel 2008 model (amino acid alignments only)\n" " -wag -- Whelan-And-Goldman 2001 model (amino acid alignments only)\n" " -quote -- allow spaces and other restricted characters (but not ' ) in\n" " sequence names and quote names in the output tree (fasta input only;\n" " FastTree will not be able to read these trees back in)\n" " -noml to turn off maximum-likelihood\n" " -nome to turn off minimum-evolution NNIs and SPRs\n" " (recommended if running additional ML NNIs with -intree)\n" " -nome -mllen with -intree to optimize branch lengths for a fixed topology\n" " -cat # to specify the number of rate categories of sites (default 20)\n" " or -nocat to use constant rates\n" " -gamma -- after optimizing the tree under the CAT approximation,\n" " rescale the lengths to optimize the Gamma20 likelihood\n" " -constraints constraintAlignment to constrain the topology search\n" " constraintAlignment should have 1s or 0s to indicates splits\n" " -expert -- see more options\n" "For more information, see http://www.microbesonline.org/fasttree/\n"; char *expertUsage = "FastTree [-nt] [-n 100] [-quote] [-pseudo | -pseudo 1.0]\n" " [-boot 1000 | -nosupport]\n" " [-intree starting_trees_file | -intree1 starting_tree_file]\n" " [-quiet | -nopr]\n" " [-nni 10] [-spr 2] [-noml | -mllen | -mlnni 10]\n" " [-mlacc 2] [-cat 20 | -nocat] [-gamma]\n" " [-slow | -fastest] [-2nd | -no2nd] [-slownni] [-seed 1253] \n" " [-top | -notop] [-topm 1.0 [-close 0.75] [-refresh 0.8]]\n" " [-matrix Matrix | -nomatrix] [-nj | -bionj]\n" " [-lg] [-wag] [-nt] [-gtr] [-gtrrates ac ag at cg ct gt] [-gtrfreq A C G T]\n" " [ -constraints constraintAlignment [ -constraintWeight 100.0 ] ]\n" " [-log logfile]\n" " [ alignment_file ]\n" " [ -out output_newick_file | > newick_tree]\n" "\n" "or\n" "\n" "FastTree [-nt] [-matrix Matrix | -nomatrix] [-rawdist] -makematrix [alignment]\n" " [-n 100] > phylip_distance_matrix\n" "\n" " FastTree supports fasta or phylip interleaved alignments\n" " By default FastTree expects protein alignments, use -nt for nucleotides\n" " FastTree reads standard input if no alignment file is given\n" "\n" "Input/output options:\n" " -n -- read in multiple alignments in. This only\n" " works with phylip interleaved format. For example, you can\n" " use it with the output from phylip's seqboot. If you use -n, FastTree\n" " will write 1 tree per line to standard output.\n" " -intree newickfile -- read the starting tree in from newickfile.\n" " Any branch lengths in the starting trees are ignored.\n" " -intree with -n will read a separate starting tree for each alignment.\n" " -intree1 newickfile -- read the same starting tree for each alignment\n" " -quiet -- do not write to standard error during normal operation (no progress\n" " indicator, no options summary, no likelihood values, etc.)\n" " -nopr -- do not write the progress indicator to stderr\n" " -log logfile -- save intermediate trees so you can extract\n" " the trees and restart long-running jobs if they crash\n" " -log also reports the per-site rates (1 means slowest category)\n" " -quote -- quote sequence names in the output and allow spaces, commas,\n" " parentheses, and colons in them but not ' characters (fasta files only)\n" "\n" "Distances:\n" " Default: For protein sequences, log-corrected distances and an\n" " amino acid dissimilarity matrix derived from BLOSUM45\n" " or for nucleotide sequences, Jukes-Cantor distances\n" " To specify a different matrix, use -matrix FilePrefix or -nomatrix\n" " Use -rawdist to turn the log-correction off\n" " or to use %different instead of Jukes-Cantor\n" "\n" " -pseudo [weight] -- Use pseudocounts to estimate distances between\n" " sequences with little or no overlap. (Off by default.) Recommended\n" " if analyzing the alignment has sequences with little or no overlap.\n" " If the weight is not specified, it is 1.0\n" "\n" "Topology refinement:\n" " By default, FastTree tries to improve the tree with up to 4*log2(N)\n" " rounds of minimum-evolution nearest-neighbor interchanges (NNI),\n" " where N is the number of unique sequences, 2 rounds of\n" " subtree-prune-regraft (SPR) moves (also min. evo.), and\n" " up to 2*log(N) rounds of maximum-likelihood NNIs.\n" " Use -nni to set the number of rounds of min. evo. NNIs,\n" " and -spr to set the rounds of SPRs.\n" " Use -noml to turn off both min-evo NNIs and SPRs (useful if refining\n" " an approximately maximum-likelihood tree with further NNIs)\n" " Use -sprlength set the maximum length of a SPR move (default 10)\n" " Use -mlnni to set the number of rounds of maximum-likelihood NNIs\n" " Use -mlacc 2 or -mlacc 3 to always optimize all 5 branches at each NNI,\n" " and to optimize all 5 branches in 2 or 3 rounds\n" " Use -mllen to optimize branch lengths without ML NNIs\n" " Use -mllen -nome with -intree to optimize branch lengths on a fixed topology\n" " Use -slownni to turn off heuristics to avoid constant subtrees (affects both\n" " ML and ME NNIs)\n" "\n" "Maximum likelihood model options:\n" " -lg -- Le-Gascuel 2008 model instead of (default) Jones-Taylor-Thorton 1992 model (a.a. only)\n" " -wag -- Whelan-And-Goldman 2001 model instead of (default) Jones-Taylor-Thorton 1992 model (a.a. only)\n" " -gtr -- generalized time-reversible instead of (default) Jukes-Cantor (nt only)\n" " -cat # -- specify the number of rate categories of sites (default 20)\n" " -nocat -- no CAT model (just 1 category)\n" " -gamma -- after the final round of optimizing branch lengths with the CAT model,\n" " report the likelihood under the discrete gamma model with the same\n" " number of categories. FastTree uses the same branch lengths but\n" " optimizes the gamma shape parameter and the scale of the lengths.\n" " The final tree will have rescaled lengths. Used with -log, this\n" " also generates per-site likelihoods for use with CONSEL, see\n" " GammaLogToPaup.pl and documentation on the FastTree web site.\n" "\n" "Support value options:\n" " By default, FastTree computes local support values by resampling the site\n" " likelihoods 1,000 times and the Shimodaira Hasegawa test. If you specify -nome,\n" " it will compute minimum-evolution bootstrap supports instead\n" " In either case, the support values are proportions ranging from 0 to 1\n" "\n" " Use -nosupport to turn off support values or -boot 100 to use just 100 resamples\n" " Use -seed to initialize the random number generator\n" "\n" "Searching for the best join:\n" " By default, FastTree combines the 'visible set' of fast neighbor-joining with\n" " local hill-climbing as in relaxed neighbor-joining\n" " -slow -- exhaustive search (like NJ or BIONJ, but different gap handling)\n" " -slow takes half an hour instead of 8 seconds for 1,250 proteins\n" " -fastest -- search the visible set (the top hit for each node) only\n" " Unlike the original fast neighbor-joining, -fastest updates visible(C)\n" " after joining A and B if join(AB,C) is better than join(C,visible(C))\n" " -fastest also updates out-distances in a very lazy way,\n" " -fastest sets -2nd on as well, use -fastest -no2nd to avoid this\n" "\n" "Top-hit heuristics:\n" " By default, FastTree uses a top-hit list to speed up search\n" " Use -notop (or -slow) to turn this feature off\n" " and compare all leaves to each other,\n" " and all new joined nodes to each other\n" " -topm 1.0 -- set the top-hit list size to parameter*sqrt(N)\n" " FastTree estimates the top m hits of a leaf from the\n" " top 2*m hits of a 'close' neighbor, where close is\n" " defined as d(seed,close) < 0.75 * d(seed, hit of rank 2*m),\n" " and updates the top-hits as joins proceed\n" " -close 0.75 -- modify the close heuristic, lower is more conservative\n" " -refresh 0.8 -- compare a joined node to all other nodes if its\n" " top-hit list is less than 80% of the desired length,\n" " or if the age of the top-hit list is log2(m) or greater\n" " -2nd or -no2nd to turn 2nd-level top hits heuristic on or off\n" " This reduces memory usage and running time but may lead to\n" " marginal reductions in tree quality.\n" " (By default, -fastest turns on -2nd.)\n" "\n" "Join options:\n" " -nj: regular (unweighted) neighbor-joining (default)\n" " -bionj: weighted joins as in BIONJ\n" " FastTree will also weight joins during NNIs\n" "\n" "Constrained topology search options:\n" " -constraints alignmentfile -- an alignment with values of 0, 1, and -\n" " Not all sequences need be present. A column of 0s and 1s defines a\n" " constrained split. Some constraints may be violated\n" " (see 'violating constraints:' in standard error).\n" " -constraintWeight -- how strongly to weight the constraints. A value of 1\n" " means a penalty of 1 in tree length for violating a constraint\n" " Default: 100.0\n" "\n" "For more information, see http://www.microbesonline.org/fasttree/\n" " or the comments in the source code\n"; ; #define MAXCODES 20 #define NOCODE 127 /* Note -- sequence lines longer than BUFFER_SIZE are allowed, but FASTA header lines must be within this limit */ #define BUFFER_SIZE 5000 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #define MAX(X,Y) ((X) > (Y) ? (X) : (Y)) typedef struct { int nPos; int nSeq; char **names; char **seqs; int nSaved; /* actual allocated size of names and seqs */ } alignment_t; /* For each position in a profile, we have a weight (% non-gapped) and a frequency vector. (If using a matrix, the frequency vector is in eigenspace). We also store codes for simple profile positions (all gaps or only 1 value) If weight[pos] > 0 && codes[pos] == NOCODE then we store the vector vectors itself is sets of nCodes long, so the vector for the ith nonconstant position starts at &vectors[nCodes*i] To speed up comparison of outprofile to a sequence or other simple profile, we also (for outprofiles) store codeDist[iPos*nCodes+k] = dist(k,profile[iPos]) For constraints, we store a vector of nOn and nOff If not using constraints, those will be NULL */ typedef struct { /* alignment profile */ numeric_t *weights; unsigned char *codes; numeric_t *vectors; /* NULL if no non-constant positions, e.g. for leaves */ int nVectors; numeric_t *codeDist; /* Optional -- distance to each code at each position */ /* constraint profile */ int *nOn; int *nOff; } profile_t; /* A visible node is a pair of nodes i, j such that j is the best hit of i, using the neighbor-joining criterion, at the time the comparison was made, or approximately so since then. Note that variance = dist because in BIONJ, constant factors of variance do not matter, and because we weight ungapped sequences higher naturally when averaging profiles, so we do not take this into account in the computation of "lambda" for BIONJ. For the top-hit list heuristic, if the top hit list becomes "too short", we store invalid entries with i=j=-1 and dist/criterion very high. */ typedef struct { int i, j; numeric_t weight; /* Total product of weights (maximum value is nPos) This is needed for weighted joins and for pseudocounts, but not in most other places. For example, it is not maintained by the top hits code */ numeric_t dist; /* The uncorrected distance (includes diameter correction) */ numeric_t criterion; /* changes when we update the out-profile or change nActive */ } besthit_t; typedef struct { int nChild; int child[3]; } children_t; typedef struct { /* Distances between amino acids */ numeric_t distances[MAXCODES][MAXCODES]; /* Inverse of the eigenvalue matrix, for rotating a frequency vector into eigenspace so that profile similarity computations are O(alphabet) not O(alphabet*alphabet) time. */ numeric_t eigeninv[MAXCODES][MAXCODES]; numeric_t eigenval[MAXCODES]; /* eigenvalues */ /* eigentot=eigeninv times the all-1s frequency vector useful for normalizing rotated frequency vectors */ numeric_t eigentot[MAXCODES]; /* codeFreq is the transpose of the eigeninv matrix is the rotated frequency vector for each code */ numeric_t codeFreq[MAXCODES][MAXCODES]; numeric_t gapFreq[MAXCODES]; } distance_matrix_t; /* A transition matrix gives the instantaneous rate of change of frequencies df/dt = M . f which is solved by f(t) = exp(M) . f(0) and which is not a symmetric matrix because of non-uniform stationary frequencies stat, so that M stat = 0 M(i,j) is instantaneous rate of j -> i, not of i -> j S = diag(sqrt(stat)) is a correction so that M' = S**-1 M S is symmetric Let W L W**-1 = M' be an eigendecomposition of M' Because M' is symmetric, W can be a rotation, and W**-1 = t(W) Set V = S*W M = V L V**-1 is an eigendecomposition of M Note V**-1 = W**-1 S**-1 = t(W) S**-1 Evolution by time t is given by exp(M*t) = V exp(L*t) V**-1 P(A & B | t) = B . exp(M*t) . (A * stat) note this is *not* the same as P(A->B | t) and we can reduce some of the computations from O(a**2) to O(a) time, where a is the alphabet size, by storing frequency vectors as t(V) . f = t(W) . t(S) . f Then P(f0 & f1 | t) = f1 . exp(M*t) . f0 * (f0 . stat) = sum(r0j * r1j * exp(l_j*t)) where r0 and r1 are the transformed vectors Posterior distribution of P given children f0 and f1 is given by P(i | f0, f1, t0, t1) = stat * P(i->f0 | t0) * P(i->f1 | t1) = P(i & f0 | t0) * P(i & f1 | t1) / stat ~ (V . exp(t0*L) . r0) * (V . exp(t1*L) . r1) / stat When normalize this posterior distribution (to sum to 1), divide by stat, and transform by t(V) -- this is the "profile" of internal nodes To eliminate the O(N**2) step of transforming by t(V), if the posterior distribution of an amino acid is near 1 then we can approximate it by P(i) ~= (i==A) * w + nearP(i) * (1-w), where w is fit so that P(i==A) is correct nearP = Posterior(i | i, i, 0.1, 0.1) [0.1 is an arbitrary choice] and we confirm that the approximation works well before we use it. Given this parameter w we can set rotated_posterior = rotation(w * (i==A)/stat + (1-w) * nearP/stat) = codeFreq(A) * w/stat(A) + nearFreq(A) * (1-w) */ typedef struct { numeric_t stat[MAXCODES]; /* The stationary distribution */ numeric_t statinv[MAXCODES]; /* 1/stat */ /* the eigenmatrix, with the eigenvectors as columns and rotations of individual characters as rows. Also includes a NOCODE entry for gaps */ numeric_t codeFreq[NOCODE+1][MAXCODES]; numeric_t eigeninv[MAXCODES][MAXCODES]; /* Inverse of eigenmatrix */ numeric_t eigeninvT[MAXCODES][MAXCODES]; /* transpose of eigeninv */ numeric_t eigenval[MAXCODES]; /* Eigenvalues */ /* These are for approximate posteriors (off by default) */ numeric_t nearP[MAXCODES][MAXCODES]; /* nearP[i][j] = P(parent=j | both children are i, both lengths are 0.1 */ numeric_t nearFreq[MAXCODES][MAXCODES]; /* rotation of nearP/stat */ } transition_matrix_t; typedef struct { int nRateCategories; numeric_t *rates; /* 1 per rate category */ unsigned int *ratecat; /* 1 category per position */ } rates_t; typedef struct { /* The input */ int nSeq; int nPos; char **seqs; /* the aligment sequences array (not reallocated) */ distance_matrix_t *distance_matrix; /* a pointer (not reallocated), or NULL if using %identity distance */ transition_matrix_t *transmat; /* a pointer (is allocated), or NULL for Jukes-Cantor */ /* Topological constraints are represented for each sequence as binary characters with values of '0', '1', or '-' (for missing data) Sequences that have no constraint may have a NULL string */ int nConstraints; char **constraintSeqs; /* The profile data structures */ int maxnode; /* The next index to allocate */ int maxnodes; /* Space allocated in data structures below */ profile_t **profiles; /* Profiles of leaves and intermediate nodes */ numeric_t *diameter; /* To correct for distance "up" from children (if any) */ numeric_t *varDiameter; /* To correct variances for distance "up" */ numeric_t *selfdist; /* Saved for use in some formulas */ numeric_t *selfweight; /* Saved for use in some formulas */ /* Average profile of all active nodes, the "outprofile" * If all inputs are ungapped, this has weight 1 (not nSequences) at each position * The frequencies all sum to one (or that is implied by the eigen-representation) */ profile_t *outprofile; double totdiam; /* We sometimes use stale out-distances, so we remember what nActive was */ numeric_t *outDistances; /* Sum of distances to other active (parent==-1) nodes */ int *nOutDistActive; /* What nActive was when this outDistance was computed */ /* the inferred tree */ int root; /* index of the root. Unlike other internal nodes, it has 3 children */ int *parent; /* -1 or index of parent */ children_t *child; numeric_t *branchlength; /* Distance to parent */ numeric_t *support; /* 1 for high-confidence nodes */ /* auxilliary data for maximum likelihood (defaults to 1 category of rate=1.0) */ rates_t rates; } NJ_t; /* Uniquify sequences in an alignment -- map from indices in the alignment to unique indicies in a NJ_t */ typedef struct { int nSeq; int nUnique; int *uniqueFirst; /* iUnique -> iAln */ int *alnNext; /* iAln -> next, or -1 */ int *alnToUniq; /* iAln -> iUnique, or -1 if another was the exemplar */ char **uniqueSeq; /* indexed by iUniq -- points to strings allocated elsewhere */ } uniquify_t; /* Describes which switch to do */ typedef enum {ABvsCD,ACvsBD,ADvsBC} nni_t; /* A list of these describes a chain of NNI moves in a rooted tree, making up, in total, an SPR move */ typedef struct { int nodes[2]; double deltaLength; /* change in tree length for this step (lower is better) */ } spr_step_t; /* Keep track of hits for the top-hits heuristic without wasting memory j = -1 means empty If j is an inactive node, this may be replaced by that node's parent (and dist recomputed) */ typedef struct { int j; numeric_t dist; } hit_t; typedef struct { int nHits; /* the allocated and desired size; some of them may be empty */ hit_t *hits; int hitSource; /* where to refresh hits from if a 2nd-level top-hit list, or -1 */ int age; /* number of joins since a refresh */ } top_hits_list_t; typedef struct { int m; /* size of a full top hits list, usually sqrt(N) */ int q; /* size of a 2nd-level top hits, usually sqrt(m) */ int maxnodes; top_hits_list_t *top_hits_lists; /* one per node */ hit_t *visible; /* the "visible" (very best) hit for each node */ /* The top-visible set is a subset, usually of size m, of the visible set -- it is the set of joins to select from Each entry is either a node whose visible set entry has a good (low) criterion, or -1 for empty, or is an obsolete node (which is effectively the same). Whenever we update the visible set, should also call UpdateTopVisible() which ensures that none of the topvisible set are stale (that is, they all point to an active node). */ int nTopVisible; /* nTopVisible = m * topvisibleMult */ int *topvisible; int topvisibleAge; /* joins since the top-visible list was recomputed */ #ifdef OPENMP /* 1 lock to read or write any top hits list, no thread grabs more than one */ omp_lock_t *locks; #endif } top_hits_t; /* Global variables */ /* Options */ int verbose = 1; int showProgress = 1; int slow = 0; int fastest = 0; bool useTopHits2nd = false; /* use the second-level top hits heuristic? */ int bionj = 0; double tophitsMult = 1.0; /* 0 means compare nodes to all other nodes */ double tophitsClose = -1.0; /* Parameter for how close is close; also used as a coverage req. */ double topvisibleMult = 1.5; /* nTopVisible = m * topvisibleMult; 1 or 2 did not make much difference in either running time or accuracy so I chose a compromise. */ double tophitsRefresh = 0.8; /* Refresh if fraction of top-hit-length drops to this */ double tophits2Mult = 1.0; /* Second-level top heuristic -- only with -fastest */ int tophits2Safety = 3; /* Safety factor for second level of top-hits heuristic */ double tophits2Refresh = 0.6; /* Refresh 2nd-level top hits if drops down to this fraction of length */ double staleOutLimit = 0.01; /* nActive changes by at most this amount before we recompute an out-distance. (Only applies if using the top-hits heuristic) */ double fResetOutProfile = 0.02; /* Recompute out profile from scratch if nActive has changed by more than this proportion, and */ int nResetOutProfile = 200; /* nActive has also changed more than this amount */ int nCodes=20; /* 20 if protein, 4 if nucleotide */ bool useMatrix=true; /* If false, use %different as the uncorrected distance */ bool logdist = true; /* If true, do a log-correction (scoredist-like or Jukes-Cantor) but only during NNIs and support values, not during neighbor-joining */ double pseudoWeight = 0.0; /* The weight of pseudocounts to avoid artificial long branches when nearby sequences in the tree have little or no overlap (off by default). The prior distance is based on all overlapping positions among the quartet or triplet under consideration. The log correction takes place after the pseudocount is used. */ double constraintWeight = 100.0;/* Cost of violation of a topological constraint in evolutionary distance or likelihood */ double MEMinDelta = 1.0e-4; /* Changes of less than this in tree-length are discounted for purposes of identifying fixed subtrees */ bool fastNNI = true; bool gammaLogLk = false; /* compute gamma likelihood without reoptimizing branch lengths? */ /* Maximum likelihood options and constants */ /* These are used to rescale likelihood values and avoid taking a logarithm at each position */ const double LkUnderflow = 1.0e-4; const double LkUnderflowInv = 1.0e4; const double LogLkUnderflow = 9.21034037197618; /* -log(LkUnderflowInv) */ const double Log2 = 0.693147180559945; /* These are used to limit the optimization of branch lengths. Also very short branch lengths can create numerical problems. In version 2.1.7, the minimum branch lengths (MLMinBranchLength and MLMinRelBranchLength) were increased to prevent numerical problems in rare cases. In version 2.1.8, to provide useful branch lengths for genome-wide alignments, the minimum branch lengths were dramatically decreased if USE_DOUBLE is defined. */ #ifndef USE_DOUBLE const double MLMinBranchLengthTolerance = 1.0e-4; /* absolute tolerance for optimizing branch lengths */ const double MLFTolBranchLength = 0.001; /* fractional tolerance for optimizing branch lengths */ const double MLMinBranchLength = 5.0e-4; /* minimum value for branch length */ const double MLMinRelBranchLength = 2.5e-4; /* minimum of rate * length */ const double fPostTotalTolerance = 1.0e-10; /* posterior vector must sum to at least this before rescaling */ #else const double MLMinBranchLengthTolerance = 1.0e-9; const double MLFTolBranchLength = 0.001; const double MLMinBranchLength = 5.0e-9; const double MLMinRelBranchLength = 2.5e-9; const double fPostTotalTolerance = 1.0e-20; #endif int mlAccuracy = 1; /* Rounds of optimization of branch lengths; 1 means do 2nd round only if close */ double closeLogLkLimit = 5.0; /* If partial optimization of an NNI looks like it would decrease the log likelihood by this much or more then do not optimize it further */ double treeLogLkDelta = 0.1; /* Give up if tree log-lk changes by less than this; NNIs that change likelihood by less than this also are considered unimportant by some heuristics */ bool exactML = true; /* Exact or approximate posterior distributions for a.a.s */ double approxMLminf = 0.95; /* Only try to approximate posterior distributions if max. value is at least this high */ double approxMLminratio = 2/3.0;/* Ratio of approximated/true posterior values must be at least this high */ double approxMLnearT = 0.2; /* 2nd component of near-constant posterior distribution uses this time scale */ const int nDefaultRateCats = 20; /* Performance and memory usage */ long profileOps = 0; /* Full profile-based distance operations */ long outprofileOps = 0; /* How many of profileOps are comparisons to outprofile */ long seqOps = 0; /* Faster leaf-based distance operations */ long profileAvgOps = 0; /* Number of profile-average steps */ long nHillBetter = 0; /* Number of hill-climbing steps */ long nCloseUsed = 0; /* Number of "close" neighbors we avoid full search for */ long nClose2Used = 0; /* Number of "close" neighbors we use 2nd-level top hits for */ long nRefreshTopHits = 0; /* Number of full-blown searches (interior nodes) */ long nVisibleUpdate = 0; /* Number of updates of the visible set */ long nNNI = 0; /* Number of NNI changes performed */ long nSPR = 0; /* Number of SPR changes performed */ long nML_NNI = 0; /* Number of max-lik. NNI changes performed */ long nSuboptimalSplits = 0; /* # of splits that are rejected given final tree (during bootstrap) */ long nSuboptimalConstrained = 0; /* Bad splits that are due to constraints */ long nConstraintViolations = 0; /* Number of constraint violations */ long nProfileFreqAlloc = 0; long nProfileFreqAvoid = 0; long szAllAlloc = 0; long mymallocUsed = 0; /* useful allocations by mymalloc */ long maxmallocHeap = 0; /* Maximum of mi.arena+mi.hblkhd from mallinfo (actual mem usage) */ long nLkCompute = 0; /* # of likelihood computations for pairs of probability vectors */ long nPosteriorCompute = 0; /* # of computations of posterior probabilities */ long nAAPosteriorExact = 0; /* # of times compute exact AA posterior */ long nAAPosteriorRough = 0; /* # of times use rough approximation */ long nStarTests = 0; /* # of times we use star test to avoid testing an NNI */ /* Protein character set */ unsigned char *codesStringAA = (unsigned char*) "ARNDCQEGHILKMFPSTWYV"; unsigned char *codesStringNT = (unsigned char*) "ACGT"; unsigned char *codesString = NULL; distance_matrix_t *ReadDistanceMatrix(char *prefix); void SetupDistanceMatrix(/*IN/OUT*/distance_matrix_t *); /* set eigentot, codeFreq, gapFreq */ void ReadMatrix(char *filename, /*OUT*/numeric_t codes[MAXCODES][MAXCODES], bool check_codes); void ReadVector(char *filename, /*OUT*/numeric_t codes[MAXCODES]); alignment_t *ReadAlignment(/*READ*/FILE *fp, bool bQuote); /* Returns a list of strings (exits on failure) */ alignment_t *FreeAlignment(alignment_t *); /* returns NULL */ void FreeAlignmentSeqs(/*IN/OUT*/alignment_t *); /* Takes as input the transpose of the matrix V, with i -> j This routine takes care of setting the diagonals */ transition_matrix_t *CreateTransitionMatrix(/*IN*/double matrix[MAXCODES][MAXCODES], /*IN*/double stat[MAXCODES]); transition_matrix_t *CreateGTR(double *gtrrates/*ac,ag,at,cg,ct,gt*/, double *gtrfreq/*ACGT*/); /* For converting profiles from 1 rotation to another, or converts NULL to NULL */ distance_matrix_t *TransMatToDistanceMat(transition_matrix_t *transmat); /* Allocates memory, initializes leaf profiles */ NJ_t *InitNJ(char **sequences, int nSeqs, int nPos, /*IN OPTIONAL*/char **constraintSeqs, int nConstraints, /*IN OPTIONAL*/distance_matrix_t *, /*IN OPTIONAL*/transition_matrix_t *); NJ_t *FreeNJ(NJ_t *NJ); /* returns NULL */ void FastNJ(/*IN/OUT*/NJ_t *NJ); /* Does the joins */ void ReliabilityNJ(/*IN/OUT*/NJ_t *NJ, int nBootstrap); /* Estimates the reliability of the joins */ /* nni_stats_t is meaningless for leaves and root, so all of those entries will just be high (for age) or 0 (for delta) */ typedef struct { int age; /* number of rounds since this node was modified by an NNI */ int subtreeAge; /* number of rounds since self or descendent had a significant improvement */ double delta; /* improvement in score for this node (or 0 if no change) */ double support; /* improvement of score for self over better of alternatives */ } nni_stats_t; /* One round of nearest-neighbor interchanges according to the minimum-evolution or approximate maximum-likelihood criterion. If doing maximum likelihood then this modifies the branch lengths. age is the # of rounds since a node was NNId Returns the # of topological changes performed */ int NNI(/*IN/OUT*/NJ_t *NJ, int iRound, int nRounds, bool useML, /*IN/OUT*/nni_stats_t *stats, /*OUT*/double *maxDeltaCriterion); nni_stats_t *InitNNIStats(NJ_t *NJ); nni_stats_t *FreeNNIStats(nni_stats_t *, NJ_t *NJ); /* returns NULL */ /* One round of subtree-prune-regraft moves (minimum evolution) */ void SPR(/*IN/OUT*/NJ_t *NJ, int maxSPRLength, int iRound, int nRounds); /* Recomputes all branch lengths by minimum evolution criterion*/ void UpdateBranchLengths(/*IN/OUT*/NJ_t *NJ); /* Recomputes all branch lengths and, optionally, internal profiles */ double TreeLength(/*IN/OUT*/NJ_t *NJ, bool recomputeProfiles); typedef struct { int nBadSplits; int nConstraintViolations; int nBadBoth; int nSplits; /* How much length would be reduce or likelihood would be increased by the best NNI we find (the worst "miss") */ double dWorstDeltaUnconstrained; double dWorstDeltaConstrained; } SplitCount_t; void TestSplitsMinEvo(NJ_t *NJ, /*OUT*/SplitCount_t *splitcount); /* Sets SH-like support values if nBootstrap>0 */ void TestSplitsML(/*IN/OUT*/NJ_t *NJ, /*OUT*/SplitCount_t *splitcount, int nBootstrap); /* Pick columns for resampling, stored as returned_vector[iBoot*nPos + j] */ int *ResampleColumns(int nPos, int nBootstrap); /* Use out-profile and NJ->totdiam to recompute out-distance for node iNode Only does this computation if the out-distance is "stale" (nOutDistActive[iNode] != nActive) Note "IN/UPDATE" for NJ always means that we may update out-distances but otherwise make no changes. */ void SetOutDistance(/*IN/UPDATE*/NJ_t *NJ, int iNode, int nActive); /* Always sets join->criterion; may update NJ->outDistance and NJ->nOutDistActive, assumes join's weight and distance are already set, and that the constraint penalty (if any) is included in the distance */ void SetCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join); /* Computes weight and distance (which includes the constraint penalty) and then sets the criterion (maybe update out-distances) */ void SetDistCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join); /* If join->i or join->j are inactive nodes, replaces them with their active ancestors. After doing this, if i == j, or either is -1, sets weight to 0 and dist and criterion to 1e20 and returns false (not a valid join) Otherwise, if i or j changed, recomputes the distance and criterion. Note that if i and j are unchanged then the criterion could be stale If bUpdateDist is false, and i or j change, then it just sets dist to a negative number */ bool UpdateBestHit(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join, bool bUpdateDist); /* This recomputes the criterion, or returns false if the visible node is no longer active. */ bool GetVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits, int iNode, /*OUT*/besthit_t *visible); int ActiveAncestor(/*IN*/NJ_t *NJ, int node); /* Compute the constraint penalty for a join. This is added to the "distance" by SetCriterion */ int JoinConstraintPenalty(/*IN*/NJ_t *NJ, int node1, int node2); int JoinConstraintPenaltyPiece(NJ_t *NJ, int node1, int node2, int iConstraint); /* Helper function for computing the number of constraints violated by a split, represented as counts of on and off on each side */ int SplitConstraintPenalty(int nOn1, int nOff1, int nOn2, int nOff2); /* Reports the (min. evo.) support for the (1,2) vs. (3,4) split col[iBoot*nPos+j] is column j for bootstrap iBoot */ double SplitSupport(profile_t *p1, profile_t *p2, profile_t *p3, profile_t *p4, /*OPTIONAL*/distance_matrix_t *dmat, int nPos, int nBootstrap, int *col); /* Returns SH-like support given resampling spec. (in col) and site likelihods for the three quartets */ double SHSupport(int nPos, int nBoostrap, int *col, double loglk[3], double *site_likelihoods[3]); profile_t *SeqToProfile(/*IN/OUT*/NJ_t *NJ, char *seq, int nPos, /*OPTIONAL*/char *constraintSeqs, int nConstraints, int iNode, unsigned long counts[256]); /* ProfileDist and SeqDist only set the dist and weight fields If using an outprofile, use the second argument of ProfileDist for better performance. These produce uncorrected distances. */ void ProfileDist(profile_t *profile1, profile_t *profile2, int nPos, /*OPTIONAL*/distance_matrix_t *distance_matrix, /*OUT*/besthit_t *hit); void SeqDist(unsigned char *codes1, unsigned char *codes2, int nPos, /*OPTIONAL*/distance_matrix_t *distance_matrix, /*OUT*/besthit_t *hit); /* Computes all pairs of profile distances, applies pseudocounts if pseudoWeight > 0, and applies log-correction if logdist is true. The lower index is compared to the higher index, e.g. for profiles A,B,C,D the comparison will be as in quartet_pair_t */ typedef enum {qAB,qAC,qAD,qBC,qBD,qCD} quartet_pair_t; void CorrectedPairDistances(profile_t **profiles, int nProfiles, /*OPTIONAL*/distance_matrix_t *distance_matrix, int nPos, /*OUT*/double *distances); /* output is indexed by nni_t To ensure good behavior while evaluating a subtree-prune-regraft move as a series of nearest-neighbor interchanges, this uses a distance-ish model of constraints, as given by PairConstraintDistance(), rather than counting the number of violated splits (which is what FastTree does during neighbor-joining). Thus, penalty values may well be >0 even if no constraints are violated, but the relative scores for the three NNIs will be correct. */ void QuartetConstraintPenalties(profile_t *profiles[4], int nConstraints, /*OUT*/double d[3]); double PairConstraintDistance(int nOn1, int nOff1, int nOn2, int nOff2); /* the split is consistent with the constraint if any of the profiles have no data or if three of the profiles have the same uniform value (all on or all off) or if AB|CD = 00|11 or 11|00 (all uniform) */ bool SplitViolatesConstraint(profile_t *profiles[4], int iConstraint); /* If false, no values were set because this constraint was not relevant. output is for the 3 splits */ bool QuartetConstraintPenaltiesPiece(profile_t *profiles[4], int iConstraint, /*OUT*/double penalty[3]); /* Apply Jukes-Cantor or scoredist-like log(1-d) transform to correct the distance for multiple substitutions. */ double LogCorrect(double distance); /* AverageProfile is used to do a weighted combination of nodes when doing a join. If weight is negative, then the value is ignored and the profiles are averaged. The weight is *not* adjusted for the gap content of the nodes. Also, the weight does not affect the representation of the constraints */ profile_t *AverageProfile(profile_t *profile1, profile_t *profile2, int nPos, int nConstraints, distance_matrix_t *distance_matrix, double weight1); /* PosteriorProfile() is like AverageProfile() but it computes posterior probabilities rather than an average */ profile_t *PosteriorProfile(profile_t *profile1, profile_t *profile2, double len1, double len2, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, int nPos, int nConstraints); /* Set a node's profile from its children. Deletes the previous profile if it exists Use -1.0 for a balanced join Fails unless the node has two children (e.g., no leaves or root) */ void SetProfile(/*IN/OUT*/NJ_t *NJ, int node, double weight1); /* OutProfile does an unweighted combination of nodes to create the out-profile. It always sets code to NOCODE so that UpdateOutProfile can work. */ profile_t *OutProfile(profile_t **profiles, int nProfiles, int nPos, int nConstraints, distance_matrix_t *distance_matrix); void UpdateOutProfile(/*UPDATE*/profile_t *out, profile_t *old1, profile_t *old2, profile_t *new, int nActiveOld, int nPos, int nConstraints, distance_matrix_t *distance_matrix); profile_t *NewProfile(int nPos, int nConstraints); /* returned has no vectors */ profile_t *FreeProfile(profile_t *profile, int nPos, int nConstraints); /* returns NULL */ void AllocRateCategories(/*IN/OUT*/rates_t *rates, int nRateCategories, int nPos); /* f1 can be NULL if code1 != NOCODE, and similarly for f2 Or, if (say) weight1 was 0, then can have code1==NOCODE *and* f1==NULL In that case, returns an arbitrary large number. */ double ProfileDistPiece(unsigned int code1, unsigned int code2, numeric_t *f1, numeric_t *f2, /*OPTIONAL*/distance_matrix_t *dmat, /*OPTIONAL*/numeric_t *codeDist2); /* Adds (or subtracts, if weight is negative) fIn/codeIn from fOut fOut is assumed to exist (as from an outprofile) do not call unless weight of input profile > 0 */ void AddToFreq(/*IN/OUT*/numeric_t *fOut, double weight, unsigned int codeIn, /*OPTIONAL*/numeric_t *fIn, /*OPTIONAL*/distance_matrix_t *dmat); /* Divide the vector (of length nCodes) by a constant so that the total (unrotated) frequency is 1.0 */ void NormalizeFreq(/*IN/OUT*/numeric_t *freq, distance_matrix_t *distance_matrix); /* Allocate, if necessary, and recompute the codeDist*/ void SetCodeDist(/*IN/OUT*/profile_t *profile, int nPos, distance_matrix_t *dmat); /* The allhits list contains the distances of the node to all other active nodes This is useful for the "reset" improvement to the visible set Note that the following routines do not handle the tophits heuristic and assume that out-distances are up to date. */ void SetBestHit(int node, NJ_t *NJ, int nActive, /*OUT*/besthit_t *bestjoin, /*OUT OPTIONAL*/besthit_t *allhits); void ExhaustiveNJSearch(NJ_t *NJ, int nActive, /*OUT*/besthit_t *bestjoin); /* Searches the visible set */ void FastNJSearch(NJ_t *NJ, int nActive, /*UPDATE*/besthit_t *visible, /*OUT*/besthit_t *bestjoin); /* Subroutines for handling the tophits heuristic */ top_hits_t *InitTopHits(NJ_t *NJ, int m); top_hits_t *FreeTopHits(top_hits_t *tophits); /* returns NULL */ /* Before we do any joins -- sets tophits and visible NJ may be modified by setting out-distances */ void SetAllLeafTopHits(/*IN/UPDATE*/NJ_t *NJ, /*IN/OUT*/top_hits_t *tophits); /* Find the best join to do. */ void TopHitNJSearch(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits, /*OUT*/besthit_t *bestjoin); /* Returns the best hit within top hits NJ may be modified because it updates out-distances if they are too stale Does *not* update visible set */ void GetBestFromTopHits(int iNode, /*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN*/top_hits_t *tophits, /*OUT*/besthit_t *bestjoin); /* visible set is modifiable so that we can reset it more globally when we do a "refresh", but we also set the visible set for newnode and do any "reset" updates too. And, we update many outdistances. */ void TopHitJoin(int newnode, /*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits); /* Sort the input besthits by criterion and save the best nOut hits as a new array in top_hits_lists Does not update criterion or out-distances Ignores (silently removes) hit to self Saved list may be shorter than requested if there are insufficient entries */ void SortSaveBestHits(int iNode, /*IN/SORT*/besthit_t *besthits, int nIn, int nOut, /*IN/OUT*/top_hits_t *tophits); /* Given candidate hits from one node, "transfer" them to another node: Stores them in a new place in the same order searches up to active nodes if hits involve non-active nodes If update flag is set, it also recomputes distance and criterion (and ensures that out-distances are updated); otherwise it sets dist to -1e20 and criterion to 1e20 */ void TransferBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive, int iNode, /*IN*/besthit_t *oldhits, int nOldHits, /*OUT*/besthit_t *newhits, bool updateDistance); /* Create best hit objects from 1 or more hits. Do not update out-distances or set criteria */ void HitsToBestHits(/*IN*/hit_t *hits, int nHits, int iNode, /*OUT*/besthit_t *newhits); besthit_t HitToBestHit(int i, hit_t hit); /* Given a set of besthit entries, look for improvements to the visible set of the j entries. Updates out-distances as it goes. Also replaces stale nodes with this node, because a join is usually how this happens (i.e. it does not need to walk up to ancestors). Note this calls UpdateTopVisible() on any change */ void UpdateVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN*/besthit_t *tophitsNode, int nTopHits, /*IN/OUT*/top_hits_t *tophits); /* Update the top-visible list to perhaps include this hit (O(sqrt(N)) time) */ void UpdateTopVisible(/*IN*/NJ_t * NJ, int nActive, int iNode, /*IN*/hit_t *hit, /*IN/OUT*/top_hits_t *tophits); /* Recompute the top-visible subset of the visible set */ void ResetTopVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits); /* Make a shorter list with only unique entries. Replaces any "dead" hits to nodes that have parents with their active ancestors and ignores any that become dead. Updates all criteria. Combined gets sorted by i & j The returned list is allocated to nCombined even though only *nUniqueOut entries are filled */ besthit_t *UniqueBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/SORT*/besthit_t *combined, int nCombined, /*OUT*/int *nUniqueOut); nni_t ChooseNNI(profile_t *profiles[4], /*OPTIONAL*/distance_matrix_t *dmat, int nPos, int nConstraints, /*OUT*/double criteria[3]); /* The three internal branch lengths or log likelihoods*/ /* length[] is ordered as described by quartet_length_t, but after we do the swap of B with C (to give AC|BD) or B with D (to get AD|BC), if that is the returned choice bFast means do not consider NNIs if AB|CD is noticeably better than the star topology (as implemented by MLQuartetOptimize). If there are constraints, then the constraint penalty is included in criteria[] */ nni_t MLQuartetNNI(profile_t *profiles[4], /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, int nPos, int nConstraints, /*OUT*/double criteria[3], /* The three potential quartet log-likelihoods */ /*IN/OUT*/numeric_t length[5], bool bFast); void OptimizeAllBranchLengths(/*IN/OUT*/NJ_t *NJ); double TreeLogLk(/*IN*/NJ_t *NJ, /*OPTIONAL OUT*/double *site_loglk); double MLQuartetLogLk(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN*/double branch_lengths[5], /*OPTIONAL OUT*/double *site_likelihoods); /* Given a topology and branch lengths, estimate rates & recompute profiles */ void SetMLRates(/*IN/OUT*/NJ_t *NJ, int nRateCategories); /* Returns a set of nRateCategories potential rates; the caller must free it */ numeric_t *MLSiteRates(int nRateCategories); /* returns site_loglk so that site_loglk[nPos*iRate + j] is the log likelihood of site j with rate iRate The caller must free it. */ double *MLSiteLikelihoodsByRate(/*IN*/NJ_t *NJ, /*IN*/numeric_t *rates, int nRateCategories); typedef struct { double mult; /* multiplier for the rates / divisor for the tree-length */ double alpha; int nPos; int nRateCats; numeric_t *rates; double *site_loglk; } siteratelk_t; double GammaLogLk(/*IN*/siteratelk_t *s, /*OPTIONAL OUT*/double *gamma_loglk_sites); /* Input site_loglk must be for each rate. Note that FastTree does not reoptimize the branch lengths under the Gamma model -- it optimizes the overall scale. Reports the gamma log likelihhod (and logs site likelihoods if fpLog is set), and reports the rescaling value. */ double RescaleGammaLogLk(int nPos, int nRateCats, /*IN*/numeric_t *rates, /*IN*/double *site_loglk, /*OPTIONAL*/FILE *fpLog); /* P(value<=x) for the gamma distribution with shape parameter alpha and scale 1/alpha */ double PGamma(double x, double alpha); /* Given a topology and branch lengths, optimize GTR rates and quickly reoptimize branch lengths If gtrfreq is NULL, then empirical frequencies are used */ void SetMLGtr(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL IN*/double *gtrfreq, /*OPTIONAL WRITE*/FILE *fpLog); /* P(A & B | len) = P(B | A, len) * P(A) If site_likelihoods is present, multiplies those values by the site likelihood at each point (Note it does not handle underflow) */ double PairLogLk(/*IN*/profile_t *p1, /*IN*/profile_t *p2, double length, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*OPTIONAL IN/OUT*/double *site_likelihoods); /* Branch lengths for 4-taxon tree ((A,B),C,D); I means internal */ typedef enum {LEN_A,LEN_B,LEN_C,LEN_D,LEN_I} quartet_length_t; typedef struct { int nPos; transition_matrix_t *transmat; rates_t *rates; int nEval; /* number of likelihood evaluations */ /* The pair to optimize */ profile_t *pair1; profile_t *pair2; } quartet_opt_t; double PairNegLogLk(double x, void *data); /* data must be a quartet_opt_t */ typedef struct { NJ_t *NJ; double freq[4]; double rates[6]; int iRate; /* which rate to set x from */ FILE *fpLog; /* OPTIONAL WRITE */ } gtr_opt_t; /* Returns -log_likelihood for the tree with the given rates data must be a gtr_opt_t and x is used to set rate iRate Does not recompute profiles -- assumes that the caller will */ double GTRNegLogLk(double x, void *data); /* Returns the resulting log likelihood. Optionally returns whether other topologies should be abandoned, based on the difference between AB|CD and the "star topology" (AB|CD with a branch length of MLMinBranchLength) exceeding closeLogLkLimit. If bStarTest is passed in, it only optimized the internal branch if the star test is true. Otherwise, it optimized all 5 branch lengths in turn. */ double MLQuartetOptimize(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN/OUT*/double branch_lengths[5], /*OPTIONAL OUT*/bool *pStarTest, /*OPTIONAL OUT*/double *site_likelihoods); /* Returns the resulting log likelihood */ double MLPairOptimize(profile_t *pA, profile_t *pB, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN/OUT*/double *branch_length); /* Returns the number of steps considered, with the actual steps in steps[] Modifies the tree by this chain of NNIs */ int FindSPRSteps(/*IN/OUT*/NJ_t *NJ, int node, int parent, /* sibling or parent of node to NNI to start the chain */ /*IN/OUT*/profile_t **upProfiles, /*OUT*/spr_step_t *steps, int maxSteps, bool bFirstAC); /* Undo a single NNI */ void UnwindSPRStep(/*IN/OUT*/NJ_t *NJ, /*IN*/spr_step_t *step, /*IN/OUT*/profile_t **upProfiles); /* Update the profile of node and its ancestor, and delete nearby out-profiles */ void UpdateForNNI(/*IN/OUT*/NJ_t *NJ, int node, /*IN/OUT*/profile_t **upProfiles, bool useML); /* Sets NJ->parent[newchild] and replaces oldchild with newchild in the list of children of parent */ void ReplaceChild(/*IN/OUT*/NJ_t *NJ, int parent, int oldchild, int newchild); int CompareHitsByCriterion(const void *c1, const void *c2); int CompareHitsByIJ(const void *c1, const void *c2); int NGaps(NJ_t *NJ, int node); /* only handles leaf sequences */ /* node is the parent of AB, sibling of C node cannot be root or a leaf If node is the child of root, then D is the other sibling of node, and the 4th profile is D's profile. Otherwise, D is the parent of node, and we use its upprofile Call this with profiles=NULL to get the nodes, without fetching or computing profiles */ void SetupABCD(NJ_t *NJ, int node, /* the 4 profiles for ABCD; the last one is an upprofile */ /*OPTIONAL OUT*/profile_t *profiles[4], /*OPTIONAL IN/OUT*/profile_t **upProfiles, /*OUT*/int nodeABCD[4], bool useML); int Sibling(NJ_t *NJ, int node); /* At root, no unique sibling so returns -1 */ void RootSiblings(NJ_t *NJ, int node, /*OUT*/int sibs[2]); /* JC probability of nucleotide not changing, for each rate category */ double *PSameVector(double length, rates_t *rates); /* JC probability of nucleotide not changing, for each rate category */ double *PDiffVector(double *pSame, rates_t *rates); /* expeigen[iRate*nCodes + j] = exp(length * rate iRate * eigenvalue j) */ numeric_t *ExpEigenRates(double length, transition_matrix_t *transmat, rates_t *rates); /* Print a progress report if more than 0.1 second has gone by since the progress report */ /* Format should include 0-4 %d references and no newlines */ void ProgressReport(char *format, int iArg1, int iArg2, int iArg3, int iArg4); void LogTree(char *format, int round, /*OPTIONAL WRITE*/FILE *fp, NJ_t *NJ, char **names, uniquify_t *unique, bool bQuote); void LogMLRates(/*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ); void *mymalloc(size_t sz); /* Prints "Out of memory" and exits on failure */ void *myfree(void *, size_t sz); /* Always returns NULL */ /* One-dimensional minimization using brent's function, with a fractional and an absolute tolerance */ double onedimenmin(double xmin, double xguess, double xmax, double (*f)(double,void*), void *data, double ftol, double atol, /*OUT*/double *fx, /*OUT*/double *f2x); double brent(double ax, double bx, double cx, double (*f)(double, void *), void *data, double ftol, double atol, double *foptx, double *f2optx, double fax, double fbx, double fcx); /* Vector operations, either using SSE3 or not Code assumes that vectors are a multiple of 4 in size */ void vector_multiply(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n, /*OUT*/numeric_t *fOut); numeric_t vector_multiply_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n); void vector_add_mult(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t *add, numeric_t weight, int n); /* multiply the transpose of a matrix by a vector */ void matrixt_by_vector4(/*IN*/numeric_t mat[4][MAXCODES], /*IN*/numeric_t vec[4], /*OUT*/numeric_t out[4]); /* sum(f1*fBy)*sum(f2*fBy) */ numeric_t vector_dot_product_rot(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* fBy, int n); /* sum(f1*f2*f3) */ numeric_t vector_multiply3_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* f3, int n); numeric_t vector_sum(/*IN*/numeric_t *f1, int n); void vector_multiply_by(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t fBy, int n); double clockDiff(/*IN*/struct timeval *clock_start); int timeval_subtract (/*OUT*/struct timeval *result, /*IN*/struct timeval *x, /*IN*/struct timeval *y); char *OpenMPString(void); void ran_start(long seed); double knuth_rand(); /* Random number between 0 and 1 */ void tred2 (double *a, const int n, const int np, double *d, double *e); double pythag(double a, double b); void tqli(double *d, double *e, int n, int np, double *z); /* Like mymalloc; duplicates the input (returns NULL if given NULL) */ void *mymemdup(void *data, size_t sz); void *myrealloc(void *data, size_t szOld, size_t szNew, bool bCopy); double pnorm(double z); /* Probability(value <=z) */ /* Hashtable functions */ typedef struct { char *string; int nCount; /* number of times this entry was seen */ int first; /* index of first entry with this value */ } hashbucket_t; typedef struct { int nBuckets; /* hashvalue -> bucket. Or look in bucket + 1, +2, etc., till you hit a NULL string */ hashbucket_t *buckets; } hashstrings_t; typedef int hashiterator_t; hashstrings_t *MakeHashtable(char **strings, int nStrings); hashstrings_t *FreeHashtable(hashstrings_t* hash); /*returns NULL*/ hashiterator_t FindMatch(hashstrings_t *hash, char *string); /* Return NULL if we have run out of values */ char *GetHashString(hashstrings_t *hash, hashiterator_t hi); int HashCount(hashstrings_t *hash, hashiterator_t hi); int HashFirst(hashstrings_t *hash, hashiterator_t hi); void PrintNJ(/*WRITE*/FILE *, NJ_t *NJ, char **names, uniquify_t *unique, bool bShowSupport, bool bQuoteNames); /* Print topology using node indices as node names */ void PrintNJInternal(/*WRITE*/FILE *, NJ_t *NJ, bool useLen); uniquify_t *UniquifyAln(/*IN*/alignment_t *aln); uniquify_t *FreeUniquify(uniquify_t *); /* returns NULL */ /* Convert a constraint alignment to a list of sequences. The returned array is indexed by iUnique and points to values in the input alignment */ char **AlnToConstraints(alignment_t *constraints, uniquify_t *unique, hashstrings_t *hashnames); /* ReadTree ignores non-unique leaves after the first instance. At the end, it prunes the tree to ignore empty children and it unroots the tree if necessary. */ void ReadTree(/*IN/OUT*/NJ_t *NJ, /*IN*/uniquify_t *unique, /*IN*/hashstrings_t *hashnames, /*READ*/FILE *fpInTree); char *ReadTreeToken(/*READ*/FILE *fp); /* returns a static array, or NULL on EOF */ void ReadTreeAddChild(int parent, int child, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children); /* Do not add the leaf if we already set this unique-set to another parent */ void ReadTreeMaybeAddLeaf(int parent, char *name, hashstrings_t *hashnames, uniquify_t *unique, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children); void ReadTreeRemove(/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children, int node); /* Routines to support tree traversal and prevent visiting a node >1 time (esp. if topology changes). */ typedef bool *traversal_t; traversal_t InitTraversal(NJ_t*); void SkipTraversalInto(int node, /*IN/OUT*/traversal_t traversal); traversal_t FreeTraversal(traversal_t, NJ_t*); /*returns NULL*/ /* returns new node, or -1 if nothing left to do. Use root for the first call. Will return every node and then root. Uses postorder tree traversal (depth-first search going down to leaves first) Keeps track of which nodes are visited, so even after an NNI that swaps a visited child with an unvisited uncle, the next call will visit the was-uncle-now-child. (However, after SPR moves, there is no such guarantee.) If pUp is not NULL, then, if going "back up" through a previously visited node (presumably due to an NNI), then it will return the node another time, with *pUp = true. */ int TraversePostorder(int lastnode, NJ_t *NJ, /*IN/OUT*/traversal_t, /*OUT OPTIONAL*/bool *pUp); /* Routines to support storing up-profiles during tree traversal Eventually these should be smart enough to do weighted joins and to minimize memory usage */ profile_t **UpProfiles(NJ_t *NJ); profile_t *GetUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node, bool useML); profile_t *DeleteUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node); /* returns NULL */ profile_t **FreeUpProfiles(profile_t **upProfiles, NJ_t *NJ); /* returns NULL */ /* Recomputes the profile for a node, presumably to reflect topology changes If bionj is set, does a weighted join -- which requires using upProfiles If useML is set, computes the posterior probability instead of averaging */ void RecomputeProfile(/*IN/OUT*/NJ_t *NJ, /*IN/OUT*/profile_t **upProfiles, int node, bool useML); /* Recompute profiles going up from the leaves, using the provided distance matrix and unweighted joins */ void RecomputeProfiles(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL*/distance_matrix_t *dmat); void RecomputeMLProfiles(/*IN/OUT*/NJ_t *NJ); /* If bionj is set, computes the weight to be given to A when computing the profile for the ancestor of A and B. C and D are the other profiles in the quartet If bionj is not set, returns -1 (which means unweighted in AverageProfile). (A and B are the first two profiles in the array) */ double QuartetWeight(profile_t *profiles[4], distance_matrix_t *dmat, int nPos); /* Returns a list of nodes, starting with node and ending with root */ int *PathToRoot(NJ_t *NJ, int node, /*OUT*/int *depth); int *FreePath(int *path, NJ_t *NJ); /* returns NULL */ /* The default amino acid distance matrix, derived from the BLOSUM45 similarity matrix */ distance_matrix_t matrixBLOSUM45; /* The default amino acid transition matrix (Jones Taylor Thorton 1992) */ double matrixJTT92[MAXCODES][MAXCODES]; double statJTT92[MAXCODES]; /* The Le-Gascuel 2008 amino acid transition matrix */ double matrixLG08[MAXCODES][MAXCODES]; double statLG08[MAXCODES]; /* The WAG amino acid transition matrix (Whelan-And-Goldman 2001) */ double matrixWAG01[MAXCODES][MAXCODES]; double statWAG01[MAXCODES]; int main(int argc, char **argv) { int nAlign = 1; /* number of alignments to read */ int iArg; char *matrixPrefix = NULL; distance_matrix_t *distance_matrix = NULL; bool make_matrix = false; char *constraintsFile = NULL; char *intreeFile = NULL; bool intree1 = false; /* the same starting tree each round */ int nni = -1; /* number of rounds of NNI, defaults to 4*log2(n) */ int spr = 2; /* number of rounds of SPR */ int maxSPRLength = 10; /* maximum distance to move a node */ int MLnni = -1; /* number of rounds of ML NNI, defaults to 2*log2(n) */ bool MLlen = false; /* optimize branch lengths; no topology changes */ int nBootstrap = 1000; /* If set, number of replicates of local bootstrap to do */ int nRateCats = nDefaultRateCats; char *logfile = NULL; bool bUseGtr = false; bool bUseLg = false; bool bUseWag = false; bool bUseGtrRates = false; double gtrrates[6] = {1,1,1,1,1,1}; bool bUseGtrFreq = false; double gtrfreq[4] = {0.25,0.25,0.25,0.25}; bool bQuote = false; FILE *fpOut = stdout; if (isatty(STDIN_FILENO) && argc == 1) { fprintf(stderr,"Usage for FastTree version %s %s%s:\n%s", FT_VERSION, SSE_STRING, OpenMPString(), usage); #if (defined _WIN32 || defined WIN32 || defined WIN64 || defined _WIN64) fprintf(stderr, "Windows users: Please remember to run this inside a command shell\n"); fprintf(stderr,"Hit return to continue\n"); fgetc(stdin); #endif exit(0); } for (iArg = 1; iArg < argc; iArg++) { if (strcmp(argv[iArg],"-makematrix") == 0) { make_matrix = true; } else if (strcmp(argv[iArg],"-logdist") == 0) { fprintf(stderr, "Warning: logdist is now on by default and obsolete\n"); } else if (strcmp(argv[iArg],"-rawdist") == 0) { logdist = false; } else if (strcmp(argv[iArg],"-verbose") == 0 && iArg < argc-1) { verbose = atoi(argv[++iArg]); } else if (strcmp(argv[iArg],"-quiet") == 0) { verbose = 0; showProgress = 0; } else if (strcmp(argv[iArg],"-nopr") == 0) { showProgress = 0; } else if (strcmp(argv[iArg],"-slow") == 0) { slow = 1; } else if (strcmp(argv[iArg],"-fastest") == 0) { fastest = 1; tophitsRefresh = 0.5; useTopHits2nd = true; } else if (strcmp(argv[iArg],"-2nd") == 0) { useTopHits2nd = true; } else if (strcmp(argv[iArg],"-no2nd") == 0) { useTopHits2nd = false; } else if (strcmp(argv[iArg],"-slownni") == 0) { fastNNI = false; } else if (strcmp(argv[iArg], "-matrix") == 0 && iArg < argc-1) { iArg++; matrixPrefix = argv[iArg]; } else if (strcmp(argv[iArg], "-nomatrix") == 0) { useMatrix = false; } else if (strcmp(argv[iArg], "-n") == 0 && iArg < argc-1) { iArg++; nAlign = atoi(argv[iArg]); if (nAlign < 1) { fprintf(stderr, "-n argument for #input alignments must be > 0 not %s\n", argv[iArg]); exit(1); } } else if (strcmp(argv[iArg], "-quote") == 0) { bQuote = true; } else if (strcmp(argv[iArg], "-nt") == 0) { nCodes = 4; } else if (strcmp(argv[iArg], "-intree") == 0 && iArg < argc-1) { iArg++; intreeFile = argv[iArg]; } else if (strcmp(argv[iArg], "-intree1") == 0 && iArg < argc-1) { iArg++; intreeFile = argv[iArg]; intree1 = true; } else if (strcmp(argv[iArg], "-nj") == 0) { bionj = 0; } else if (strcmp(argv[iArg], "-bionj") == 0) { bionj = 1; } else if (strcmp(argv[iArg], "-boot") == 0 && iArg < argc-1) { iArg++; nBootstrap = atoi(argv[iArg]); } else if (strcmp(argv[iArg], "-noboot") == 0 || strcmp(argv[iArg], "-nosupport") == 0) { nBootstrap = 0; } else if (strcmp(argv[iArg], "-seed") == 0 && iArg < argc-1) { iArg++; long seed = atol(argv[iArg]); ran_start(seed); } else if (strcmp(argv[iArg],"-top") == 0) { if(tophitsMult < 0.01) tophitsMult = 1.0; } else if (strcmp(argv[iArg],"-notop") == 0) { tophitsMult = 0.0; } else if (strcmp(argv[iArg], "-topm") == 0 && iArg < argc-1) { iArg++; tophitsMult = atof(argv[iArg]); } else if (strcmp(argv[iArg], "-close") == 0 && iArg < argc-1) { iArg++; tophitsClose = atof(argv[iArg]); if (tophitsMult <= 0) { fprintf(stderr, "Cannot use -close unless -top is set above 0\n"); exit(1); } if (tophitsClose <= 0 || tophitsClose >= 1) { fprintf(stderr, "-close argument must be between 0 and 1\n"); exit(1); } } else if (strcmp(argv[iArg], "-refresh") == 0 && iArg < argc-1) { iArg++; tophitsRefresh = atof(argv[iArg]); if (tophitsMult <= 0) { fprintf(stderr, "Cannot use -refresh unless -top is set above 0\n"); exit(1); } if (tophitsRefresh <= 0 || tophitsRefresh >= 1) { fprintf(stderr, "-refresh argument must be between 0 and 1\n"); exit(1); } } else if (strcmp(argv[iArg],"-nni") == 0 && iArg < argc-1) { iArg++; nni = atoi(argv[iArg]); if (nni == 0) spr = 0; } else if (strcmp(argv[iArg],"-spr") == 0 && iArg < argc-1) { iArg++; spr = atoi(argv[iArg]); } else if (strcmp(argv[iArg],"-sprlength") == 0 && iArg < argc-1) { iArg++; maxSPRLength = atoi(argv[iArg]); } else if (strcmp(argv[iArg],"-mlnni") == 0 && iArg < argc-1) { iArg++; MLnni = atoi(argv[iArg]); } else if (strcmp(argv[iArg],"-noml") == 0) { MLnni = 0; } else if (strcmp(argv[iArg],"-mllen") == 0) { MLnni = 0; MLlen = true; } else if (strcmp(argv[iArg],"-nome") == 0) { spr = 0; nni = 0; } else if (strcmp(argv[iArg],"-help") == 0) { fprintf(stderr,"FastTree %s %s%s:\n%s", FT_VERSION, SSE_STRING, OpenMPString(), usage); exit(0); } else if (strcmp(argv[iArg],"-expert") == 0) { fprintf(stderr, "Detailed usage for FastTree %s %s%s:\n%s", FT_VERSION, SSE_STRING, OpenMPString(), expertUsage); exit(0); } else if (strcmp(argv[iArg],"-pseudo") == 0) { if (iArg < argc-1 && isdigit(argv[iArg+1][0])) { iArg++; pseudoWeight = atof(argv[iArg]); if (pseudoWeight < 0.0) { fprintf(stderr,"Illegal argument to -pseudo: %s\n", argv[iArg]); exit(1); } } else { pseudoWeight = 1.0; } } else if (strcmp(argv[iArg],"-constraints") == 0 && iArg < argc-1) { iArg++; constraintsFile = argv[iArg]; } else if (strcmp(argv[iArg],"-constraintWeight") == 0 && iArg < argc-1) { iArg++; constraintWeight = atof(argv[iArg]); if (constraintWeight <= 0.0) { fprintf(stderr, "Illegal argument to -constraintWeight (must be greater than zero): %s\n", argv[iArg]); exit(1); } } else if (strcmp(argv[iArg],"-mlacc") == 0 && iArg < argc-1) { iArg++; mlAccuracy = atoi(argv[iArg]); if (mlAccuracy < 1) { fprintf(stderr, "Illlegal -mlacc argument: %s\n", argv[iArg]); exit(1); } } else if (strcmp(argv[iArg],"-exactml") == 0 || strcmp(argv[iArg],"-mlexact") == 0) { fprintf(stderr,"-exactml is not required -- exact posteriors is the default now\n"); } else if (strcmp(argv[iArg],"-approxml") == 0 || strcmp(argv[iArg],"-mlapprox") == 0) { exactML = false; } else if (strcmp(argv[iArg],"-cat") == 0 && iArg < argc-1) { iArg++; nRateCats = atoi(argv[iArg]); if (nRateCats < 1) { fprintf(stderr, "Illlegal argument to -ncat (must be greater than zero): %s\n", argv[iArg]); exit(1); } } else if (strcmp(argv[iArg],"-nocat") == 0) { nRateCats = 1; } else if (strcmp(argv[iArg], "-lg") == 0) { bUseLg = true; } else if (strcmp(argv[iArg], "-wag") == 0) { bUseWag = true; } else if (strcmp(argv[iArg], "-gtr") == 0) { bUseGtr = true; } else if (strcmp(argv[iArg], "-gtrrates") == 0 && iArg < argc-6) { bUseGtr = true; bUseGtrRates = true; int i; for (i = 0; i < 6; i++) { gtrrates[i] = atof(argv[++iArg]); if (gtrrates[i] < 1e-5) { fprintf(stderr, "Illegal or too small value of GTR rate: %s\n", argv[iArg]); exit(1); } } } else if (strcmp(argv[iArg],"-gtrfreq") == 0 && iArg < argc-4) { bUseGtr = true; bUseGtrFreq = true; int i; double sum = 0; for (i = 0; i < 4; i++) { gtrfreq[i] = atof(argv[++iArg]); sum += gtrfreq[i]; if (gtrfreq[i] < 1e-5) { fprintf(stderr, "Illegal or too small value of GTR frequency: %s\n", argv[iArg]); exit(1); } } if (fabs(1.0-sum) > 0.01) { fprintf(stderr, "-gtrfreq values do not sum to 1\n"); exit(1); } for (i = 0; i < 4; i++) gtrfreq[i] /= sum; } else if (strcmp(argv[iArg],"-log") == 0 && iArg < argc-1) { iArg++; logfile = argv[iArg]; } else if (strcmp(argv[iArg],"-gamma") == 0) { gammaLogLk = true; } else if (strcmp(argv[iArg],"-out") == 0 && iArg < argc-1) { iArg++; fpOut = fopen(argv[iArg],"w"); if(fpOut==NULL) { fprintf(stderr,"Cannot write to %s\n",argv[iArg]); exit(1); } } else if (argv[iArg][0] == '-') { fprintf(stderr, "Unknown or incorrect use of option %s\n%s", argv[iArg], usage); exit(1); } else break; } if(iArg < argc-1) { fprintf(stderr, "%s", usage); exit(1); } codesString = nCodes == 20 ? codesStringAA : codesStringNT; if (nCodes == 4 && matrixPrefix == NULL) useMatrix = false; /* no default nucleotide matrix */ char *fileName = iArg == (argc-1) ? argv[argc-1] : NULL; if (slow && fastest) { fprintf(stderr,"Cannot be both slow and fastest\n"); exit(1); } if (slow && tophitsMult > 0) { tophitsMult = 0.0; } FILE *fpLog = NULL; if (logfile != NULL) { fpLog = fopen(logfile, "w"); if (fpLog == NULL) { fprintf(stderr, "Cannot write to: %s\n", logfile); exit(1); } fprintf(fpLog, "Command:"); int i; for (i=0; i < argc; i++) fprintf(fpLog, " %s", argv[i]); fprintf(fpLog,"\n"); fflush(fpLog); } int i; FILE *fps[2] = {NULL,NULL}; int nFPs = 0; if (verbose) fps[nFPs++] = stderr; if (fpLog != NULL) fps[nFPs++] = fpLog; if (!make_matrix) { /* Report settings */ char tophitString[100] = "no"; char tophitsCloseStr[100] = "default"; if(tophitsClose > 0) sprintf(tophitsCloseStr,"%.2f",tophitsClose); if(tophitsMult>0) sprintf(tophitString,"%.2f*sqrtN close=%s refresh=%.2f", tophitsMult, tophitsCloseStr, tophitsRefresh); char supportString[100] = "none"; if (nBootstrap>0) { if (MLnni != 0 || MLlen) sprintf(supportString, "SH-like %d", nBootstrap); else sprintf(supportString,"Local boot %d",nBootstrap); } char nniString[100] = "(no NNI)"; if (nni > 0) sprintf(nniString, "+NNI (%d rounds)", nni); if (nni == -1) strcpy(nniString, "+NNI"); char sprString[100] = "(no SPR)"; if (spr > 0) sprintf(sprString, "+SPR (%d rounds range %d)", spr, maxSPRLength); char mlnniString[100] = "(no ML-NNI)"; if(MLnni > 0) sprintf(mlnniString, "+ML-NNI (%d rounds)", MLnni); else if (MLnni == -1) sprintf(mlnniString, "+ML-NNI"); else if (MLlen) sprintf(mlnniString, "+ML branch lengths"); if ((MLlen || MLnni != 0) && !exactML) strcat(mlnniString, " approx"); if (MLnni != 0) sprintf(mlnniString+strlen(mlnniString), " opt-each=%d",mlAccuracy); for (i = 0; i < nFPs; i++) { FILE *fp = fps[i]; fprintf(fp,"FastTree Version %s %s%s\nAlignment: %s", FT_VERSION, SSE_STRING, OpenMPString(), fileName != NULL ? fileName : "standard input"); if (nAlign>1) fprintf(fp, " (%d alignments)", nAlign); fprintf(fp,"\n%s distances: %s Joins: %s Support: %s\n", nCodes == 20 ? "Amino acid" : "Nucleotide", matrixPrefix ? matrixPrefix : (useMatrix? "BLOSUM45" : (nCodes==4 && logdist ? "Jukes-Cantor" : "%different")), bionj ? "weighted" : "balanced" , supportString); if (intreeFile == NULL) fprintf(fp, "Search: %s%s %s %s %s\nTopHits: %s\n", slow?"Exhaustive (slow)" : (fastest ? "Fastest" : "Normal"), useTopHits2nd ? "+2nd" : "", nniString, sprString, mlnniString, tophitString); else fprintf(fp, "Start at tree from %s %s %s\n", intreeFile, nniString, sprString); if (MLnni != 0 || MLlen) { fprintf(fp, "ML Model: %s,", (nCodes == 4) ? (bUseGtr ? "Generalized Time-Reversible" : "Jukes-Cantor") : (bUseLg ? "Le-Gascuel 2008" : (bUseWag ? "Whelan-And-Goldman" : "Jones-Taylor-Thorton")) ); if (nRateCats == 1) fprintf(fp, " No rate variation across sites"); else fprintf(fp, " CAT approximation with %d rate categories", nRateCats); fprintf(fp, "\n"); if (nCodes == 4 && bUseGtrRates) fprintf(fp, "GTR rates(ac ag at cg ct gt) %.4f %.4f %.4f %.4f %.4f %.4f\n", gtrrates[0],gtrrates[1],gtrrates[2],gtrrates[3],gtrrates[4],gtrrates[5]); if (nCodes == 4 && bUseGtrFreq) fprintf(fp, "GTR frequencies(A C G T) %.4f %.4f %.4f %.4f\n", gtrfreq[0],gtrfreq[1],gtrfreq[2],gtrfreq[3]); } if (constraintsFile != NULL) fprintf(fp, "Constraints: %s Weight: %.3f\n", constraintsFile, constraintWeight); if (pseudoWeight > 0) fprintf(fp, "Pseudocount weight for comparing sequences with little overlap: %.3lf\n",pseudoWeight); fflush(fp); } } if (matrixPrefix != NULL) { if (!useMatrix) { fprintf(stderr,"Cannot use both -matrix and -nomatrix arguments!"); exit(1); } distance_matrix = ReadDistanceMatrix(matrixPrefix); } else if (useMatrix) { /* use default matrix */ assert(nCodes==20); distance_matrix = &matrixBLOSUM45; SetupDistanceMatrix(distance_matrix); } else { distance_matrix = NULL; } int iAln; FILE *fpIn = fileName != NULL ? fopen(fileName, "r") : stdin; if (fpIn == NULL) { fprintf(stderr, "Cannot read %s\n", fileName); exit(1); } FILE *fpConstraints = NULL; if (constraintsFile != NULL) { fpConstraints = fopen(constraintsFile, "r"); if (fpConstraints == NULL) { fprintf(stderr, "Cannot read %s\n", constraintsFile); exit(1); } } FILE *fpInTree = NULL; if (intreeFile != NULL) { fpInTree = fopen(intreeFile,"r"); if (fpInTree == NULL) { fprintf(stderr, "Cannot read %s\n", intreeFile); exit(1); } } for(iAln = 0; iAln < nAlign; iAln++) { alignment_t *aln = ReadAlignment(fpIn, bQuote); if (aln->nSeq < 1) { fprintf(stderr, "No alignment sequences\n"); exit(1); } if (fpLog) { fprintf(fpLog, "Read %d sequences, %d positions\n", aln->nSeq, aln->nPos); fflush(fpLog); } struct timeval clock_start; gettimeofday(&clock_start,NULL); ProgressReport("Read alignment",0,0,0,0); /* Check that all names in alignment are unique */ hashstrings_t *hashnames = MakeHashtable(aln->names, aln->nSeq); int i; for (i=0; i<aln->nSeq; i++) { hashiterator_t hi = FindMatch(hashnames,aln->names[i]); if (HashCount(hashnames,hi) != 1) { fprintf(stderr,"Non-unique name '%s' in the alignment\n",aln->names[i]); exit(1); } } /* Make a list of unique sequences -- note some lists are bigger than required */ ProgressReport("Hashed the names",0,0,0,0); if (make_matrix) { NJ_t *NJ = InitNJ(aln->seqs, aln->nSeq, aln->nPos, /*constraintSeqs*/NULL, /*nConstraints*/0, distance_matrix, /*transmat*/NULL); printf(" %d\n",aln->nSeq); int i,j; for(i = 0; i < NJ->nSeq; i++) { printf("%s",aln->names[i]); for (j = 0; j < NJ->nSeq; j++) { besthit_t hit; SeqDist(NJ->profiles[i]->codes,NJ->profiles[j]->codes,NJ->nPos,NJ->distance_matrix,/*OUT*/&hit); if (logdist) hit.dist = LogCorrect(hit.dist); /* Make sure -0 prints as 0 */ printf(" %f", hit.dist <= 0.0 ? 0.0 : hit.dist); } printf("\n"); } } else { /* reset counters*/ profileOps = 0; outprofileOps = 0; seqOps = 0; profileAvgOps = 0; nHillBetter = 0; nCloseUsed = 0; nClose2Used = 0; nRefreshTopHits = 0; nVisibleUpdate = 0; nNNI = 0; nML_NNI = 0; nProfileFreqAlloc = 0; nProfileFreqAvoid = 0; szAllAlloc = 0; mymallocUsed = 0; maxmallocHeap = 0; nLkCompute = 0; nPosteriorCompute = 0; nAAPosteriorExact = 0; nAAPosteriorRough = 0; nStarTests = 0; uniquify_t *unique = UniquifyAln(aln); ProgressReport("Identified unique sequences",0,0,0,0); /* read constraints */ alignment_t *constraints = NULL; char **uniqConstraints = NULL; if (constraintsFile != NULL) { constraints = ReadAlignment(fpConstraints, bQuote); if (constraints->nSeq < 4) { fprintf(stderr, "Warning: constraints file with less than 4 sequences ignored:\nalignment #%d in %s\n", iAln+1, constraintsFile); constraints = FreeAlignment(constraints); } else { uniqConstraints = AlnToConstraints(constraints, unique, hashnames); ProgressReport("Read the constraints",0,0,0,0); } } /* end load constraints */ transition_matrix_t *transmat = NULL; if (nCodes == 20) { transmat = bUseLg? CreateTransitionMatrix(matrixLG08,statLG08) : (bUseWag? CreateTransitionMatrix(matrixWAG01,statWAG01) : CreateTransitionMatrix(matrixJTT92,statJTT92)); } else if (nCodes == 4 && bUseGtr && (bUseGtrRates || bUseGtrFreq)) { transmat = CreateGTR(gtrrates,gtrfreq); } NJ_t *NJ = InitNJ(unique->uniqueSeq, unique->nUnique, aln->nPos, uniqConstraints, uniqConstraints != NULL ? constraints->nPos : 0, /* nConstraints */ distance_matrix, transmat); if (verbose>2) fprintf(stderr, "read %s seqs %d (%d unique) positions %d nameLast %s seqLast %s\n", fileName ? fileName : "standard input", aln->nSeq, unique->nUnique, aln->nPos, aln->names[aln->nSeq-1], aln->seqs[aln->nSeq-1]); FreeAlignmentSeqs(/*IN/OUT*/aln); /*no longer needed*/ if (fpInTree != NULL) { if (intree1) fseek(fpInTree, 0L, SEEK_SET); ReadTree(/*IN/OUT*/NJ, /*IN*/unique, /*IN*/hashnames, /*READ*/fpInTree); if (verbose > 2) fprintf(stderr, "Read tree from %s\n", intreeFile); if (verbose > 2) PrintNJ(stderr, NJ, aln->names, unique, /*support*/false, bQuote); } else { FastNJ(NJ); } LogTree("NJ", 0, fpLog, NJ, aln->names, unique, bQuote); /* profile-frequencies for the "up-profiles" in ReliabilityNJ take only diameter(Tree)*L*a space not N*L*a space, because we can free them as we go. And up-profile by their nature tend to be complicated. So save the profile-frequency memory allocation counters now to exclude later results. */ #ifdef TRACK_MEMORY long svProfileFreqAlloc = nProfileFreqAlloc; long svProfileFreqAvoid = nProfileFreqAvoid; #endif int nniToDo = nni == -1 ? (int)(0.5 + 4.0 * log(NJ->nSeq)/log(2)) : nni; int sprRemaining = spr; int MLnniToDo = (MLnni != -1) ? MLnni : (int)(0.5 + 2.0*log(NJ->nSeq)/log(2)); if(verbose>0) { if (fpInTree == NULL) fprintf(stderr, "Initial topology in %.2f seconds\n", clockDiff(&clock_start)); if (spr > 0 || nniToDo > 0 || MLnniToDo > 0) fprintf(stderr,"Refining topology: %d rounds ME-NNIs, %d rounds ME-SPRs, %d rounds ML-NNIs\n", nniToDo, spr, MLnniToDo); } if (nniToDo>0) { int i; bool bConverged = false; nni_stats_t *nni_stats = InitNNIStats(NJ); for (i=0; i < nniToDo; i++) { double maxDelta; if (!bConverged) { int nChange = NNI(/*IN/OUT*/NJ, i, nniToDo, /*use ml*/false, /*IN/OUT*/nni_stats, /*OUT*/&maxDelta); LogTree("ME_NNI%d",i+1, fpLog, NJ, aln->names, unique, bQuote); if (nChange == 0) { bConverged = true; if (verbose>1) fprintf(stderr, "Min_evolution NNIs converged at round %d -- skipping some rounds\n", i+1); if (fpLog) fprintf(fpLog, "Min_evolution NNIs converged at round %d -- skipping some rounds\n", i+1); } } /* Interleave SPRs with NNIs (typically 1/3rd NNI, SPR, 1/3rd NNI, SPR, 1/3rd NNI */ if (sprRemaining > 0 && (nniToDo/(spr+1) > 0 && ((i+1) % (nniToDo/(spr+1))) == 0)) { SPR(/*IN/OUT*/NJ, maxSPRLength, spr-sprRemaining, spr); LogTree("ME_SPR%d",spr-sprRemaining+1, fpLog, NJ, aln->names, unique, bQuote); sprRemaining--; /* Restart the NNIs -- set all ages to 0, etc. */ bConverged = false; nni_stats = FreeNNIStats(nni_stats, NJ); nni_stats = InitNNIStats(NJ); } } nni_stats = FreeNNIStats(nni_stats, NJ); } while(sprRemaining > 0) { /* do any remaining SPR rounds */ SPR(/*IN/OUT*/NJ, maxSPRLength, spr-sprRemaining, spr); LogTree("ME_SPR%d",spr-sprRemaining+1, fpLog, NJ, aln->names, unique, bQuote); sprRemaining--; } /* In minimum-evolution mode, update branch lengths, even if no NNIs or SPRs, so that they are log-corrected, do not include penalties from constraints, and avoid errors due to approximation of out-distances. If doing maximum-likelihood NNIs, then we'll also use these to get estimates of starting distances for quartets, etc. */ UpdateBranchLengths(/*IN/OUT*/NJ); LogTree("ME_Lengths",0, fpLog, NJ, aln->names, unique, bQuote); double total_len = 0; int iNode; for (iNode = 0; iNode < NJ->maxnode; iNode++) total_len += fabs(NJ->branchlength[iNode]); if (verbose>0) { fprintf(stderr, "Total branch-length %.3f after %.2f sec\n", total_len, clockDiff(&clock_start)); fflush(stderr); } if (fpLog) { fprintf(fpLog, "Total branch-length %.3f after %.2f sec\n", total_len, clockDiff(&clock_start)); fflush(stderr); } #ifdef TRACK_MEMORY if (verbose>1) { struct mallinfo mi = mallinfo(); fprintf(stderr, "Memory @ end of ME phase: %.2f MB (%.1f byte/pos) useful %.2f expected %.2f\n", (mi.arena+mi.hblkhd)/1.0e6, (mi.arena+mi.hblkhd)/(double)(NJ->nSeq*(double)NJ->nPos), mi.uordblks/1.0e6, mymallocUsed/1e6); } #endif SplitCount_t splitcount = {0,0,0,0,0.0,0.0}; if (MLnniToDo > 0 || MLlen) { bool warn_len = total_len/NJ->maxnode < 0.001 && MLMinBranchLengthTolerance > 1.0/aln->nPos; bool warn = warn_len || (total_len/NJ->maxnode < 0.001 && aln->nPos >= 10000); if (warn) fprintf(stderr, "\nWARNING! This alignment consists of closely-related and very-long sequences.\n"); if (warn_len) fprintf(stderr, "This version of FastTree may not report reasonable branch lengths!\n" #ifdef USE_DOUBLE "Consider changing MLMinBranchLengthTolerance.\n" #else "Consider recompiling FastTree with -DUSE_DOUBLE.\n" #endif "For more information, visit\n" "http://www.microbesonline.org/fasttree/#BranchLen\n\n"); if (warn) fprintf(stderr, "WARNING! FastTree (or other standard maximum-likelihood tools)\n" "may not be appropriate for aligments of very closely-related sequences\n" "like this one, as FastTree does not account for recombination or gene conversion\n\n"); /* Do maximum-likelihood computations */ /* Convert profiles to use the transition matrix */ distance_matrix_t *tmatAsDist = TransMatToDistanceMat(/*OPTIONAL*/NJ->transmat); RecomputeProfiles(NJ, /*OPTIONAL*/tmatAsDist); tmatAsDist = myfree(tmatAsDist, sizeof(distance_matrix_t)); double lastloglk = -1e20; nni_stats_t *nni_stats = InitNNIStats(NJ); bool resetGtr = nCodes == 4 && bUseGtr && !bUseGtrRates; if (MLlen) { int iRound; int maxRound = (int)(0.5 + log(NJ->nSeq)/log(2)); double dLastLogLk = -1e20; for (iRound = 1; iRound <= maxRound; iRound++) { int node; numeric_t *oldlength = (numeric_t*)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (node = 0; node < NJ->maxnode; node++) oldlength[node] = NJ->branchlength[node]; OptimizeAllBranchLengths(/*IN/OUT*/NJ); LogTree("ML_Lengths",iRound, fpLog, NJ, aln->names, unique, bQuote); double dMaxChange = 0; /* biggest change in branch length */ for (node = 0; node < NJ->maxnode; node++) { double d = fabs(oldlength[node] - NJ->branchlength[node]); if (dMaxChange < d) dMaxChange = d; } oldlength = myfree(oldlength, sizeof(numeric_t)*NJ->maxnodes); double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL); bool bConverged = iRound > 1 && (dMaxChange < 0.001 || loglk < (dLastLogLk+treeLogLkDelta)); if (verbose) fprintf(stderr, "%d rounds ML lengths: LogLk %s= %.3lf Max-change %.4lf%s Time %.2f\n", iRound, exactML || nCodes != 20 ? "" : "~", loglk, dMaxChange, bConverged ? " (converged)" : "", clockDiff(&clock_start)); if (fpLog) fprintf(fpLog, "TreeLogLk\tLength%d\t%.4lf\tMaxChange\t%.4lf\n", iRound, loglk, dMaxChange); if (iRound == 1) { if (resetGtr) SetMLGtr(/*IN/OUT*/NJ, bUseGtrFreq ? gtrfreq : NULL, fpLog); SetMLRates(/*IN/OUT*/NJ, nRateCats); LogMLRates(fpLog, NJ); } if (bConverged) break; } } if (MLnniToDo > 0) { /* This may help us converge faster, and is fast */ OptimizeAllBranchLengths(/*IN/OUT*/NJ); LogTree("ML_Lengths%d",1, fpLog, NJ, aln->names, unique, bQuote); } int iMLnni; double maxDelta; bool bConverged = false; for (iMLnni = 0; iMLnni < MLnniToDo; iMLnni++) { int changes = NNI(/*IN/OUT*/NJ, iMLnni, MLnniToDo, /*use ml*/true, /*IN/OUT*/nni_stats, /*OUT*/&maxDelta); LogTree("ML_NNI%d",iMLnni+1, fpLog, NJ, aln->names, unique, bQuote); double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL); bool bConvergedHere = (iMLnni > 0) && ((loglk < lastloglk + treeLogLkDelta) || maxDelta < treeLogLkDelta); if (verbose) fprintf(stderr, "ML-NNI round %d: LogLk %s= %.3f NNIs %d max delta %.2f Time %.2f%s\n", iMLnni+1, exactML || nCodes != 20 ? "" : "~", loglk, changes, maxDelta, clockDiff(&clock_start), bConverged ? " (final)" : ""); if (fpLog) fprintf(fpLog, "TreeLogLk\tML_NNI%d\t%.4lf\tMaxChange\t%.4lf\n", iMLnni+1, loglk, maxDelta); if (bConverged) break; /* we did our extra round */ if (bConvergedHere) bConverged = true; if (bConverged || iMLnni == MLnniToDo-2) { /* last round uses high-accuracy seettings -- reset NNI stats to tone down heuristics */ nni_stats = FreeNNIStats(nni_stats, NJ); nni_stats = InitNNIStats(NJ); if (verbose) fprintf(stderr, "Turning off heuristics for final round of ML NNIs%s\n", bConvergedHere? " (converged)" : ""); if (fpLog) fprintf(fpLog, "Turning off heuristics for final round of ML NNIs%s\n", bConvergedHere? " (converged)" : ""); } lastloglk = loglk; if (iMLnni == 0 && NJ->rates.nRateCategories == 1) { if (resetGtr) SetMLGtr(/*IN/OUT*/NJ, bUseGtrFreq ? gtrfreq : NULL, fpLog); SetMLRates(/*IN/OUT*/NJ, nRateCats); LogMLRates(fpLog, NJ); } } nni_stats = FreeNNIStats(nni_stats, NJ); /* This does not take long and improves the results */ if (MLnniToDo > 0) { OptimizeAllBranchLengths(/*IN/OUT*/NJ); LogTree("ML_Lengths%d",2, fpLog, NJ, aln->names, unique, bQuote); if (verbose || fpLog) { double loglk = TreeLogLk(NJ, /*site_likelihoods*/NULL); if (verbose) fprintf(stderr, "Optimize all lengths: LogLk %s= %.3f Time %.2f\n", exactML || nCodes != 20 ? "" : "~", loglk, clockDiff(&clock_start)); if (fpLog) { fprintf(fpLog, "TreeLogLk\tML_Lengths%d\t%.4f\n", 2, loglk); fflush(fpLog); } } } /* Count bad splits and compute SH-like supports if desired */ if ((MLnniToDo > 0 && !fastest) || nBootstrap > 0) TestSplitsML(NJ, /*OUT*/&splitcount, nBootstrap); /* Compute gamma-based likelihood? */ if (gammaLogLk && nRateCats > 1) { numeric_t *rates = MLSiteRates(nRateCats); double *site_loglk = MLSiteLikelihoodsByRate(NJ, rates, nRateCats); double scale = RescaleGammaLogLk(NJ->nPos, nRateCats, rates, /*IN*/site_loglk, /*OPTIONAL*/fpLog); rates = myfree(rates, sizeof(numeric_t) * nRateCats); site_loglk = myfree(site_loglk, sizeof(double) * nRateCats * NJ->nPos); for (i = 0; i < NJ->maxnodes; i++) NJ->branchlength[i] *= scale; } } else { /* Minimum evolution supports */ TestSplitsMinEvo(NJ, /*OUT*/&splitcount); if (nBootstrap > 0) ReliabilityNJ(NJ, nBootstrap); } for (i = 0; i < nFPs; i++) { FILE *fp = fps[i]; fprintf(fp, "Total time: %.2f seconds Unique: %d/%d Bad splits: %d/%d", clockDiff(&clock_start), NJ->nSeq, aln->nSeq, splitcount.nBadSplits, splitcount.nSplits); if (splitcount.dWorstDeltaUnconstrained > 0) fprintf(fp, " Worst %sdelta-%s %.3f", uniqConstraints != NULL ? "unconstrained " : "", (MLnniToDo > 0 || MLlen) ? "LogLk" : "Len", splitcount.dWorstDeltaUnconstrained); fprintf(fp,"\n"); if (NJ->nSeq > 3 && NJ->nConstraints > 0) { fprintf(fp, "Violating constraints: %d both bad: %d", splitcount.nConstraintViolations, splitcount.nBadBoth); if (splitcount.dWorstDeltaConstrained > 0) fprintf(fp, " Worst delta-%s due to constraints: %.3f", (MLnniToDo > 0 || MLlen) ? "LogLk" : "Len", splitcount.dWorstDeltaConstrained); fprintf(fp,"\n"); } if (verbose > 1 || fp == fpLog) { double dN2 = NJ->nSeq*(double)NJ->nSeq; fprintf(fp, "Dist/N**2: by-profile %.3f (out %.3f) by-leaf %.3f avg-prof %.3f\n", profileOps/dN2, outprofileOps/dN2, seqOps/dN2, profileAvgOps/dN2); if (nCloseUsed>0 || nClose2Used > 0 || nRefreshTopHits>0) fprintf(fp, "Top hits: close neighbors %ld/%d 2nd-level %ld refreshes %ld", nCloseUsed, NJ->nSeq, nClose2Used, nRefreshTopHits); if(!slow) fprintf(fp, " Hill-climb: %ld Update-best: %ld\n", nHillBetter, nVisibleUpdate); if (nniToDo > 0 || spr > 0 || MLnniToDo > 0) fprintf(fp, "NNI: %ld SPR: %ld ML-NNI: %ld\n", nNNI, nSPR, nML_NNI); if (MLnniToDo > 0) { fprintf(fp, "Max-lk operations: lk %ld posterior %ld", nLkCompute, nPosteriorCompute); if (nAAPosteriorExact > 0 || nAAPosteriorRough > 0) fprintf(fp, " approximate-posteriors %.2f%%", (100.0*nAAPosteriorRough)/(double)(nAAPosteriorExact+nAAPosteriorRough)); if (mlAccuracy < 2) fprintf(fp, " star-only %ld", nStarTests); fprintf(fp, "\n"); } } #ifdef TRACK_MEMORY fprintf(fp, "Memory: %.2f MB (%.1f byte/pos) ", maxmallocHeap/1.0e6, maxmallocHeap/(double)(aln->nSeq*(double)aln->nPos)); /* Only report numbers from before we do reliability estimates */ fprintf(fp, "profile-freq-alloc %ld avoided %.2f%%\n", svProfileFreqAlloc, svProfileFreqAvoid > 0 ? 100.0*svProfileFreqAvoid/(double)(svProfileFreqAlloc+svProfileFreqAvoid) : 0); #endif fflush(fp); } PrintNJ(fpOut, NJ, aln->names, unique, /*support*/nBootstrap > 0, bQuote); fflush(fpOut); if (fpLog) { fprintf(fpLog,"TreeCompleted\n"); fflush(fpLog); } FreeNJ(NJ); if (uniqConstraints != NULL) uniqConstraints = myfree(uniqConstraints, sizeof(char*) * unique->nUnique); constraints = FreeAlignment(constraints); unique = FreeUniquify(unique); } /* end build tree */ hashnames = FreeHashtable(hashnames); aln = FreeAlignment(aln); } /* end loop over alignments */ if (fpLog != NULL) fclose(fpLog); if (fpOut != stdout) fclose(fpOut); exit(0); } void ProgressReport(char *format, int i1, int i2, int i3, int i4) { static bool time_set = false; static struct timeval time_last; static struct timeval time_begin; if (!showProgress) return; static struct timeval time_now; gettimeofday(&time_now,NULL); if (!time_set) { time_begin = time_last = time_now; time_set = true; } static struct timeval elapsed; timeval_subtract(&elapsed,&time_now,&time_last); if (elapsed.tv_sec > 1 || elapsed.tv_usec > 100*1000 || verbose > 1) { timeval_subtract(&elapsed,&time_now,&time_begin); fprintf(stderr, "%7i.%2.2i seconds: ", (int)elapsed.tv_sec, (int)(elapsed.tv_usec/10000)); fprintf(stderr, format, i1, i2, i3, i4); if (verbose > 1 || !isatty(STDERR_FILENO)) { fprintf(stderr, "\n"); } else { fprintf(stderr, " \r"); } fflush(stderr); time_last = time_now; } } void LogMLRates(/*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ) { if (fpLog != NULL) { rates_t *rates = &NJ->rates; fprintf(fpLog, "NCategories\t%d\nRates",rates->nRateCategories); assert(rates->nRateCategories > 0); int iRate; for (iRate = 0; iRate < rates->nRateCategories; iRate++) fprintf(fpLog, " %f", rates->rates[iRate]); fprintf(fpLog,"\nSiteCategories"); int iPos; for (iPos = 0; iPos < NJ->nPos; iPos++) { iRate = rates->ratecat[iPos]; fprintf(fpLog," %d",iRate+1); } fprintf(fpLog,"\n"); fflush(fpLog); } } void LogTree(char *format, int i, /*OPTIONAL WRITE*/FILE *fpLog, NJ_t *NJ, char **names, uniquify_t *unique, bool bQuote) { if(fpLog != NULL) { fprintf(fpLog, format, i); fprintf(fpLog, "\t"); PrintNJ(fpLog, NJ, names, unique, /*support*/false, bQuote); fflush(fpLog); } } NJ_t *InitNJ(char **sequences, int nSeq, int nPos, /*OPTIONAL*/char **constraintSeqs, int nConstraints, /*OPTIONAL*/distance_matrix_t *distance_matrix, /*OPTIONAL*/transition_matrix_t *transmat) { int iNode; NJ_t *NJ = (NJ_t*)mymalloc(sizeof(NJ_t)); NJ->root = -1; /* set at end of FastNJ() */ NJ->maxnode = NJ->nSeq = nSeq; NJ->nPos = nPos; NJ->maxnodes = 2*nSeq; NJ->seqs = sequences; NJ->distance_matrix = distance_matrix; NJ->transmat = transmat; NJ->nConstraints = nConstraints; NJ->constraintSeqs = constraintSeqs; NJ->profiles = (profile_t **)mymalloc(sizeof(profile_t*) * NJ->maxnodes); unsigned long counts[256]; int i; for (i = 0; i < 256; i++) counts[i] = 0; for (iNode = 0; iNode < NJ->nSeq; iNode++) { NJ->profiles[iNode] = SeqToProfile(NJ, NJ->seqs[iNode], nPos, constraintSeqs != NULL ? constraintSeqs[iNode] : NULL, nConstraints, iNode, /*IN/OUT*/counts); } unsigned long totCount = 0; for (i = 0; i < 256; i++) totCount += counts[i]; /* warnings about unknown characters */ for (i = 0; i < 256; i++) { if (counts[i] == 0 || i == '.' || i == '-') continue; unsigned char *codesP; bool bMatched = false; for (codesP = codesString; *codesP != '\0'; codesP++) { if (*codesP == i || tolower(*codesP) == i) { bMatched = true; break; } } if (!bMatched) fprintf(stderr, "Ignored unknown character %c (seen %lu times)\n", i, counts[i]); } /* warnings about the counts */ double fACGTUN = (counts['A'] + counts['C'] + counts['G'] + counts['T'] + counts['U'] + counts['N'] + counts['a'] + counts['c'] + counts['g'] + counts['t'] + counts['u'] + counts['n']) / (double)(totCount - counts['-'] - counts['.']); if (nCodes == 4 && fACGTUN < 0.9) fprintf(stderr, "WARNING! ONLY %.1f%% NUCLEOTIDE CHARACTERS -- IS THIS REALLY A NUCLEOTIDE ALIGNMENT?\n", 100.0 * fACGTUN); else if (nCodes == 20 && fACGTUN >= 0.9) fprintf(stderr, "WARNING! %.1f%% NUCLEOTIDE CHARACTERS -- IS THIS REALLY A PROTEIN ALIGNMENT?\n", 100.0 * fACGTUN); if(verbose>10) fprintf(stderr,"Made sequence profiles\n"); for (iNode = NJ->nSeq; iNode < NJ->maxnodes; iNode++) NJ->profiles[iNode] = NULL; /* not yet exists */ NJ->outprofile = OutProfile(NJ->profiles, NJ->nSeq, NJ->nPos, NJ->nConstraints, NJ->distance_matrix); if(verbose>10) fprintf(stderr,"Made out-profile\n"); NJ->totdiam = 0.0; NJ->diameter = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->diameter[iNode] = 0; NJ->varDiameter = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->varDiameter[iNode] = 0; NJ->selfdist = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->selfdist[iNode] = 0; NJ->selfweight = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->nSeq; iNode++) NJ->selfweight[iNode] = NJ->nPos - NGaps(NJ,iNode); NJ->outDistances = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); NJ->nOutDistActive = (int *)mymalloc(sizeof(int)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->nOutDistActive[iNode] = NJ->nSeq * 10; /* unreasonably high value */ NJ->parent = NULL; /* so SetOutDistance ignores it */ for (iNode = 0; iNode < NJ->nSeq; iNode++) SetOutDistance(/*IN/UPDATE*/NJ, iNode, /*nActive*/NJ->nSeq); if (verbose>2) { for (iNode = 0; iNode < 4 && iNode < NJ->nSeq; iNode++) fprintf(stderr, "Node %d outdist %f\n", iNode, NJ->outDistances[iNode]); } NJ->parent = (int *)mymalloc(sizeof(int)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->parent[iNode] = -1; NJ->branchlength = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); /* distance to parent */ for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->branchlength[iNode] = 0; NJ->support = (numeric_t *)mymalloc(sizeof(numeric_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->maxnodes; iNode++) NJ->support[iNode] = -1.0; NJ->child = (children_t*)mymalloc(sizeof(children_t)*NJ->maxnodes); for (iNode= 0; iNode < NJ->maxnode; iNode++) NJ->child[iNode].nChild = 0; NJ->rates.nRateCategories = 0; NJ->rates.rates = NULL; NJ->rates.ratecat = NULL; AllocRateCategories(&NJ->rates, 1, NJ->nPos); return(NJ); } NJ_t *FreeNJ(NJ_t *NJ) { if (NJ==NULL) return(NJ); int i; for (i=0; i < NJ->maxnode; i++) NJ->profiles[i] = FreeProfile(NJ->profiles[i], NJ->nPos, NJ->nConstraints); NJ->profiles = myfree(NJ->profiles, sizeof(profile_t*) * NJ->maxnodes); NJ->outprofile = FreeProfile(NJ->outprofile, NJ->nPos, NJ->nConstraints); NJ->diameter = myfree(NJ->diameter, sizeof(numeric_t)*NJ->maxnodes); NJ->varDiameter = myfree(NJ->varDiameter, sizeof(numeric_t)*NJ->maxnodes); NJ->selfdist = myfree(NJ->selfdist, sizeof(numeric_t)*NJ->maxnodes); NJ->selfweight = myfree(NJ->selfweight, sizeof(numeric_t)*NJ->maxnodes); NJ->outDistances = myfree(NJ->outDistances, sizeof(numeric_t)*NJ->maxnodes); NJ->nOutDistActive = myfree(NJ->nOutDistActive, sizeof(int)*NJ->maxnodes); NJ->parent = myfree(NJ->parent, sizeof(int)*NJ->maxnodes); NJ->branchlength = myfree(NJ->branchlength, sizeof(numeric_t)*NJ->maxnodes); NJ->support = myfree(NJ->support, sizeof(numeric_t)*NJ->maxnodes); NJ->child = myfree(NJ->child, sizeof(children_t)*NJ->maxnodes); NJ->transmat = myfree(NJ->transmat, sizeof(transition_matrix_t)); AllocRateCategories(&NJ->rates, 0, NJ->nPos); return(myfree(NJ, sizeof(NJ_t))); } /* Allocate or reallocate the rate categories, and set every position to category 0 and every category's rate to 1.0 If nRateCategories=0, just deallocate */ void AllocRateCategories(/*IN/OUT*/rates_t *rates, int nRateCategories, int nPos) { assert(nRateCategories >= 0); rates->rates = myfree(rates->rates, sizeof(numeric_t)*rates->nRateCategories); rates->ratecat = myfree(rates->ratecat, sizeof(unsigned int)*nPos); rates->nRateCategories = nRateCategories; if (rates->nRateCategories > 0) { rates->rates = (numeric_t*)mymalloc(sizeof(numeric_t)*rates->nRateCategories); int i; for (i = 0; i < nRateCategories; i++) rates->rates[i] = 1.0; rates->ratecat = (unsigned int *)mymalloc(sizeof(unsigned int)*nPos); for (i = 0; i < nPos; i++) rates->ratecat[i] = 0; } } void FastNJ(NJ_t *NJ) { int iNode; assert(NJ->nSeq >= 1); if (NJ->nSeq < 3) { NJ->root = NJ->maxnode++; NJ->child[NJ->root].nChild = NJ->nSeq; for (iNode = 0; iNode < NJ->nSeq; iNode++) { NJ->parent[iNode] = NJ->root; NJ->child[NJ->root].child[iNode] = iNode; } if (NJ->nSeq == 1) { NJ->branchlength[0] = 0; } else { assert (NJ->nSeq == 2); besthit_t hit; SeqDist(NJ->profiles[0]->codes,NJ->profiles[1]->codes,NJ->nPos,NJ->distance_matrix,/*OUT*/&hit); NJ->branchlength[0] = hit.dist/2.0; NJ->branchlength[1] = hit.dist/2.0; } return; } /* else 3 or more sequences */ /* The visible set stores the best hit of each node (unless using top hits, in which case it is handled by the top hits routines) */ besthit_t *visible = NULL; /* Not used if doing top hits */ besthit_t *besthitNew = NULL; /* All hits of new node -- not used if doing top-hits */ /* The top-hits lists, with the key parameter m = length of each top-hit list */ top_hits_t *tophits = NULL; int m = 0; /* maximum length of a top-hits list */ if (tophitsMult > 0) { m = (int)(0.5 + tophitsMult*sqrt(NJ->nSeq)); if(m<4 || 2*m >= NJ->nSeq) { m=0; if(verbose>1) fprintf(stderr,"Too few leaves, turning off top-hits\n"); } else { if(verbose>2) fprintf(stderr,"Top-hit-list size = %d of %d\n", m, NJ->nSeq); } } assert(!(slow && m>0)); /* Initialize top-hits or visible set */ if (m>0) { tophits = InitTopHits(NJ, m); SetAllLeafTopHits(/*IN/UPDATE*/NJ, /*OUT*/tophits); ResetTopVisible(/*IN/UPDATE*/NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/tophits); } else if (!slow) { visible = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnodes); besthitNew = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnodes); for (iNode = 0; iNode < NJ->nSeq; iNode++) SetBestHit(iNode, NJ, /*nActive*/NJ->nSeq, /*OUT*/&visible[iNode], /*OUT IGNORED*/NULL); } /* Iterate over joins */ int nActiveOutProfileReset = NJ->nSeq; int nActive; for (nActive = NJ->nSeq; nActive > 3; nActive--) { int nJoinsDone = NJ->nSeq - nActive; if (nJoinsDone > 0 && (nJoinsDone % 100) == 0) ProgressReport("Joined %6d of %6d", nJoinsDone, NJ->nSeq-3, 0, 0); besthit_t join; /* the join to do */ if (slow) { ExhaustiveNJSearch(NJ,nActive,/*OUT*/&join); } else if (m>0) { TopHitNJSearch(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, /*OUT*/&join); } else { FastNJSearch(NJ, nActive, /*IN/OUT*/visible, /*OUT*/&join); } if (verbose>2) { double penalty = constraintWeight * (double)JoinConstraintPenalty(NJ, join.i, join.j); if (penalty > 0.001) { fprintf(stderr, "Constraint violation during neighbor-joining %d %d into %d penalty %.3f\n", join.i, join.j, NJ->maxnode, penalty); int iC; for (iC = 0; iC < NJ->nConstraints; iC++) { int local = JoinConstraintPenaltyPiece(NJ, join.i, join.j, iC); if (local > 0) fprintf(stderr, "Constraint %d piece %d %d/%d %d/%d %d/%d\n", iC, local, NJ->profiles[join.i]->nOn[iC], NJ->profiles[join.i]->nOff[iC], NJ->profiles[join.j]->nOn[iC], NJ->profiles[join.j]->nOff[iC], NJ->outprofile->nOn[iC] - NJ->profiles[join.i]->nOn[iC] - NJ->profiles[join.j]->nOn[iC], NJ->outprofile->nOff[iC] - NJ->profiles[join.i]->nOff[iC] - NJ->profiles[join.j]->nOff[iC]); } } } /* because of the stale out-distance heuristic, make sure that these are up-to-date */ SetOutDistance(NJ, join.i, nActive); SetOutDistance(NJ, join.j, nActive); /* Make sure weight is set and criterion is up to date */ SetDistCriterion(NJ, nActive, /*IN/OUT*/&join); assert(NJ->nOutDistActive[join.i] == nActive); assert(NJ->nOutDistActive[join.j] == nActive); int newnode = NJ->maxnode++; NJ->parent[join.i] = newnode; NJ->parent[join.j] = newnode; NJ->child[newnode].nChild = 2; NJ->child[newnode].child[0] = join.i < join.j ? join.i : join.j; NJ->child[newnode].child[1] = join.i > join.j ? join.i : join.j; double rawIJ = join.dist + NJ->diameter[join.i] + NJ->diameter[join.j]; double distIJ = join.dist; double deltaDist = (NJ->outDistances[join.i]-NJ->outDistances[join.j])/(double)(nActive-2); NJ->branchlength[join.i] = (distIJ + deltaDist)/2; NJ->branchlength[join.j] = (distIJ - deltaDist)/2; double bionjWeight = 0.5; /* IJ = bionjWeight*I + (1-bionjWeight)*J */ double varIJ = rawIJ - NJ->varDiameter[join.i] - NJ->varDiameter[join.j]; if (bionj && join.weight > 0.01 && varIJ > 0.001) { /* Set bionjWeight according to the BIONJ formula, where the variance matrix is approximated by Vij = ProfileVar(i,j) - varDiameter(i) - varDiameter(j) ProfileVar(i,j) = distance(i,j) = top(i,j)/weight(i,j) (The node's distance diameter does not affect the variances.) The BIONJ formula is equation 9 from Gascuel 1997: bionjWeight = 1/2 + sum(k!=i,j) (Vjk - Vik) / ((nActive-2)*Vij) sum(k!=i,j) (Vjk - Vik) = sum(k!=i,j) Vik - varDiameter(j) + varDiameter(i) = sum(k!=i,j) ProfileVar(j,k) - sum(k!=i,j) ProfileVar(i,k) + (nActive-2)*(varDiameter(i)-varDiameter(j)) sum(k!=i,j) ProfileVar(i,k) ~= (sum(k!=i,j) distance(i,k) * weight(i,k))/(mean(k!=i,j) weight(i,k)) ~= (N-2) * top(i, Out-i-j) / weight(i, Out-i-j) weight(i, Out-i-j) = N*weight(i,Out) - weight(i,i) - weight(i,j) top(i, Out-i-j) = N*top(i,Out) - top(i,i) - top(i,j) */ besthit_t outI; besthit_t outJ; ProfileDist(NJ->profiles[join.i],NJ->outprofile,NJ->nPos,NJ->distance_matrix,/*OUT*/&outI); ProfileDist(NJ->profiles[join.j],NJ->outprofile,NJ->nPos,NJ->distance_matrix,/*OUT*/&outJ); outprofileOps += 2; double varIWeight = (nActive * outI.weight - NJ->selfweight[join.i] - join.weight); double varJWeight = (nActive * outJ.weight - NJ->selfweight[join.j] - join.weight); double varITop = outI.dist * outI.weight * nActive - NJ->selfdist[join.i] * NJ->selfweight[join.i] - rawIJ * join.weight; double varJTop = outJ.dist * outJ.weight * nActive - NJ->selfdist[join.j] * NJ->selfweight[join.j] - rawIJ * join.weight; double deltaProfileVarOut = (nActive-2) * (varJTop/varJWeight - varITop/varIWeight); double deltaVarDiam = (nActive-2)*(NJ->varDiameter[join.i] - NJ->varDiameter[join.j]); if (varJWeight > 0.01 && varIWeight > 0.01) bionjWeight = 0.5 + (deltaProfileVarOut+deltaVarDiam)/(2*(nActive-2)*varIJ); if(bionjWeight<0) bionjWeight=0; if(bionjWeight>1) bionjWeight=1; if (verbose>2) fprintf(stderr,"dVarO %f dVarDiam %f varIJ %f from dist %f weight %f (pos %d) bionjWeight %f %f\n", deltaProfileVarOut, deltaVarDiam, varIJ, join.dist, join.weight, NJ->nPos, bionjWeight, 1-bionjWeight); if (verbose>3 && (newnode%5) == 0) { /* Compare weight estimated from outprofiles from weight made by summing over other nodes */ double deltaProfileVarTot = 0; for (iNode = 0; iNode < newnode; iNode++) { if (NJ->parent[iNode] < 0) { /* excludes join.i, join.j */ besthit_t di, dj; ProfileDist(NJ->profiles[join.i],NJ->profiles[iNode],NJ->nPos,NJ->distance_matrix,/*OUT*/&di); ProfileDist(NJ->profiles[join.j],NJ->profiles[iNode],NJ->nPos,NJ->distance_matrix,/*OUT*/&dj); deltaProfileVarTot += dj.dist - di.dist; } } double lambdaTot = 0.5 + (deltaProfileVarTot+deltaVarDiam)/(2*(nActive-2)*varIJ); if (lambdaTot < 0) lambdaTot = 0; if (lambdaTot > 1) lambdaTot = 1; if (fabs(bionjWeight-lambdaTot) > 0.01 || verbose > 4) fprintf(stderr, "deltaProfileVar actual %.6f estimated %.6f lambda actual %.3f estimated %.3f\n", deltaProfileVarTot,deltaProfileVarOut,lambdaTot,bionjWeight); } } if (verbose > 2) fprintf(stderr, "Join\t%d\t%d\t%.6f\tlambda\t%.6f\tselfw\t%.3f\t%.3f\tnew\t%d\n", join.i < join.j ? join.i : join.j, join.i < join.j ? join.j : join.i, join.criterion, bionjWeight, NJ->selfweight[join.i < join.j ? join.i : join.j], NJ->selfweight[join.i < join.j ? join.j : join.i], newnode); NJ->diameter[newnode] = bionjWeight * (NJ->branchlength[join.i] + NJ->diameter[join.i]) + (1-bionjWeight) * (NJ->branchlength[join.j] + NJ->diameter[join.j]); NJ->varDiameter[newnode] = bionjWeight * NJ->varDiameter[join.i] + (1-bionjWeight) * NJ->varDiameter[join.j] + bionjWeight * (1-bionjWeight) * varIJ; NJ->profiles[newnode] = AverageProfile(NJ->profiles[join.i],NJ->profiles[join.j], NJ->nPos, NJ->nConstraints, NJ->distance_matrix, bionj ? bionjWeight : /*noweight*/-1.0); /* Update out-distances and total diameters */ int changedActiveOutProfile = nActiveOutProfileReset - (nActive-1); if (changedActiveOutProfile >= nResetOutProfile && changedActiveOutProfile >= fResetOutProfile * nActiveOutProfileReset) { /* Recompute the outprofile from scratch to avoid roundoff error */ profile_t **activeProfiles = (profile_t**)mymalloc(sizeof(profile_t*)*(nActive-1)); int nSaved = 0; NJ->totdiam = 0; for (iNode=0;iNode<NJ->maxnode;iNode++) { if (NJ->parent[iNode]<0) { assert(nSaved < nActive-1); activeProfiles[nSaved++] = NJ->profiles[iNode]; NJ->totdiam += NJ->diameter[iNode]; } } assert(nSaved==nActive-1); FreeProfile(NJ->outprofile, NJ->nPos, NJ->nConstraints); if(verbose>2) fprintf(stderr,"Recomputing outprofile %d %d\n",nActiveOutProfileReset,nActive-1); NJ->outprofile = OutProfile(activeProfiles, nSaved, NJ->nPos, NJ->nConstraints, NJ->distance_matrix); activeProfiles = myfree(activeProfiles, sizeof(profile_t*)*(nActive-1)); nActiveOutProfileReset = nActive-1; } else { UpdateOutProfile(/*OUT*/NJ->outprofile, NJ->profiles[join.i], NJ->profiles[join.j], NJ->profiles[newnode], nActive, NJ->nPos, NJ->nConstraints, NJ->distance_matrix); NJ->totdiam += NJ->diameter[newnode] - NJ->diameter[join.i] - NJ->diameter[join.j]; } /* Store self-dist for use in other computations */ besthit_t selfdist; ProfileDist(NJ->profiles[newnode],NJ->profiles[newnode],NJ->nPos,NJ->distance_matrix,/*OUT*/&selfdist); NJ->selfdist[newnode] = selfdist.dist; NJ->selfweight[newnode] = selfdist.weight; /* Find the best hit of the joined node IJ */ if (m>0) { TopHitJoin(newnode, /*IN/UPDATE*/NJ, nActive-1, /*IN/OUT*/tophits); } else { /* Not using top-hits, so we update all out-distances */ for (iNode = 0; iNode < NJ->maxnode; iNode++) { if (NJ->parent[iNode] < 0) { /* True nActive is now nActive-1 */ SetOutDistance(/*IN/UPDATE*/NJ, iNode, nActive-1); } } if(visible != NULL) { SetBestHit(newnode, NJ, nActive-1, /*OUT*/&visible[newnode], /*OUT OPTIONAL*/besthitNew); if (verbose>2) fprintf(stderr,"Visible %d %d %f %f\n", visible[newnode].i, visible[newnode].j, visible[newnode].dist, visible[newnode].criterion); if (besthitNew != NULL) { /* Use distances to new node to update visible set entries that are non-optimal */ for (iNode = 0; iNode < NJ->maxnode; iNode++) { if (NJ->parent[iNode] >= 0 || iNode == newnode) continue; int iOldVisible = visible[iNode].j; assert(iOldVisible>=0); assert(visible[iNode].i == iNode); /* Update the criterion; use nActive-1 because haven't decremented nActive yet */ if (NJ->parent[iOldVisible] < 0) SetCriterion(/*IN/OUT*/NJ, nActive-1, &visible[iNode]); if (NJ->parent[iOldVisible] >= 0 || besthitNew[iNode].criterion < visible[iNode].criterion) { if(verbose>3) fprintf(stderr,"Visible %d reset from %d to %d (%f vs. %f)\n", iNode, iOldVisible, newnode, visible[iNode].criterion, besthitNew[iNode].criterion); if(NJ->parent[iOldVisible] < 0) nVisibleUpdate++; visible[iNode].j = newnode; visible[iNode].dist = besthitNew[iNode].dist; visible[iNode].criterion = besthitNew[iNode].criterion; } } /* end loop over all nodes */ } /* end if recording all hits of new node */ } /* end if keeping a visible set */ } /* end else (m==0) */ } /* end loop over nActive */ #ifdef TRACK_MEMORY if (verbose>1) { struct mallinfo mi = mallinfo(); fprintf(stderr, "Memory @ end of FastNJ(): %.2f MB (%.1f byte/pos) useful %.2f expected %.2f\n", (mi.arena+mi.hblkhd)/1.0e6, (mi.arena+mi.hblkhd)/(double)(NJ->nSeq*(double)NJ->nPos), mi.uordblks/1.0e6, mymallocUsed/1e6); } #endif /* We no longer need the tophits, visible set, etc. */ if (visible != NULL) visible = myfree(visible,sizeof(besthit_t)*NJ->maxnodes); if (besthitNew != NULL) besthitNew = myfree(besthitNew,sizeof(besthit_t)*NJ->maxnodes); tophits = FreeTopHits(tophits); /* Add a root for the 3 remaining nodes */ int top[3]; int nTop = 0; for (iNode = 0; iNode < NJ->maxnode; iNode++) { if (NJ->parent[iNode] < 0) { assert(nTop <= 2); top[nTop++] = iNode; } } assert(nTop==3); NJ->root = NJ->maxnode++; NJ->child[NJ->root].nChild = 3; for (nTop = 0; nTop < 3; nTop++) { NJ->parent[top[nTop]] = NJ->root; NJ->child[NJ->root].child[nTop] = top[nTop]; } besthit_t dist01, dist02, dist12; ProfileDist(NJ->profiles[top[0]], NJ->profiles[top[1]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist01); ProfileDist(NJ->profiles[top[0]], NJ->profiles[top[2]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist02); ProfileDist(NJ->profiles[top[1]], NJ->profiles[top[2]], NJ->nPos, NJ->distance_matrix, /*OUT*/&dist12); double d01 = dist01.dist - NJ->diameter[top[0]] - NJ->diameter[top[1]]; double d02 = dist02.dist - NJ->diameter[top[0]] - NJ->diameter[top[2]]; double d12 = dist12.dist - NJ->diameter[top[1]] - NJ->diameter[top[2]]; NJ->branchlength[top[0]] = (d01 + d02 - d12)/2; NJ->branchlength[top[1]] = (d01 + d12 - d02)/2; NJ->branchlength[top[2]] = (d02 + d12 - d01)/2; /* Check how accurate the outprofile is */ if (verbose>2) { profile_t *p[3] = {NJ->profiles[top[0]], NJ->profiles[top[1]], NJ->profiles[top[2]]}; profile_t *out = OutProfile(p, 3, NJ->nPos, NJ->nConstraints, NJ->distance_matrix); int i; double freqerror = 0; double weighterror = 0; for (i=0;i<NJ->nPos;i++) { weighterror += fabs(out->weights[i] - NJ->outprofile->weights[i]); int k; for(k=0;k<nCodes;k++) freqerror += fabs(out->vectors[nCodes*i+k] - NJ->outprofile->vectors[nCodes*i+k]); } fprintf(stderr,"Roundoff error in outprofile@end: WeightError %f FreqError %f\n", weighterror, freqerror); FreeProfile(out, NJ->nPos, NJ->nConstraints); } return; } void ExhaustiveNJSearch(NJ_t *NJ, int nActive, /*OUT*/besthit_t *join) { join->i = -1; join->j = -1; join->weight = 0; join->dist = 1e20; join->criterion = 1e20; double bestCriterion = 1e20; int i, j; for (i = 0; i < NJ->maxnode-1; i++) { if (NJ->parent[i] < 0) { for (j = i+1; j < NJ->maxnode; j++) { if (NJ->parent[j] < 0) { besthit_t hit; hit.i = i; hit.j = j; SetDistCriterion(NJ, nActive, /*IN/OUT*/&hit); if (hit.criterion < bestCriterion) { *join = hit; bestCriterion = hit.criterion; } } } } } assert (join->i >= 0 && join->j >= 0); } void FastNJSearch(NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *besthits, /*OUT*/besthit_t *join) { join->i = -1; join->j = -1; join->dist = 1e20; join->weight = 0; join->criterion = 1e20; int iNode; for (iNode = 0; iNode < NJ->maxnode; iNode++) { int jNode = besthits[iNode].j; if (NJ->parent[iNode] < 0 && NJ->parent[jNode] < 0) { /* both i and j still active */ /* recompute criterion to reflect the current out-distances */ SetCriterion(NJ, nActive, /*IN/OUT*/&besthits[iNode]); if (besthits[iNode].criterion < join->criterion) *join = besthits[iNode]; } } if(!fastest) { int changed; do { changed = 0; assert(join->i >= 0 && join->j >= 0); SetBestHit(join->i, NJ, nActive, /*OUT*/&besthits[join->i], /*OUT IGNORED*/NULL); if (besthits[join->i].j != join->j) { changed = 1; if (verbose>2) fprintf(stderr,"BetterI\t%d\t%d\t%d\t%d\t%f\t%f\n", join->i,join->j,besthits[join->i].i,besthits[join->i].j, join->criterion,besthits[join->i].criterion); } /* Save the best hit either way, because the out-distance has probably changed since we started the computation. */ join->j = besthits[join->i].j; join->weight = besthits[join->i].weight; join->dist = besthits[join->i].dist; join->criterion = besthits[join->i].criterion; SetBestHit(join->j, NJ, nActive, /*OUT*/&besthits[join->j], /*OUT IGNORE*/NULL); if (besthits[join->j].j != join->i) { changed = 1; if (verbose>2) fprintf(stderr,"BetterJ\t%d\t%d\t%d\t%d\t%f\t%f\n", join->i,join->j,besthits[join->j].i,besthits[join->j].j, join->criterion,besthits[join->j].criterion); join->i = besthits[join->j].j; join->weight = besthits[join->j].weight; join->dist = besthits[join->j].dist; join->criterion = besthits[join->j].criterion; } if(changed) nHillBetter++; } while(changed); } } /* A token is one of ():;, or an alphanumeric string without whitespace Any whitespace between tokens is ignored */ char *ReadTreeToken(FILE *fp) { static char buf[BUFFER_SIZE]; int len = 0; int c; for (c = fgetc(fp); c != EOF; c = fgetc(fp)) { if (c == '(' || c == ')' || c == ':' || c == ';' || c == ',') { /* standalone token */ if (len == 0) { buf[len++] = c; buf[len] = '\0'; return(buf); } else { ungetc(c, fp); buf[len] = '\0'; return(buf); } } else if (isspace(c)) { if (len > 0) { buf[len] = '\0'; return(buf); } /* else ignore whitespace at beginning of token */ } else { /* not whitespace or standalone token */ buf[len++] = c; if (len >= BUFFER_SIZE) { buf[BUFFER_SIZE-1] = '\0'; fprintf(stderr, "Token too long in tree file, token begins with\n%s\n", buf); exit(1); } } } if (len > 0) { /* return the token we have so far */ buf[len] = '\0'; return(buf); } /* else */ return(NULL); } void ReadTreeError(char *err, char *token) { fprintf(stderr, "Tree parse error: unexpected token '%s' -- %s\n", token == NULL ? "(End of file)" : token, err); exit(1); } void ReadTreeAddChild(int parent, int child, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children) { assert(parent >= 0); assert(child >= 0); assert(parents[child] < 0); assert(children[parent].nChild < 3); parents[child] = parent; children[parent].child[children[parent].nChild++] = child; } void ReadTreeMaybeAddLeaf(int parent, char *name, hashstrings_t *hashnames, uniquify_t *unique, /*IN/OUT*/int *parents, /*IN/OUT*/children_t *children) { hashiterator_t hi = FindMatch(hashnames,name); if (HashCount(hashnames,hi) != 1) ReadTreeError("not recognized as a sequence name", name); int iSeqNonunique = HashFirst(hashnames,hi); assert(iSeqNonunique >= 0 && iSeqNonunique < unique->nSeq); int iSeqUnique = unique->alnToUniq[iSeqNonunique]; assert(iSeqUnique >= 0 && iSeqUnique < unique->nUnique); /* Either record this leaves' parent (if it is -1) or ignore this leaf (if already seen) */ if (parents[iSeqUnique] < 0) { ReadTreeAddChild(parent, iSeqUnique, /*IN/OUT*/parents, /*IN/OUT*/children); if(verbose > 5) fprintf(stderr, "Found leaf uniq%d name %s child of %d\n", iSeqUnique, name, parent); } else { if (verbose > 5) fprintf(stderr, "Skipped redundant leaf uniq%d name %s\n", iSeqUnique, name); } } void ReadTreeRemove(/*IN/OUT*/int *parents, /*IN/OUT*/children_t *children, int node) { if(verbose > 5) fprintf(stderr,"Removing node %d parent %d\n", node, parents[node]); assert(parents[node] >= 0); int parent = parents[node]; parents[node] = -1; children_t *pc = &children[parent]; int oldn; for (oldn = 0; oldn < pc->nChild; oldn++) { if (pc->child[oldn] == node) break; } assert(oldn < pc->nChild); /* move successor nodes back in child list and shorten list */ int i; for (i = oldn; i < pc->nChild-1; i++) pc->child[i] = pc->child[i+1]; pc->nChild--; /* add its children to parent's child list */ children_t *nc = &children[node]; if (nc->nChild > 0) { assert(nc->nChild<=2); assert(pc->nChild < 3); assert(pc->nChild + nc->nChild <= 3); int j; for (j = 0; j < nc->nChild; j++) { if(verbose > 5) fprintf(stderr,"Repointing parent %d to child %d\n", parent, nc->child[j]); pc->child[pc->nChild++] = nc->child[j]; parents[nc->child[j]] = parent; } nc->nChild = 0; } } void ReadTree(/*IN/OUT*/NJ_t *NJ, /*IN*/uniquify_t *unique, /*IN*/hashstrings_t *hashnames, /*READ*/FILE *fpInTree) { assert(NJ->nSeq == unique->nUnique); /* First, do a preliminary parse of the tree to with non-unique leaves ignored We need to store this separately from NJ because it may have too many internal nodes (matching sequences show up once in the NJ but could be in multiple places in the tree) Will use iUnique as the index of nodes, as in the NJ structure */ int maxnodes = unique->nSeq*2; int maxnode = unique->nSeq; int *parent = (int*)mymalloc(sizeof(int)*maxnodes); children_t *children = (children_t *)mymalloc(sizeof(children_t)*maxnodes); int root = maxnode++; int i; for (i = 0; i < maxnodes; i++) { parent[i] = -1; children[i].nChild = 0; } /* The stack is the current path to the root, with the root at the first (top) position */ int stack_size = 1; int *stack = (int*)mymalloc(sizeof(int)*maxnodes); stack[0] = root; int nDown = 0; int nUp = 0; char *token; token = ReadTreeToken(fpInTree); if (token == NULL || *token != '(') ReadTreeError("No '(' at start", token); /* nDown is still 0 because we have created the root */ while ((token = ReadTreeToken(fpInTree)) != NULL) { if (nDown > 0) { /* In a stream of parentheses */ if (*token == '(') nDown++; else if (*token == ',' || *token == ';' || *token == ':' || *token == ')') ReadTreeError("while reading parentheses", token); else { /* Add intermediate nodes if nDown was > 1 (for nDown=1, the only new node is the leaf) */ while (nDown-- > 0) { int new = maxnode++; assert(new < maxnodes); ReadTreeAddChild(stack[stack_size-1], new, /*IN/OUT*/parent, /*IN/OUT*/children); if(verbose > 5) fprintf(stderr, "Added internal child %d of %d, stack size increase to %d\n", new, stack[stack_size-1],stack_size+1); stack[stack_size++] = new; assert(stack_size < maxnodes); } ReadTreeMaybeAddLeaf(stack[stack_size-1], token, hashnames, unique, /*IN/OUT*/parent, /*IN/OUT*/children); } } else if (nUp > 0) { if (*token == ';') { /* end the tree? */ if (nUp != stack_size) ReadTreeError("unbalanced parentheses", token); else break; } else if (*token == ')') nUp++; else if (*token == '(') ReadTreeError("unexpected '(' after ')'", token); else if (*token == ':') { token = ReadTreeToken(fpInTree); /* Read the branch length and ignore it */ if (token == NULL || (*token != '-' && !isdigit(*token))) ReadTreeError("not recognized as a branch length", token); } else if (*token == ',') { /* Go back up the stack the correct #times */ while (nUp-- > 0) { stack_size--; if(verbose > 5) fprintf(stderr, "Up to nUp=%d stack size %d at %d\n", nUp, stack_size, stack[stack_size-1]); if (stack_size <= 0) ReadTreeError("too many ')'", token); } nUp = 0; } else if (*token == '-' || isdigit(*token)) ; /* ignore bootstrap value */ else fprintf(stderr, "Warning while parsing tree: non-numeric label %s for internal node\n", token); } else if (*token == '(') { nDown = 1; } else if (*token == ')') { nUp = 1; } else if (*token == ':') { token = ReadTreeToken(fpInTree); if (token == NULL || (*token != '-' && !isdigit(*token))) ReadTreeError("not recognized as a branch length", token); } else if (*token == ',') { ; /* do nothing */ } else if (*token == ';') ReadTreeError("unexpected token", token); else ReadTreeMaybeAddLeaf(stack[stack_size-1], token, hashnames, unique, /*IN/OUT*/parent, /*IN/OUT*/children); } /* Verify that all sequences were seen */ for (i = 0; i < unique->nUnique; i++) { if (parent[i] < 0) { fprintf(stderr, "Alignment sequence %d (unique %d) absent from input tree\n" "The starting tree (the argument to -intree) must include all sequences in the alignment!\n", unique->uniqueFirst[i], i); exit(1); } } /* Simplify the tree -- remove all internal nodes with < 2 children Keep trying until no nodes get removed */ int nRemoved; do { nRemoved = 0; /* Here stack is the list of nodes we haven't visited yet while doing a tree traversal */ stack_size = 1; stack[0] = root; while (stack_size > 0) { int node = stack[--stack_size]; if (node >= unique->nUnique) { /* internal node */ if (children[node].nChild <= 1) { if (node != root) { ReadTreeRemove(/*IN/OUT*/parent,/*IN/OUT*/children,node); nRemoved++; } else if (node == root && children[node].nChild == 1) { int newroot = children[node].child[0]; parent[newroot] = -1; children[root].nChild = 0; nRemoved++; if(verbose > 5) fprintf(stderr,"Changed root from %d to %d\n",root,newroot); root = newroot; stack[stack_size++] = newroot; } } else { int j; for (j = 0; j < children[node].nChild; j++) { assert(stack_size < maxnodes); stack[stack_size++] = children[node].child[j]; if(verbose > 5) fprintf(stderr,"Added %d to stack\n", stack[stack_size-1]); } } } } } while (nRemoved > 0); /* Simplify the root node to 3 children if it has 2 */ if (children[root].nChild == 2) { for (i = 0; i < 2; i++) { int child = children[root].child[i]; assert(child >= 0 && child < maxnodes); if (children[child].nChild == 2) { ReadTreeRemove(parent,children,child); /* replace root -> child -> A,B with root->A,B */ break; } } } for (i = 0; i < maxnodes; i++) if(verbose > 5) fprintf(stderr,"Simplfied node %d has parent %d nchild %d\n", i, parent[i], children[i].nChild); /* Map the remaining internal nodes to NJ nodes */ int *map = (int*)mymalloc(sizeof(int)*maxnodes); for (i = 0; i < unique->nUnique; i++) map[i] = i; for (i = unique->nUnique; i < maxnodes; i++) map[i] = -1; stack_size = 1; stack[0] = root; while (stack_size > 0) { int node = stack[--stack_size]; if (node >= unique->nUnique) { /* internal node */ assert(node == root || children[node].nChild > 1); map[node] = NJ->maxnode++; for (i = 0; i < children[node].nChild; i++) { assert(stack_size < maxnodes); stack[stack_size++] = children[node].child[i]; } } } for (i = 0; i < maxnodes; i++) if(verbose > 5) fprintf(stderr,"Map %d to %d (parent %d nchild %d)\n", i, map[i], parent[i], children[i].nChild); /* Set NJ->parent, NJ->children, NJ->root */ NJ->root = map[root]; int node; for (node = 0; node < maxnodes; node++) { int njnode = map[node]; if (njnode >= 0) { NJ->child[njnode].nChild = children[node].nChild; for (i = 0; i < children[node].nChild; i++) { assert(children[node].child[i] >= 0 && children[node].child[i] < maxnodes); NJ->child[njnode].child[i] = map[children[node].child[i]]; } if (parent[node] >= 0) NJ->parent[njnode] = map[parent[node]]; } } /* Make sure that parent/child relationships match */ for (i = 0; i < NJ->maxnode; i++) { children_t *c = &NJ->child[i]; int j; for (j = 0; j < c->nChild;j++) assert(c->child[j] >= 0 && c->child[j] < NJ->maxnode && NJ->parent[c->child[j]] == i); } assert(NJ->parent[NJ->root] < 0); map = myfree(map,sizeof(int)*maxnodes); stack = myfree(stack,sizeof(int)*maxnodes); children = myfree(children,sizeof(children_t)*maxnodes); parent = myfree(parent,sizeof(int)*maxnodes); /* Compute profiles as balanced -- the NNI stage will recompute these profiles anyway */ traversal_t traversal = InitTraversal(NJ); node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (node >= NJ->nSeq && node != NJ->root) SetProfile(/*IN/OUT*/NJ, node, /*noweight*/-1.0); } traversal = FreeTraversal(traversal,NJ); } /* Print topology using node indices as node names */ void PrintNJInternal(FILE *fp, NJ_t *NJ, bool useLen) { if (NJ->nSeq < 4) { return; } typedef struct { int node; int end; } stack_t; stack_t *stack = (stack_t *)mymalloc(sizeof(stack_t)*NJ->maxnodes); int stackSize = 1; stack[0].node = NJ->root; stack[0].end = 0; while(stackSize>0) { stack_t *last = &stack[stackSize-1]; stackSize--; /* Save last, as we are about to overwrite it */ int node = last->node; int end = last->end; if (node < NJ->nSeq) { if (NJ->child[NJ->parent[node]].child[0] != node) fputs(",",fp); fprintf(fp, "%d", node); if (useLen) fprintf(fp, ":%.4f", NJ->branchlength[node]); } else if (end) { fprintf(fp, ")%d", node); if (useLen) fprintf(fp, ":%.4f", NJ->branchlength[node]); } else { if (node != NJ->root && NJ->child[NJ->parent[node]].child[0] != node) fprintf(fp, ","); fprintf(fp, "("); stackSize++; stack[stackSize-1].node = node; stack[stackSize-1].end = 1; children_t *c = &NJ->child[node]; /* put children on in reverse order because we use the last one first */ int i; for (i = c->nChild-1; i >=0; i--) { stackSize++; stack[stackSize-1].node = c->child[i]; stack[stackSize-1].end = 0; } } } fprintf(fp, ";\n"); stack = myfree(stack, sizeof(stack_t)*NJ->maxnodes); } void PrintNJ(FILE *fp, NJ_t *NJ, char **names, uniquify_t *unique, bool bShowSupport, bool bQuote) { /* And print the tree: depth first search * The stack contains * list of remaining children with their depth * parent node, with a flag of -1 so I know to print right-paren */ if (NJ->nSeq==1 && unique->alnNext[unique->uniqueFirst[0]] >= 0) { /* Special case -- otherwise we end up with double parens */ int first = unique->uniqueFirst[0]; assert(first >= 0 && first < unique->nSeq); fprintf(fp, bQuote ? "('%s':0.0" : "(%s:0.0", names[first]); int iName = unique->alnNext[first]; while (iName >= 0) { assert(iName < unique->nSeq); fprintf(fp, bQuote ? ",'%s':0.0" : ",%s:0.0", names[iName]); iName = unique->alnNext[iName]; } fprintf(fp,");\n"); return; } typedef struct { int node; int end; } stack_t; stack_t *stack = (stack_t *)mymalloc(sizeof(stack_t)*NJ->maxnodes); int stackSize = 1; stack[0].node = NJ->root; stack[0].end = 0; while(stackSize>0) { stack_t *last = &stack[stackSize-1]; stackSize--; /* Save last, as we are about to overwrite it */ int node = last->node; int end = last->end; if (node < NJ->nSeq) { if (NJ->child[NJ->parent[node]].child[0] != node) fputs(",",fp); int first = unique->uniqueFirst[node]; assert(first >= 0 && first < unique->nSeq); /* Print the name, or the subtree of duplicate names */ if (unique->alnNext[first] == -1) { fprintf(fp, bQuote ? "'%s'" : "%s", names[first]); } else { fprintf(fp, bQuote ? "('%s':0.0" : "(%s:0.0", names[first]); int iName = unique->alnNext[first]; while (iName >= 0) { assert(iName < unique->nSeq); fprintf(fp, bQuote ? ",'%s':0.0" : ",%s:0.0", names[iName]); iName = unique->alnNext[iName]; } fprintf(fp,")"); } /* Print the branch length */ #ifdef USE_DOUBLE #define FP_FORMAT "%.9f" #else #define FP_FORMAT "%.5f" #endif fprintf(fp, ":" FP_FORMAT, NJ->branchlength[node]); } else if (end) { if (node == NJ->root) fprintf(fp, ")"); else if (bShowSupport) fprintf(fp, ")%.3f:" FP_FORMAT, NJ->support[node], NJ->branchlength[node]); else fprintf(fp, "):" FP_FORMAT, NJ->branchlength[node]); } else { if (node != NJ->root && NJ->child[NJ->parent[node]].child[0] != node) fprintf(fp, ","); fprintf(fp, "("); stackSize++; stack[stackSize-1].node = node; stack[stackSize-1].end = 1; children_t *c = &NJ->child[node]; /* put children on in reverse order because we use the last one first */ int i; for (i = c->nChild-1; i >=0; i--) { stackSize++; stack[stackSize-1].node = c->child[i]; stack[stackSize-1].end = 0; } } } fprintf(fp, ";\n"); stack = myfree(stack, sizeof(stack_t)*NJ->maxnodes); } alignment_t *ReadAlignment(/*IN*/FILE *fp, bool bQuote) { /* bQuote supports the -quote option */ int nSeq = 0; int nPos = 0; char **names = NULL; char **seqs = NULL; char buf[BUFFER_SIZE] = ""; if (fgets(buf,sizeof(buf),fp) == NULL) { fprintf(stderr, "Error reading header line\n"); exit(1); } int nSaved = 100; if (buf[0] == '>') { /* FASTA, truncate names at any of these */ char *nameStop = bQuote ? "'\t\r\n" : "(),: \t\r\n"; char *seqSkip = " \t\r\n"; /* skip these characters in the sequence */ seqs = (char**)mymalloc(sizeof(char*) * nSaved); names = (char**)mymalloc(sizeof(char*) * nSaved); do { /* loop over lines */ if (buf[0] == '>') { /* truncate the name */ char *p, *q; for (p = buf+1; *p != '\0'; p++) { for (q = nameStop; *q != '\0'; q++) { if (*p == *q) { *p = '\0'; break; } } if (*p == '\0') break; } /* allocate space for another sequence */ nSeq++; if (nSeq > nSaved) { int nNewSaved = nSaved*2; seqs = myrealloc(seqs,sizeof(char*)*nSaved,sizeof(char*)*nNewSaved, /*copy*/false); names = myrealloc(names,sizeof(char*)*nSaved,sizeof(char*)*nNewSaved, /*copy*/false); nSaved = nNewSaved; } names[nSeq-1] = (char*)mymemdup(buf+1,strlen(buf)); seqs[nSeq-1] = NULL; } else { /* count non-space characters and append to sequence */ int nKeep = 0; char *p, *q; for (p=buf; *p != '\0'; p++) { for (q=seqSkip; *q != '\0'; q++) { if (*p == *q) break; } if (*p != *q) nKeep++; } int nOld = (seqs[nSeq-1] == NULL) ? 0 : strlen(seqs[nSeq-1]); seqs[nSeq-1] = (char*)myrealloc(seqs[nSeq-1], nOld, nOld+nKeep+1, /*copy*/false); if (nOld+nKeep > nPos) nPos = nOld + nKeep; char *out = seqs[nSeq-1] + nOld; for (p=buf; *p != '\0'; p++) { for (q=seqSkip; *q != '\0'; q++) { if (*p == *q) break; } if (*p != *q) { *out = *p; out++; } } assert(out-seqs[nSeq-1] == nKeep + nOld); *out = '\0'; } } while(fgets(buf,sizeof(buf),fp) != NULL); if (seqs[nSeq-1] == NULL) { fprintf(stderr, "No sequence data for last entry %s\n",names[nSeq-1]); exit(1); } names = myrealloc(names,sizeof(char*)*nSaved,sizeof(char*)*nSeq, /*copy*/false); seqs = myrealloc(seqs,sizeof(char*)*nSaved,sizeof(char*)*nSeq, /*copy*/false); } else { /* PHYLIP interleaved-like format Allow arbitrary length names, require spaces between names and sequences Allow multiple alignments, either separated by a single empty line (e.g. seqboot output) or not. */ if (buf[0] == '\n' || buf[0] == '\r') { if (fgets(buf,sizeof(buf),fp) == NULL) { fprintf(stderr, "Empty header line followed by EOF\n"); exit(1); } } if (sscanf(buf, "%d%d", &nSeq, &nPos) != 2 || nSeq < 1 || nPos < 1) { fprintf(stderr, "Error parsing header line:%s\n", buf); exit(1); } names = (char **)mymalloc(sizeof(char*) * nSeq); seqs = (char **)mymalloc(sizeof(char*) * nSeq); nSaved = nSeq; int i; for (i = 0; i < nSeq; i++) { names[i] = NULL; seqs[i] = (char *)mymalloc(nPos+1); /* null-terminate */ seqs[i][0] = '\0'; } int iSeq = 0; while(fgets(buf,sizeof(buf),fp)) { if ((buf[0] == '\n' || buf[0] == '\r') && (iSeq == nSeq || iSeq == 0)) { iSeq = 0; } else { int j = 0; /* character just past end of name */ if (buf[0] == ' ') { if (names[iSeq] == NULL) { fprintf(stderr, "No name in phylip line %s", buf); exit(1); } } else { while (buf[j] != '\n' && buf[j] != '\0' && buf[j] != ' ') j++; if (buf[j] != ' ' || j == 0) { fprintf(stderr, "No sequence in phylip line %s", buf); exit(1); } if (iSeq >= nSeq) { fprintf(stderr, "No empty line between sequence blocks (is the sequence count wrong?)\n"); exit(1); } if (names[iSeq] == NULL) { /* save the name */ names[iSeq] = (char *)mymalloc(j+1); int k; for (k = 0; k < j; k++) names[iSeq][k] = buf[k]; names[iSeq][j] = '\0'; } else { /* check the name */ int k; int match = 1; for (k = 0; k < j; k++) { if (names[iSeq][k] != buf[k]) { match = 0; break; } } if (!match || names[iSeq][j] != '\0') { fprintf(stderr, "Wrong name in phylip line %s\nExpected %s\n", buf, names[iSeq]); exit(1); } } } int seqlen = strlen(seqs[iSeq]); for (; buf[j] != '\n' && buf[j] != '\0'; j++) { if (buf[j] != ' ') { if (seqlen >= nPos) { fprintf(stderr, "Too many characters (expected %d) for sequence named %s\nSo far have:\n%s\n", nPos, names[iSeq], seqs[iSeq]); exit(1); } seqs[iSeq][seqlen++] = toupper(buf[j]); } } seqs[iSeq][seqlen] = '\0'; /* null-terminate */ if(verbose>10) fprintf(stderr,"Read iSeq %d name %s seqsofar %s\n", iSeq, names[iSeq], seqs[iSeq]); iSeq++; if (iSeq == nSeq && strlen(seqs[0]) == nPos) break; /* finished alignment */ } /* end else non-empty phylip line */ } if (iSeq != nSeq && iSeq != 0) { fprintf(stderr, "Wrong number of sequences: expected %d\n", nSeq); exit(1); } } /* Check lengths of sequences */ int i; for (i = 0; i < nSeq; i++) { int seqlen = strlen(seqs[i]); if (seqlen != nPos) { fprintf(stderr, "Wrong number of characters for %s: expected %d but have %d instead.\n" "This sequence may be truncated, or another sequence may be too long.\n", names[i], nPos, seqlen); exit(1); } } /* Replace "." with "-" and warn if we find any */ /* If nucleotide sequences, replace U with T and N with X */ bool findDot = false; for (i = 0; i < nSeq; i++) { char *p; for (p = seqs[i]; *p != '\0'; p++) { if (*p == '.') { findDot = true; *p = '-'; } if (nCodes == 4 && *p == 'U') *p = 'T'; if (nCodes == 4 && *p == 'N') *p = 'X'; } } if (findDot) fprintf(stderr, "Warning! Found \".\" character(s). These are treated as gaps\n"); if (ferror(fp)) { fprintf(stderr, "Error reading input file\n"); exit(1); } alignment_t *align = (alignment_t*)mymalloc(sizeof(alignment_t)); align->nSeq = nSeq; align->nPos = nPos; align->names = names; align->seqs = seqs; align->nSaved = nSaved; return(align); } void FreeAlignmentSeqs(/*IN/OUT*/alignment_t *aln) { assert(aln != NULL); int i; for (i = 0; i < aln->nSeq; i++) aln->seqs[i] = myfree(aln->seqs[i], aln->nPos+1); } alignment_t *FreeAlignment(alignment_t *aln) { if(aln==NULL) return(NULL); int i; for (i = 0; i < aln->nSeq; i++) { aln->names[i] = myfree(aln->names[i],strlen(aln->names[i])+1); aln->seqs[i] = myfree(aln->seqs[i], aln->nPos+1); } aln->names = myfree(aln->names, sizeof(char*)*aln->nSaved); aln->seqs = myfree(aln->seqs, sizeof(char*)*aln->nSaved); myfree(aln, sizeof(alignment_t)); return(NULL); } char **AlnToConstraints(alignment_t *constraints, uniquify_t *unique, hashstrings_t *hashnames) { /* look up constraints as names and map to unique-space */ char ** uniqConstraints = (char**)mymalloc(sizeof(char*) * unique->nUnique); int i; for (i = 0; i < unique->nUnique; i++) uniqConstraints[i] = NULL; for (i = 0; i < constraints->nSeq; i++) { char *name = constraints->names[i]; char *constraintSeq = constraints->seqs[i]; hashiterator_t hi = FindMatch(hashnames,name); if (HashCount(hashnames,hi) != 1) { fprintf(stderr, "Sequence %s from constraints file is not in the alignment\n", name); exit(1); } int iSeqNonunique = HashFirst(hashnames,hi); assert(iSeqNonunique >= 0 && iSeqNonunique < unique->nSeq); int iSeqUnique = unique->alnToUniq[iSeqNonunique]; assert(iSeqUnique >= 0 && iSeqUnique < unique->nUnique); if (uniqConstraints[iSeqUnique] != NULL) { /* Already set a constraint for this group of sequences! Warn that we are ignoring this one unless the constraints match */ if (strcmp(uniqConstraints[iSeqUnique],constraintSeq) != 0) { fprintf(stderr, "Warning: ignoring constraints for %s:\n%s\n" "Another sequence has the same sequence but different constraints\n", name, constraintSeq); } } else { uniqConstraints[iSeqUnique] = constraintSeq; } } return(uniqConstraints); } profile_t *SeqToProfile(/*IN/OUT*/NJ_t *NJ, char *seq, int nPos, /*OPTIONAL*/char *constraintSeq, int nConstraints, int iNode, unsigned long counts[256]) { static unsigned char charToCode[256]; static int codeSet = 0; int c, i; if (!codeSet) { for (c = 0; c < 256; c++) { charToCode[c] = nCodes; } for (i = 0; codesString[i]; i++) { charToCode[codesString[i]] = i; charToCode[tolower(codesString[i])] = i; } charToCode['-'] = NOCODE; codeSet=1; } assert(strlen(seq) == nPos); profile_t *profile = NewProfile(nPos,nConstraints); for (i = 0; i < nPos; i++) { unsigned int character = (unsigned int) seq[i]; counts[character]++; c = charToCode[character]; if(verbose>10 && i < 2) fprintf(stderr,"pos %d char %c code %d\n", i, seq[i], c); /* treat unknowns as gaps */ if (c == nCodes || c == NOCODE) { profile->codes[i] = NOCODE; profile->weights[i] = 0.0; } else { profile->codes[i] = c; profile->weights[i] = 1.0; } } if (nConstraints > 0) { for (i = 0; i < nConstraints; i++) { profile->nOn[i] = 0; profile->nOff[i] = 0; } bool bWarn = false; if (constraintSeq != NULL) { assert(strlen(constraintSeq) == nConstraints); for (i = 0; i < nConstraints; i++) { if (constraintSeq[i] == '1') { profile->nOn[i] = 1; } else if (constraintSeq[i] == '0') { profile->nOff[i] = 1; } else if (constraintSeq[i] != '-') { if (!bWarn) { fprintf(stderr, "Constraint characters in unique sequence %d replaced with gap:", iNode+1); bWarn = true; } fprintf(stderr, " %c%d", constraintSeq[i], i+1); /* For the benefit of ConstraintSequencePenalty -- this is a bit of a hack, as this modifies the value read from the alignment */ constraintSeq[i] = '-'; } } if (bWarn) fprintf(stderr, "\n"); } } return profile; } void SeqDist(unsigned char *codes1, unsigned char *codes2, int nPos, distance_matrix_t *dmat, /*OUT*/besthit_t *hit) { double top = 0; /* summed over positions */ int nUse = 0; int i; if (dmat==NULL) { int nDiff = 0; for (i = 0; i < nPos; i++) { if (codes1[i] != NOCODE && codes2[i] != NOCODE) { nUse++; if (codes1[i] != codes2[i]) nDiff++; } } top = (double)nDiff; } else { for (i = 0; i < nPos; i++) { if (codes1[i] != NOCODE && codes2[i] != NOCODE) { nUse++; top += dmat->distances[(unsigned int)codes1[i]][(unsigned int)codes2[i]]; } } } hit->weight = (double)nUse; hit->dist = nUse > 0 ? top/(double)nUse : 1.0; seqOps++; } void CorrectedPairDistances(profile_t **profiles, int nProfiles, /*OPTIONAL*/distance_matrix_t *distance_matrix, int nPos, /*OUT*/double *distances) { assert(distances != NULL); assert(profiles != NULL); assert(nProfiles>1 && nProfiles <= 4); besthit_t hit[6]; int iHit,i,j; for (iHit=0, i=0; i < nProfiles; i++) { for (j=i+1; j < nProfiles; j++, iHit++) { ProfileDist(profiles[i],profiles[j],nPos,distance_matrix,/*OUT*/&hit[iHit]); distances[iHit] = hit[iHit].dist; } } if (pseudoWeight > 0) { /* Estimate the prior distance */ double dTop = 0; double dBottom = 0; for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++) { dTop += hit[iHit].dist * hit[iHit].weight; dBottom += hit[iHit].weight; } double prior = (dBottom > 0.01) ? dTop/dBottom : 3.0; for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++) distances[iHit] = (distances[iHit] * hit[iHit].weight + prior * pseudoWeight) / (hit[iHit].weight + pseudoWeight); } if (logdist) { for (iHit=0; iHit < (nProfiles*(nProfiles-1))/2; iHit++) distances[iHit] = LogCorrect(distances[iHit]); } } /* During the neighbor-joining phase, a join only violates our constraints if node1, node2, and other are all represented in the constraint and if one of the 3 is split and the other two do not agree */ int JoinConstraintPenalty(/*IN*/NJ_t *NJ, int node1, int node2) { if (NJ->nConstraints == 0) return(0.0); int penalty = 0; int iC; for (iC = 0; iC < NJ->nConstraints; iC++) penalty += JoinConstraintPenaltyPiece(NJ, node1, node2, iC); return(penalty); } int JoinConstraintPenaltyPiece(NJ_t *NJ, int node1, int node2, int iC) { profile_t *pOut = NJ->outprofile; profile_t *p1 = NJ->profiles[node1]; profile_t *p2 = NJ->profiles[node2]; int nOn1 = p1->nOn[iC]; int nOff1 = p1->nOff[iC]; int nOn2 = p2->nOn[iC]; int nOff2 = p2->nOff[iC]; int nOnOut = pOut->nOn[iC] - nOn1 - nOn2; int nOffOut = pOut->nOff[iC] - nOff1 - nOff2; if ((nOn1+nOff1) > 0 && (nOn2+nOff2) > 0 && (nOnOut+nOffOut) > 0) { /* code is -1 for split, 0 for off, 1 for on */ int code1 = (nOn1 > 0 && nOff1 > 0) ? -1 : (nOn1 > 0 ? 1 : 0); int code2 = (nOn2 > 0 && nOff2 > 0) ? -1 : (nOn2 > 0 ? 1 : 0); int code3 = (nOnOut > 0 && nOffOut) > 0 ? -1 : (nOnOut > 0 ? 1 : 0); int nSplit = (code1 == -1 ? 1 : 0) + (code2 == -1 ? 1 : 0) + (code3 == -1 ? 1 : 0); int nOn = (code1 == 1 ? 1 : 0) + (code2 == 1 ? 1 : 0) + (code3 == 1 ? 1 : 0); if (nSplit == 1 && nOn == 1) return(SplitConstraintPenalty(nOn1+nOn2, nOff1+nOff2, nOnOut, nOffOut)); } /* else */ return(0); } void QuartetConstraintPenalties(profile_t *profiles[4], int nConstraints, /*OUT*/double penalty[3]) { int i; for (i=0; i < 3; i++) penalty[i] = 0.0; if(nConstraints == 0) return; int iC; for (iC = 0; iC < nConstraints; iC++) { double part[3]; if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/part)) { for (i=0;i<3;i++) penalty[i] += part[i]; if (verbose>2 && (fabs(part[ABvsCD]-part[ACvsBD]) > 0.001 || fabs(part[ABvsCD]-part[ADvsBC]) > 0.001)) fprintf(stderr, "Constraint Penalties at %d: ABvsCD %.3f ACvsBD %.3f ADvsBC %.3f %d/%d %d/%d %d/%d %d/%d\n", iC, part[ABvsCD], part[ACvsBD], part[ADvsBC], profiles[0]->nOn[iC], profiles[0]->nOff[iC], profiles[1]->nOn[iC], profiles[1]->nOff[iC], profiles[2]->nOn[iC], profiles[2]->nOff[iC], profiles[3]->nOn[iC], profiles[3]->nOff[iC]); } } if (verbose>2) fprintf(stderr, "Total Constraint Penalties: ABvsCD %.3f ACvsBD %.3f ADvsBC %.3f\n", penalty[ABvsCD], penalty[ACvsBD], penalty[ADvsBC]); } double PairConstraintDistance(int nOn1, int nOff1, int nOn2, int nOff2) { double f1 = nOn1/(double)(nOn1+nOff1); double f2 = nOn2/(double)(nOn2+nOff2); /* 1 - f1 * f2 - (1-f1)*(1-f2) = 1 - f1 * f2 - 1 + f1 + f2 - f1 * f2 */ return(f1 + f2 - 2.0 * f1 * f2); } bool QuartetConstraintPenaltiesPiece(profile_t *profiles[4], int iC, /*OUT*/double piece[3]) { int nOn[4]; int nOff[4]; int i; int nSplit = 0; int nPlus = 0; int nMinus = 0; for (i=0; i < 4; i++) { nOn[i] = profiles[i]->nOn[iC]; nOff[i] = profiles[i]->nOff[iC]; if (nOn[i] + nOff[i] == 0) return(false); /* ignore */ else if (nOn[i] > 0 && nOff[i] > 0) nSplit++; else if (nOn[i] > 0) nPlus++; else nMinus++; } /* If just one of them is split or on the other side and the others all agree, also ignore */ if (nPlus >= 3 || nMinus >= 3) return(false); piece[ABvsCD] = constraintWeight * (PairConstraintDistance(nOn[0],nOff[0],nOn[1],nOff[1]) + PairConstraintDistance(nOn[2],nOff[2],nOn[3],nOff[3])); piece[ACvsBD] = constraintWeight * (PairConstraintDistance(nOn[0],nOff[0],nOn[2],nOff[2]) + PairConstraintDistance(nOn[1],nOff[1],nOn[3],nOff[3])); piece[ADvsBC] = constraintWeight * (PairConstraintDistance(nOn[0],nOff[0],nOn[3],nOff[3]) + PairConstraintDistance(nOn[2],nOff[2],nOn[1],nOff[1])); return(true); } /* Minimum number of constrained leaves that need to be moved to satisfy the constraint (or 0 if constraint is satisfied) Defining it this way should ensure that SPR moves that break constraints get a penalty */ int SplitConstraintPenalty(int nOn1, int nOff1, int nOn2, int nOff2) { return(nOn1 + nOff2 < nOn2 + nOff1 ? (nOn1 < nOff2 ? nOn1 : nOff2) : (nOn2 < nOff1 ? nOn2 : nOff1)); } bool SplitViolatesConstraint(profile_t *profiles[4], int iConstraint) { int i; int codes[4]; /* 0 for off, 1 for on, -1 for split (quit if not constrained at all) */ for (i = 0; i < 4; i++) { if (profiles[i]->nOn[iConstraint] + profiles[i]->nOff[iConstraint] == 0) return(false); else if (profiles[i]->nOn[iConstraint] > 0 && profiles[i]->nOff[iConstraint] == 0) codes[i] = 1; else if (profiles[i]->nOn[iConstraint] == 0 && profiles[i]->nOff[iConstraint] > 0) codes[i] = 0; else codes[i] = -1; } int n0 = 0; int n1 = 0; for (i = 0; i < 4; i++) { if (codes[i] == 0) n0++; else if (codes[i] == 1) n1++; } /* 3 on one side means no violation, even if other is code -1 otherwise must have code != -1 and agreement on the split */ if (n0 >= 3 || n1 >= 3) return(false); if (n0==2 && n1==2 && codes[0] == codes[1] && codes[2] == codes[3]) return(false); return(true); } double LogCorrect(double dist) { const double maxscore = 3.0; if (nCodes == 4 && !useMatrix) { /* Jukes-Cantor */ dist = dist < 0.74 ? -0.75*log(1.0 - dist * 4.0/3.0) : maxscore; } else { /* scoredist-like */ dist = dist < 0.99 ? -1.3*log(1.0 - dist) : maxscore; } return (dist < maxscore ? dist : maxscore); } /* A helper function -- f1 and f2 can be NULL if the corresponding code != NOCODE */ double ProfileDistPiece(unsigned int code1, unsigned int code2, numeric_t *f1, numeric_t *f2, /*OPTIONAL*/distance_matrix_t *dmat, /*OPTIONAL*/numeric_t *codeDist2) { if (dmat) { if (code1 != NOCODE && code2 != NOCODE) { /* code1 vs code2 */ return(dmat->distances[code1][code2]); } else if (codeDist2 != NULL && code1 != NOCODE) { /* code1 vs. codeDist2 */ return(codeDist2[code1]); } else { /* f1 vs f2 */ if (f1 == NULL) { if(code1 == NOCODE) return(10.0); f1 = &dmat->codeFreq[code1][0]; } if (f2 == NULL) { if(code2 == NOCODE) return(10.0); f2 = &dmat->codeFreq[code2][0]; } return(vector_multiply3_sum(f1,f2,dmat->eigenval,nCodes)); } } else { /* no matrix */ if (code1 != NOCODE) { if (code2 != NOCODE) { return(code1 == code2 ? 0.0 : 1.0); /* code1 vs code2 */ } else { if(f2 == NULL) return(10.0); return(1.0 - f2[code1]); /* code1 vs. f2 */ } } else { if (code2 != NOCODE) { if(f1 == NULL) return(10.0); return(1.0 - f1[code2]); /* f1 vs code2 */ } else { /* f1 vs. f2 */ if (f1 == NULL || f2 == NULL) return(10.0); double piece = 1.0; int k; for (k = 0; k < nCodes; k++) { piece -= f1[k] * f2[k]; } return(piece); } } } assert(0); } /* E.g. GET_FREQ(profile,iPos,iVector) Gets the next element of the vectors (and updates iVector), or returns NULL if we didn't store a vector */ #define GET_FREQ(P,I,IVECTOR) \ (P->weights[I] > 0 && P->codes[I] == NOCODE ? &P->vectors[nCodes*(IVECTOR++)] : NULL) void ProfileDist(profile_t *profile1, profile_t *profile2, int nPos, /*OPTIONAL*/distance_matrix_t *dmat, /*OUT*/besthit_t *hit) { double top = 0; double denom = 0; int iFreq1 = 0; int iFreq2 = 0; int i = 0; for (i = 0; i < nPos; i++) { numeric_t *f1 = GET_FREQ(profile1,i,/*IN/OUT*/iFreq1); numeric_t *f2 = GET_FREQ(profile2,i,/*IN/OUT*/iFreq2); if (profile1->weights[i] > 0 && profile2->weights[i] > 0) { double weight = profile1->weights[i] * profile2->weights[i]; denom += weight; double piece = ProfileDistPiece(profile1->codes[i],profile2->codes[i],f1,f2,dmat, profile2->codeDist ? &profile2->codeDist[i*nCodes] : NULL); top += weight * piece; } } assert(iFreq1 == profile1->nVectors); assert(iFreq2 == profile2->nVectors); hit->weight = denom > 0 ? denom : 0.01; /* 0.01 is an arbitrarily low value of weight (normally >>1) */ hit->dist = denom > 0 ? top/denom : 1; profileOps++; } /* This should not be called if the update weight is 0, as in that case code==NOCODE and in=NULL is possible, and then it will fail. */ void AddToFreq(/*IN/OUT*/numeric_t *fOut, double weight, unsigned int codeIn, /*OPTIONAL*/numeric_t *fIn, /*OPTIONAL*/distance_matrix_t *dmat) { assert(fOut != NULL); if (fIn != NULL) { vector_add_mult(fOut, fIn, weight, nCodes); } else if (dmat) { assert(codeIn != NOCODE); vector_add_mult(fOut, dmat->codeFreq[codeIn], weight, nCodes); } else { assert(codeIn != NOCODE); fOut[codeIn] += weight; } } void SetProfile(/*IN/OUT*/NJ_t *NJ, int node, double weight1) { children_t *c = &NJ->child[node]; assert(c->nChild == 2); assert(NJ->profiles[c->child[0]] != NULL); assert(NJ->profiles[c->child[1]] != NULL); if (NJ->profiles[node] != NULL) FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints); NJ->profiles[node] = AverageProfile(NJ->profiles[c->child[0]], NJ->profiles[c->child[1]], NJ->nPos, NJ->nConstraints, NJ->distance_matrix, weight1); } /* bionjWeight is the weight of the first sequence (between 0 and 1), or -1 to do the average. */ profile_t *AverageProfile(profile_t *profile1, profile_t *profile2, int nPos, int nConstraints, distance_matrix_t *dmat, double bionjWeight) { int i; if (bionjWeight < 0) { bionjWeight = 0.5; } /* First, set codes and weights and see how big vectors will be */ profile_t *out = NewProfile(nPos, nConstraints); for (i = 0; i < nPos; i++) { out->weights[i] = bionjWeight * profile1->weights[i] + (1-bionjWeight) * profile2->weights[i]; out->codes[i] = NOCODE; if (out->weights[i] > 0) { if (profile1->weights[i] > 0 && profile1->codes[i] != NOCODE && (profile2->weights[i] <= 0 || profile1->codes[i] == profile2->codes[i])) { out->codes[i] = profile1->codes[i]; } else if (profile1->weights[i] <= 0 && profile2->weights[i] > 0 && profile2->codes[i] != NOCODE) { out->codes[i] = profile2->codes[i]; } if (out->codes[i] == NOCODE) out->nVectors++; } } /* Allocate and set the vectors */ out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors); for (i = 0; i < nCodes * out->nVectors; i++) out->vectors[i] = 0; nProfileFreqAlloc += out->nVectors; nProfileFreqAvoid += nPos - out->nVectors; int iFreqOut = 0; int iFreq1 = 0; int iFreq2 = 0; for (i=0; i < nPos; i++) { numeric_t *f = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); numeric_t *f1 = GET_FREQ(profile1,i,/*IN/OUT*/iFreq1); numeric_t *f2 = GET_FREQ(profile2,i,/*IN/OUT*/iFreq2); if (f != NULL) { if (profile1->weights[i] > 0) AddToFreq(/*IN/OUT*/f, profile1->weights[i] * bionjWeight, profile1->codes[i], f1, dmat); if (profile2->weights[i] > 0) AddToFreq(/*IN/OUT*/f, profile2->weights[i] * (1.0-bionjWeight), profile2->codes[i], f2, dmat); NormalizeFreq(/*IN/OUT*/f, dmat); } /* end if computing f */ if (verbose > 10 && i < 5) { fprintf(stderr,"Average profiles: pos %d in-w1 %f in-w2 %f bionjWeight %f to weight %f code %d\n", i, profile1->weights[i], profile2->weights[i], bionjWeight, out->weights[i], out->codes[i]); if (f!= NULL) { int k; for (k = 0; k < nCodes; k++) fprintf(stderr, "\t%c:%f", codesString[k], f ? f[k] : -1.0); fprintf(stderr,"\n"); } } } /* end loop over positions */ assert(iFreq1 == profile1->nVectors); assert(iFreq2 == profile2->nVectors); assert(iFreqOut == out->nVectors); /* compute total constraints */ for (i = 0; i < nConstraints; i++) { out->nOn[i] = profile1->nOn[i] + profile2->nOn[i]; out->nOff[i] = profile1->nOff[i] + profile2->nOff[i]; } profileAvgOps++; return(out); } /* Make the (unrotated) frequencies sum to 1 Simply dividing by total_weight is not ideal because of roundoff error So compute total_freq instead */ void NormalizeFreq(/*IN/OUT*/numeric_t *freq, distance_matrix_t *dmat) { double total_freq = 0; int k; if (dmat != NULL) { /* The total frequency is dot_product(true_frequencies, 1) So we rotate the 1 vector by eigeninv (stored in eigentot) */ total_freq = vector_multiply_sum(freq, dmat->eigentot, nCodes); } else { for (k = 0; k < nCodes; k++) total_freq += freq[k]; } if (total_freq > fPostTotalTolerance) { numeric_t inverse_weight = 1.0/total_freq; vector_multiply_by(/*IN/OUT*/freq, inverse_weight, nCodes); } else { /* This can happen if we are in a very low-weight region, e.g. if a mostly-gap position gets weighted down repeatedly; just set them all to arbitrary but legal values */ if (dmat == NULL) { for (k = 0; k < nCodes; k++) freq[k] = 1.0/nCodes; } else { for (k = 0; k < nCodes; k++) freq[k] = dmat->codeFreq[0][k]; } } } /* OutProfile() computes the out-profile */ profile_t *OutProfile(profile_t **profiles, int nProfiles, int nPos, int nConstraints, distance_matrix_t *dmat) { int i; /* position */ int in; /* profile */ profile_t *out = NewProfile(nPos, nConstraints); double inweight = 1.0/(double)nProfiles; /* The maximal output weight is 1.0 */ /* First, set weights -- code is always NOCODE, prevent weight=0 */ for (i = 0; i < nPos; i++) { out->weights[i] = 0; for (in = 0; in < nProfiles; in++) out->weights[i] += profiles[in]->weights[i] * inweight; if (out->weights[i] <= 0) out->weights[i] = 1e-20; /* always store a vector */ out->nVectors++; out->codes[i] = NOCODE; /* outprofile is normally complicated */ } /* Initialize the frequencies to 0 */ out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors); for (i = 0; i < nCodes*out->nVectors; i++) out->vectors[i] = 0; /* Add up the weights, going through each sequence in turn */ for (in = 0; in < nProfiles; in++) { int iFreqOut = 0; int iFreqIn = 0; for (i = 0; i < nPos; i++) { numeric_t *fIn = GET_FREQ(profiles[in],i,/*IN/OUT*/iFreqIn); numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); if (profiles[in]->weights[i] > 0) AddToFreq(/*IN/OUT*/fOut, profiles[in]->weights[i], profiles[in]->codes[i], fIn, dmat); } assert(iFreqOut == out->nVectors); assert(iFreqIn == profiles[in]->nVectors); } /* And normalize the frequencies to sum to 1 */ int iFreqOut = 0; for (i = 0; i < nPos; i++) { numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); if (fOut) NormalizeFreq(/*IN/OUT*/fOut, dmat); } assert(iFreqOut == out->nVectors); if (verbose > 10) fprintf(stderr,"Average %d profiles\n", nProfiles); if(dmat) SetCodeDist(/*IN/OUT*/out, nPos, dmat); /* Compute constraints */ for (i = 0; i < nConstraints; i++) { out->nOn[i] = 0; out->nOff[i] = 0; for (in = 0; in < nProfiles; in++) { out->nOn[i] += profiles[in]->nOn[i]; out->nOff[i] += profiles[in]->nOff[i]; } } return(out); } void UpdateOutProfile(/*IN/OUT*/profile_t *out, profile_t *old1, profile_t *old2, profile_t *new, int nActiveOld, int nPos, int nConstraints, distance_matrix_t *dmat) { int i, k; int iFreqOut = 0; int iFreq1 = 0; int iFreq2 = 0; int iFreqNew = 0; assert(nActiveOld > 0); for (i = 0; i < nPos; i++) { numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); numeric_t *fOld1 = GET_FREQ(old1,i,/*IN/OUT*/iFreq1); numeric_t *fOld2 = GET_FREQ(old2,i,/*IN/OUT*/iFreq2); numeric_t *fNew = GET_FREQ(new,i,/*IN/OUT*/iFreqNew); assert(out->codes[i] == NOCODE && fOut != NULL); /* No no-vector optimization for outprofiles */ if (verbose > 3 && i < 3) { fprintf(stderr,"Updating out-profile position %d weight %f (mult %f)\n", i, out->weights[i], out->weights[i]*nActiveOld); } double originalMult = out->weights[i]*nActiveOld; double newMult = originalMult + new->weights[i] - old1->weights[i] - old2->weights[i]; out->weights[i] = newMult/(nActiveOld-1); if (out->weights[i] <= 0) out->weights[i] = 1e-20; /* always use the vector */ for (k = 0; k < nCodes; k++) fOut[k] *= originalMult; if (old1->weights[i] > 0) AddToFreq(/*IN/OUT*/fOut, -old1->weights[i], old1->codes[i], fOld1, dmat); if (old2->weights[i] > 0) AddToFreq(/*IN/OUT*/fOut, -old2->weights[i], old2->codes[i], fOld2, dmat); if (new->weights[i] > 0) AddToFreq(/*IN/OUT*/fOut, new->weights[i], new->codes[i], fNew, dmat); /* And renormalize */ NormalizeFreq(/*IN/OUT*/fOut, dmat); if (verbose > 2 && i < 3) { fprintf(stderr,"Updated out-profile position %d weight %f (mult %f)", i, out->weights[i], out->weights[i]*nActiveOld); if(out->weights[i] > 0) for (k=0;k<nCodes;k++) fprintf(stderr, " %c:%f", dmat?'?':codesString[k], fOut[k]); fprintf(stderr,"\n"); } } assert(iFreqOut == out->nVectors); assert(iFreq1 == old1->nVectors); assert(iFreq2 == old2->nVectors); assert(iFreqNew == new->nVectors); if(dmat) SetCodeDist(/*IN/OUT*/out,nPos,dmat); /* update constraints -- note in practice this should be a no-op */ for (i = 0; i < nConstraints; i++) { out->nOn[i] += new->nOn[i] - old1->nOn[i] - old2->nOn[i]; out->nOff[i] += new->nOff[i] - old1->nOff[i] - old2->nOff[i]; } } void SetCodeDist(/*IN/OUT*/profile_t *profile, int nPos, distance_matrix_t *dmat) { if (profile->codeDist == NULL) profile->codeDist = (numeric_t*)mymalloc(sizeof(numeric_t)*nPos*nCodes); int i; int iFreq = 0; for (i = 0; i < nPos; i++) { numeric_t *f = GET_FREQ(profile,i,/*IN/OUT*/iFreq); int k; for (k = 0; k < nCodes; k++) profile->codeDist[i*nCodes+k] = ProfileDistPiece(/*code1*/profile->codes[i], /*code2*/k, /*f1*/f, /*f2*/NULL, dmat, NULL); } assert(iFreq==profile->nVectors); } void SetBestHit(int node, NJ_t *NJ, int nActive, /*OUT*/besthit_t *bestjoin, /*OUT OPTIONAL*/besthit_t *allhits) { assert(NJ->parent[node] < 0); bestjoin->i = node; bestjoin->j = -1; bestjoin->dist = 1e20; bestjoin->criterion = 1e20; int j; besthit_t tmp; #ifdef OPENMP /* Note -- if we are already in a parallel region, this will be ignored */ #pragma omp parallel for schedule(dynamic, 50) #endif for (j = 0; j < NJ->maxnode; j++) { besthit_t *sv = allhits != NULL ? &allhits[j] : &tmp; sv->i = node; sv->j = j; if (NJ->parent[j] >= 0) { sv->i = -1; /* illegal/empty join */ sv->weight = 0.0; sv->criterion = sv->dist = 1e20; continue; } /* Note that we compute self-distances (allow j==node) because the top-hit heuristic expects self to be within its top hits, but we exclude those from the bestjoin that we return... */ SetDistCriterion(NJ, nActive, /*IN/OUT*/sv); if (sv->criterion < bestjoin->criterion && node != j) *bestjoin = *sv; } if (verbose>5) { fprintf(stderr, "SetBestHit %d %d %f %f\n", bestjoin->i, bestjoin->j, bestjoin->dist, bestjoin->criterion); } } void ReadMatrix(char *filename, /*OUT*/numeric_t codes[MAXCODES][MAXCODES], bool checkCodes) { char buf[BUFFER_SIZE] = ""; FILE *fp = fopen(filename, "r"); if (fp == NULL) { fprintf(stderr, "Cannot read %s\n",filename); exit(1); } if (fgets(buf,sizeof(buf),fp) == NULL) { fprintf(stderr, "Error reading header line for %s:\n%s\n", filename, buf); exit(1); } if (checkCodes) { int i; int iBufPos; for (iBufPos=0,i=0;i<nCodes;i++,iBufPos++) { if(buf[iBufPos] != codesString[i]) { fprintf(stderr,"Header line\n%s\nin file %s does not have expected code %c # %d in %s\n", buf, filename, codesString[i], i, codesString); exit(1); } iBufPos++; if(buf[iBufPos] != '\n' && buf[iBufPos] != '\r' && buf[iBufPos] != '\0' && buf[iBufPos] != '\t') { fprintf(stderr, "Header line in %s should be tab-delimited\n", filename); exit(1); } if (buf[iBufPos] == '\0' && i < nCodes-1) { fprintf(stderr, "Header line in %s ends prematurely\n",filename); exit(1); } } /* end loop over codes */ /* Should be at end, but allow \n because of potential DOS \r\n */ if(buf[iBufPos] != '\0' && buf[iBufPos] != '\n' && buf[iBufPos] != '\r') { fprintf(stderr, "Header line in %s has too many entries\n", filename); exit(1); } } int iLine; for (iLine = 0; iLine < nCodes; iLine++) { buf[0] = '\0'; if (fgets(buf,sizeof(buf),fp) == NULL) { fprintf(stderr, "Cannot read line %d from file %s\n", iLine+2, filename); exit(1); } char *field = strtok(buf,"\t\r\n"); field = strtok(NULL, "\t"); /* ignore first column */ int iColumn; for (iColumn = 0; iColumn < nCodes && field != NULL; iColumn++, field = strtok(NULL,"\t")) { if(sscanf(field,ScanNumericSpec,&codes[iLine][iColumn]) != 1) { fprintf(stderr,"Cannot parse field %s in file %s\n", field, filename); exit(1); } } } } void ReadVector(char *filename, /*OUT*/numeric_t codes[MAXCODES]) { FILE *fp = fopen(filename,"r"); if (fp == NULL) { fprintf(stderr, "Cannot read %s\n",filename); exit(1); } int i; for (i = 0; i < nCodes; i++) { if (fscanf(fp,ScanNumericSpec,&codes[i]) != 1) { fprintf(stderr,"Cannot read %d entry of %s\n",i+1,filename); exit(1); } } if (fclose(fp) != 0) { fprintf(stderr, "Error reading %s\n",filename); exit(1); } } distance_matrix_t *ReadDistanceMatrix(char *prefix) { char buffer[BUFFER_SIZE]; distance_matrix_t *dmat = (distance_matrix_t*)mymalloc(sizeof(distance_matrix_t)); if(strlen(prefix) > BUFFER_SIZE-20) { fprintf(stderr,"Filename %s too long\n", prefix); exit(1); } strcpy(buffer, prefix); strcat(buffer, ".distances"); ReadMatrix(buffer, /*OUT*/dmat->distances, /*checkCodes*/true); strcpy(buffer, prefix); strcat(buffer, ".inverses"); ReadMatrix(buffer, /*OUT*/dmat->eigeninv, /*checkCodes*/false); strcpy(buffer, prefix); strcat(buffer, ".eigenvalues"); ReadVector(buffer, /*OUT*/dmat->eigenval); if(verbose>1) fprintf(stderr, "Read distance matrix from %s\n",prefix); SetupDistanceMatrix(/*IN/OUT*/dmat); return(dmat); } void SetupDistanceMatrix(/*IN/OUT*/distance_matrix_t *dmat) { /* Check that the eigenvalues and eigen-inverse are consistent with the distance matrix and that the matrix is symmetric */ int i,j,k; for (i = 0; i < nCodes; i++) { for (j = 0; j < nCodes; j++) { if(fabs(dmat->distances[i][j]-dmat->distances[j][i]) > 1e-6) { fprintf(stderr,"Distance matrix not symmetric for %d,%d: %f vs %f\n", i+1,j+1, dmat->distances[i][j], dmat->distances[j][i]); exit(1); } double total = 0.0; for (k = 0; k < nCodes; k++) total += dmat->eigenval[k] * dmat->eigeninv[k][i] * dmat->eigeninv[k][j]; if(fabs(total - dmat->distances[i][j]) > 1e-6) { fprintf(stderr,"Distance matrix entry %d,%d should be %f but eigen-representation gives %f\n", i+1,j+1,dmat->distances[i][j],total); exit(1); } } } /* And compute eigentot */ for (k = 0; k < nCodes; k++) { dmat->eigentot[k] = 0.; int j; for (j = 0; j < nCodes; j++) dmat->eigentot[k] += dmat->eigeninv[k][j]; } /* And compute codeFreq */ int code; for(code = 0; code < nCodes; code++) { for (k = 0; k < nCodes; k++) { dmat->codeFreq[code][k] = dmat->eigeninv[k][code]; } } /* And gapFreq */ for(code = 0; code < nCodes; code++) { double gapFreq = 0.0; for (k = 0; k < nCodes; k++) gapFreq += dmat->codeFreq[k][code]; dmat->gapFreq[code] = gapFreq / nCodes; } if(verbose>10) fprintf(stderr, "Made codeFreq\n"); } nni_t ChooseNNI(profile_t *profiles[4], /*OPTIONAL*/distance_matrix_t *dmat, int nPos, int nConstraints, /*OUT*/double criteria[3]) { double d[6]; CorrectedPairDistances(profiles, 4, dmat, nPos, /*OUT*/d); double penalty[3]; /* indexed as nni_t */ QuartetConstraintPenalties(profiles, nConstraints, /*OUT*/penalty); criteria[ABvsCD] = d[qAB] + d[qCD] + penalty[ABvsCD]; criteria[ACvsBD] = d[qAC] + d[qBD] + penalty[ACvsBD]; criteria[ADvsBC] = d[qAD] + d[qBC] + penalty[ADvsBC]; nni_t choice = ABvsCD; if (criteria[ACvsBD] < criteria[ABvsCD] && criteria[ACvsBD] <= criteria[ADvsBC]) { choice = ACvsBD; } else if (criteria[ADvsBC] < criteria[ABvsCD] && criteria[ADvsBC] <= criteria[ACvsBD]) { choice = ADvsBC; } if (verbose > 1 && penalty[choice] > penalty[ABvsCD] + 1e-6) { fprintf(stderr, "Worsen constraint: from %.3f to %.3f distance %.3f to %.3f: ", penalty[ABvsCD], penalty[choice], criteria[ABvsCD], choice == ACvsBD ? criteria[ACvsBD] : criteria[ADvsBC]); int iC; for (iC = 0; iC < nConstraints; iC++) { double ppart[3]; if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/ppart)) { double old_penalty = ppart[ABvsCD]; double new_penalty = ppart[choice]; if (new_penalty > old_penalty + 1e-6) fprintf(stderr, " %d (%d/%d %d/%d %d/%d %d/%d)", iC, profiles[0]->nOn[iC], profiles[0]->nOff[iC], profiles[1]->nOn[iC], profiles[1]->nOff[iC], profiles[2]->nOn[iC], profiles[2]->nOff[iC], profiles[3]->nOn[iC], profiles[3]->nOff[iC]); } } fprintf(stderr,"\n"); } if (verbose > 3) fprintf(stderr, "NNI scores ABvsCD %.5f ACvsBD %.5f ADvsBC %.5f choice %s\n", criteria[ABvsCD], criteria[ACvsBD], criteria[ADvsBC], choice == ABvsCD ? "AB|CD" : (choice == ACvsBD ? "AC|BD" : "AD|BC")); return(choice); } profile_t *PosteriorProfile(profile_t *p1, profile_t *p2, double len1, double len2, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, int nPos, int nConstraints) { if (len1 < MLMinBranchLength) len1 = MLMinBranchLength; if (len2 < MLMinBranchLength) len2 = MLMinBranchLength; int i,j,k; profile_t *out = NewProfile(nPos, nConstraints); for (i = 0; i < nPos; i++) { out->codes[i] = NOCODE; out->weights[i] = 1.0; } out->nVectors = nPos; out->vectors = (numeric_t*)mymalloc(sizeof(numeric_t)*nCodes*out->nVectors); for (i = 0; i < nCodes * out->nVectors; i++) out->vectors[i] = 0; int iFreqOut = 0; int iFreq1 = 0; int iFreq2 = 0; numeric_t *expeigenRates1 = NULL, *expeigenRates2 = NULL; if (transmat != NULL) { expeigenRates1 = ExpEigenRates(len1, transmat, rates); expeigenRates2 = ExpEigenRates(len2, transmat, rates); } if (transmat == NULL) { /* Jukes-Cantor */ assert(nCodes == 4); double *PSame1 = PSameVector(len1, rates); double *PDiff1 = PDiffVector(PSame1, rates); double *PSame2 = PSameVector(len2, rates); double *PDiff2 = PDiffVector(PSame2, rates); numeric_t mix1[4], mix2[4]; for (i=0; i < nPos; i++) { int iRate = rates->ratecat[i]; double w1 = p1->weights[i]; double w2 = p2->weights[i]; int code1 = p1->codes[i]; int code2 = p2->codes[i]; numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1); numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2); /* First try to store a simple profile */ if (f1 == NULL && f2 == NULL) { if (code1 == NOCODE && code2 == NOCODE) { out->codes[i] = NOCODE; out->weights[i] = 0.0; continue; } else if (code1 == NOCODE) { /* Posterior(parent | character & gap, len1, len2) = Posterior(parent | character, len1) = PSame() for matching characters and 1-PSame() for the rest = (pSame - pDiff) * character + (1-(pSame-pDiff)) * gap */ out->codes[i] = code2; out->weights[i] = w2 * (PSame2[iRate] - PDiff2[iRate]); continue; } else if (code2 == NOCODE) { out->codes[i] = code1; out->weights[i] = w1 * (PSame1[iRate] - PDiff1[iRate]); continue; } else if (code1 == code2) { out->codes[i] = code1; double f12code = (w1*PSame1[iRate] + (1-w1)*0.25) * (w2*PSame2[iRate] + (1-w2)*0.25); double f12other = (w1*PDiff1[iRate] + (1-w1)*0.25) * (w2*PDiff2[iRate] + (1-w2)*0.25); /* posterior probability of code1/code2 after scaling */ double pcode = f12code/(f12code+3*f12other); /* Now f = w * (code ? 1 : 0) + (1-w) * 0.25, so to get pcode we need fcode = 1/4 + w1*3/4 or w = (f-1/4)*4/3 */ out->weights[i] = (pcode - 0.25) * 4.0/3.0; /* This can be zero because of numerical problems, I think */ if (out->weights[i] < 1e-6) { if (verbose > 1) fprintf(stderr, "Replaced weight %f with %f from w1 %f w2 %f PSame %f %f f12code %f f12other %f\n", out->weights[i], 1e-6, w1, w2, PSame1[iRate], PSame2[iRate], f12code, f12other); out->weights[i] = 1e-6; } continue; } } /* if we did not compute a simple profile, then do the full computation and store the full vector */ if (f1 == NULL) { for (j = 0; j < 4; j++) mix1[j] = (1-w1)*0.25; if(code1 != NOCODE) mix1[code1] += w1; f1 = mix1; } if (f2 == NULL) { for (j = 0; j < 4; j++) mix2[j] = (1-w2)*0.25; if(code2 != NOCODE) mix2[code2] += w2; f2 = mix2; } out->codes[i] = NOCODE; out->weights[i] = 1.0; numeric_t *f = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); double lkAB = 0; for (j = 0; j < 4; j++) { f[j] = (f1[j] * PSame1[iRate] + (1.0-f1[j]) * PDiff1[iRate]) * (f2[j] * PSame2[iRate] + (1.0-f2[j]) * PDiff2[iRate]); lkAB += f[j]; } double lkABInv = 1.0/lkAB; for (j = 0; j < 4; j++) f[j] *= lkABInv; } PSame1 = myfree(PSame1, sizeof(double) * rates->nRateCategories); PSame2 = myfree(PSame2, sizeof(double) * rates->nRateCategories); PDiff1 = myfree(PDiff1, sizeof(double) * rates->nRateCategories); PDiff2 = myfree(PDiff2, sizeof(double) * rates->nRateCategories); } else if (nCodes == 4) { /* matrix model on nucleotides */ numeric_t *fGap = &transmat->codeFreq[NOCODE][0]; numeric_t f1mix[4], f2mix[4]; for (i=0; i < nPos; i++) { if (p1->codes[i] == NOCODE && p2->codes[i] == NOCODE && p1->weights[i] == 0 && p2->weights[i] == 0) { /* aligning gap with gap -- just output a gap out->codes[i] is already set to NOCODE so need not set that */ out->weights[i] = 0; continue; } int iRate = rates->ratecat[i]; numeric_t *expeigen1 = &expeigenRates1[iRate*4]; numeric_t *expeigen2 = &expeigenRates2[iRate*4]; numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1); numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2); numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); assert(fOut != NULL); if (f1 == NULL) { f1 = &transmat->codeFreq[p1->codes[i]][0]; /* codeFreq includes an entry for NOCODE */ double w = p1->weights[i]; if (w > 0.0 && w < 1.0) { for (j = 0; j < 4; j++) f1mix[j] = w * f1[j] + (1.0-w) * fGap[j]; f1 = f1mix; } } if (f2 == NULL) { f2 = &transmat->codeFreq[p2->codes[i]][0]; double w = p2->weights[i]; if (w > 0.0 && w < 1.0) { for (j = 0; j < 4; j++) f2mix[j] = w * f2[j] + (1.0-w) * fGap[j]; f2 = f2mix; } } numeric_t fMult1[4] ALIGNED; /* rotated1 * expeigen1 */ numeric_t fMult2[4] ALIGNED; /* rotated2 * expeigen2 */ #if 0 /* SSE3 is slower */ vector_multiply(f1, expeigen1, 4, /*OUT*/fMult1); vector_multiply(f2, expeigen2, 4, /*OUT*/fMult2); #else for (j = 0; j < 4; j++) { fMult1[j] = f1[j]*expeigen1[j]; fMult2[j] = f2[j]*expeigen2[j]; } #endif numeric_t fPost[4] ALIGNED; /* in unrotated space */ for (j = 0; j < 4; j++) { #if 0 /* SSE3 is slower */ fPost[j] = vector_dot_product_rot(fMult1, fMult2, &transmat->codeFreq[j][0], 4) * transmat->statinv[j]; */ #else double out1 = 0; double out2 = 0; for (k = 0; k < 4; k++) { out1 += fMult1[k] * transmat->codeFreq[j][k]; out2 += fMult2[k] * transmat->codeFreq[j][k]; } fPost[j] = out1*out2*transmat->statinv[j]; #endif } double fPostTot = 0; for (j = 0; j < 4; j++) fPostTot += fPost[j]; assert(fPostTot > fPostTotalTolerance); double fPostInv = 1.0/fPostTot; #if 0 /* SSE3 is slower */ vector_multiply_by(fPost, fPostInv, 4); #else for (j = 0; j < 4; j++) fPost[j] *= fPostInv; #endif /* and finally, divide by stat again & rotate to give the new frequencies */ matrixt_by_vector4(transmat->eigeninvT, fPost, /*OUT*/fOut); } /* end loop over position i */ } else if (nCodes == 20) { /* matrix model on amino acids */ numeric_t *fGap = &transmat->codeFreq[NOCODE][0]; numeric_t f1mix[20] ALIGNED; numeric_t f2mix[20] ALIGNED; for (i=0; i < nPos; i++) { if (p1->codes[i] == NOCODE && p2->codes[i] == NOCODE && p1->weights[i] == 0 && p2->weights[i] == 0) { /* aligning gap with gap -- just output a gap out->codes[i] is already set to NOCODE so need not set that */ out->weights[i] = 0; continue; } int iRate = rates->ratecat[i]; numeric_t *expeigen1 = &expeigenRates1[iRate*20]; numeric_t *expeigen2 = &expeigenRates2[iRate*20]; numeric_t *f1 = GET_FREQ(p1,i,/*IN/OUT*/iFreq1); numeric_t *f2 = GET_FREQ(p2,i,/*IN/OUT*/iFreq2); numeric_t *fOut = GET_FREQ(out,i,/*IN/OUT*/iFreqOut); assert(fOut != NULL); if (f1 == NULL) { f1 = &transmat->codeFreq[p1->codes[i]][0]; /* codeFreq includes an entry for NOCODE */ double w = p1->weights[i]; if (w > 0.0 && w < 1.0) { for (j = 0; j < 20; j++) f1mix[j] = w * f1[j] + (1.0-w) * fGap[j]; f1 = f1mix; } } if (f2 == NULL) { f2 = &transmat->codeFreq[p2->codes[i]][0]; double w = p2->weights[i]; if (w > 0.0 && w < 1.0) { for (j = 0; j < 20; j++) f2mix[j] = w * f2[j] + (1.0-w) * fGap[j]; f2 = f2mix; } } numeric_t fMult1[20] ALIGNED; /* rotated1 * expeigen1 */ numeric_t fMult2[20] ALIGNED; /* rotated2 * expeigen2 */ vector_multiply(f1, expeigen1, 20, /*OUT*/fMult1); vector_multiply(f2, expeigen2, 20, /*OUT*/fMult2); numeric_t fPost[20] ALIGNED; /* in unrotated space */ for (j = 0; j < 20; j++) { numeric_t value = vector_dot_product_rot(fMult1, fMult2, &transmat->codeFreq[j][0], 20) * transmat->statinv[j]; /* Added this logic try to avoid rare numerical problems */ fPost[j] = value >= 0 ? value : 0; } double fPostTot = vector_sum(fPost, 20); assert(fPostTot > fPostTotalTolerance); double fPostInv = 1.0/fPostTot; vector_multiply_by(/*IN/OUT*/fPost, fPostInv, 20); int ch = -1; /* the dominant character, if any */ if (!exactML) { for (j = 0; j < 20; j++) { if (fPost[j] >= approxMLminf) { ch = j; break; } } } /* now, see if we can use the approximation fPost ~= (1 or 0) * w + nearP * (1-w) to avoid rotating */ double w = 0; if (ch >= 0) { w = (fPost[ch] - transmat->nearP[ch][ch]) / (1.0 - transmat->nearP[ch][ch]); for (j = 0; j < 20; j++) { if (j != ch) { double fRough = (1.0-w) * transmat->nearP[ch][j]; if (fRough < fPost[j] * approxMLminratio) { ch = -1; /* give up on the approximation */ break; } } } } if (ch >= 0) { nAAPosteriorRough++; double wInvStat = w * transmat->statinv[ch]; for (j = 0; j < 20; j++) fOut[j] = wInvStat * transmat->codeFreq[ch][j] + (1.0-w) * transmat->nearFreq[ch][j]; } else { /* and finally, divide by stat again & rotate to give the new frequencies */ nAAPosteriorExact++; for (j = 0; j < 20; j++) fOut[j] = vector_multiply_sum(fPost, &transmat->eigeninv[j][0], 20); } } /* end loop over position i */ } else { assert(0); /* illegal nCodes */ } if (transmat != NULL) { expeigenRates1 = myfree(expeigenRates1, sizeof(numeric_t) * rates->nRateCategories * nCodes); expeigenRates2 = myfree(expeigenRates2, sizeof(numeric_t) * rates->nRateCategories * nCodes); } /* Reallocate out->vectors to be the right size */ out->nVectors = iFreqOut; if (out->nVectors == 0) out->vectors = (numeric_t*)myfree(out->vectors, sizeof(numeric_t)*nCodes*nPos); else out->vectors = (numeric_t*)myrealloc(out->vectors, /*OLDSIZE*/sizeof(numeric_t)*nCodes*nPos, /*NEWSIZE*/sizeof(numeric_t)*nCodes*out->nVectors, /*copy*/true); /* try to save space */ nProfileFreqAlloc += out->nVectors; nProfileFreqAvoid += nPos - out->nVectors; /* compute total constraints */ for (i = 0; i < nConstraints; i++) { out->nOn[i] = p1->nOn[i] + p2->nOn[i]; out->nOff[i] = p1->nOff[i] + p2->nOff[i]; } nPosteriorCompute++; return(out); } double *PSameVector(double length, rates_t *rates) { double *pSame = mymalloc(sizeof(double) * rates->nRateCategories); int iRate; for (iRate = 0; iRate < rates->nRateCategories; iRate++) pSame[iRate] = 0.25 + 0.75 * exp((-4.0/3.0) * fabs(length*rates->rates[iRate])); return(pSame); } double *PDiffVector(double *pSame, rates_t *rates) { double *pDiff = mymalloc(sizeof(double) * rates->nRateCategories); int iRate; for (iRate = 0; iRate < rates->nRateCategories; iRate++) pDiff[iRate] = (1.0 - pSame[iRate])/3.0; return(pDiff); } numeric_t *ExpEigenRates(double length, transition_matrix_t *transmat, rates_t *rates) { numeric_t *expeigen = mymalloc(sizeof(numeric_t) * nCodes * rates->nRateCategories); int iRate, j; for (iRate = 0; iRate < rates->nRateCategories; iRate++) { for (j = 0; j < nCodes; j++) { double relLen = length * rates->rates[iRate]; /* very short branch lengths lead to numerical problems so prevent them */ if (relLen < MLMinRelBranchLength) relLen = MLMinRelBranchLength; expeigen[iRate*nCodes + j] = exp(relLen * transmat->eigenval[j]); } } return(expeigen); } double PairLogLk(profile_t *pA, profile_t *pB, double length, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*OPTIONAL IN/OUT*/double *site_likelihoods) { double lk = 1.0; double loglk = 0.0; /* stores underflow of lk during the loop over positions */ int i,j; assert(rates != NULL && rates->nRateCategories > 0); numeric_t *expeigenRates = NULL; if (transmat != NULL) expeigenRates = ExpEigenRates(length, transmat, rates); if (transmat == NULL) { /* Jukes-Cantor */ assert (nCodes == 4); double *pSame = PSameVector(length, rates); double *pDiff = PDiffVector(pSame, rates); int iFreqA = 0; int iFreqB = 0; for (i = 0; i < nPos; i++) { int iRate = rates->ratecat[i]; double wA = pA->weights[i]; double wB = pB->weights[i]; int codeA = pA->codes[i]; int codeB = pB->codes[i]; numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA); numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB); double lkAB = 0; if (fA == NULL && fB == NULL) { if (codeA == NOCODE) { /* A is all gaps */ /* gap to gap is sum(j) 0.25 * (0.25 * pSame + 0.75 * pDiff) = sum(i) 0.25*0.25 = 0.25 gap to any character gives the same result */ lkAB = 0.25; } else if (codeB == NOCODE) { /* B is all gaps */ lkAB = 0.25; } else if (codeA == codeB) { /* A and B match */ lkAB = pSame[iRate] * wA*wB + 0.25 * (1-wA*wB); } else { /* codeA != codeB */ lkAB = pDiff[iRate] * wA*wB + 0.25 * (1-wA*wB); } } else if (fA == NULL) { /* Compare codeA to profile of B */ if (codeA == NOCODE) lkAB = 0.25; else lkAB = wA * (pDiff[iRate] + fB[codeA] * (pSame[iRate]-pDiff[iRate])) + (1.0-wA) * 0.25; /* because lkAB = wA * P(codeA->B) + (1-wA) * 0.25 P(codeA -> B) = sum(j) P(B==j) * (j==codeA ? pSame : pDiff) = sum(j) P(B==j) * pDiff + = pDiff + P(B==codeA) * (pSame-pDiff) */ } else if (fB == NULL) { /* Compare codeB to profile of A */ if (codeB == NOCODE) lkAB = 0.25; else lkAB = wB * (pDiff[iRate] + fA[codeB] * (pSame[iRate]-pDiff[iRate])) + (1.0-wB) * 0.25; } else { /* both are full profiles */ for (j = 0; j < 4; j++) lkAB += fB[j] * (fA[j] * pSame[iRate] + (1-fA[j])* pDiff[iRate]); /* P(A|B) */ } assert(lkAB > 0); lk *= lkAB; while (lk < LkUnderflow) { lk *= LkUnderflowInv; loglk -= LogLkUnderflow; } if (site_likelihoods != NULL) site_likelihoods[i] *= lkAB; } pSame = myfree(pSame, sizeof(double) * rates->nRateCategories); pDiff = myfree(pDiff, sizeof(double) * rates->nRateCategories); } else if (nCodes == 4) { /* matrix model on nucleotides */ int iFreqA = 0; int iFreqB = 0; numeric_t fAmix[4], fBmix[4]; numeric_t *fGap = &transmat->codeFreq[NOCODE][0]; for (i = 0; i < nPos; i++) { int iRate = rates->ratecat[i]; numeric_t *expeigen = &expeigenRates[iRate*4]; double wA = pA->weights[i]; double wB = pB->weights[i]; if (wA == 0 && wB == 0 && pA->codes[i] == NOCODE && pB->codes[i] == NOCODE) { /* Likelihood of A vs B is 1, so nothing changes Do not need to advance iFreqA or iFreqB */ continue; } numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA); numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB); if (fA == NULL) fA = &transmat->codeFreq[pA->codes[i]][0]; if (wA > 0.0 && wA < 1.0) { for (j = 0; j < 4; j++) fAmix[j] = wA*fA[j] + (1.0-wA)*fGap[j]; fA = fAmix; } if (fB == NULL) fB = &transmat->codeFreq[pB->codes[i]][0]; if (wB > 0.0 && wB < 1.0) { for (j = 0; j < 4; j++) fBmix[j] = wB*fB[j] + (1.0-wB)*fGap[j]; fB = fBmix; } /* SSE3 instructions do not speed this step up: numeric_t lkAB = vector_multiply3_sum(expeigen, fA, fB); */ // dsp this is where check for <=0 was added in 2.1.1.LG double lkAB = 0; for (j = 0; j < 4; j++) lkAB += expeigen[j]*fA[j]*fB[j]; assert(lkAB > 0); if (site_likelihoods != NULL) site_likelihoods[i] *= lkAB; lk *= lkAB; while (lk < LkUnderflow) { lk *= LkUnderflowInv; loglk -= LogLkUnderflow; } while (lk > LkUnderflowInv) { lk *= LkUnderflow; loglk += LogLkUnderflow; } } } else if (nCodes == 20) { /* matrix model on amino acids */ int iFreqA = 0; int iFreqB = 0; numeric_t fAmix[20], fBmix[20]; numeric_t *fGap = &transmat->codeFreq[NOCODE][0]; for (i = 0; i < nPos; i++) { int iRate = rates->ratecat[i]; numeric_t *expeigen = &expeigenRates[iRate*20]; double wA = pA->weights[i]; double wB = pB->weights[i]; if (wA == 0 && wB == 0 && pA->codes[i] == NOCODE && pB->codes[i] == NOCODE) { /* Likelihood of A vs B is 1, so nothing changes Do not need to advance iFreqA or iFreqB */ continue; } numeric_t *fA = GET_FREQ(pA,i,/*IN/OUT*/iFreqA); numeric_t *fB = GET_FREQ(pB,i,/*IN/OUT*/iFreqB); if (fA == NULL) fA = &transmat->codeFreq[pA->codes[i]][0]; if (wA > 0.0 && wA < 1.0) { for (j = 0; j < 20; j++) fAmix[j] = wA*fA[j] + (1.0-wA)*fGap[j]; fA = fAmix; } if (fB == NULL) fB = &transmat->codeFreq[pB->codes[i]][0]; if (wB > 0.0 && wB < 1.0) { for (j = 0; j < 20; j++) fBmix[j] = wB*fB[j] + (1.0-wB)*fGap[j]; fB = fBmix; } numeric_t lkAB = vector_multiply3_sum(expeigen, fA, fB, 20); if (!(lkAB > 0)) { /* If this happens, it indicates a numerical problem that needs to be addressed elsewhere, so report all the details */ fprintf(stderr, "# FastTree.c::PairLogLk -- numerical problem!\n"); fprintf(stderr, "# This block is intended for loading into R\n"); fprintf(stderr, "lkAB = %.8g\n", lkAB); fprintf(stderr, "Branch_length= %.8g\nalignment_position=%d\nnCodes=%d\nrate_category=%d\nrate=%.8g\n", length, i, nCodes, iRate, rates->rates[iRate]); fprintf(stderr, "wA=%.8g\nwB=%.8g\n", wA, wB); fprintf(stderr, "codeA = %d\ncodeB = %d\n", pA->codes[i], pB->codes[i]); fprintf(stderr, "fA = c("); for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", fA[j]); fprintf(stderr,")\n"); fprintf(stderr, "fB = c("); for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", fB[j]); fprintf(stderr,")\n"); fprintf(stderr, "stat = c("); for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", transmat->stat[j]); fprintf(stderr,")\n"); fprintf(stderr, "eigenval = c("); for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", transmat->eigenval[j]); fprintf(stderr,")\n"); fprintf(stderr, "expeigen = c("); for (j = 0; j < nCodes; j++) fprintf(stderr, "%s %.8g", j==0?"":",", expeigen[j]); fprintf(stderr,")\n"); int k; fprintf(stderr, "codeFreq = c("); for (j = 0; j < nCodes; j++) for(k = 0; k < nCodes; k++) fprintf(stderr, "%s %.8g", j==0 && k==0?"":",", transmat->codeFreq[j][k]); fprintf(stderr,")\n"); fprintf(stderr, "eigeninv = c("); for (j = 0; j < nCodes; j++) for(k = 0; k < nCodes; k++) fprintf(stderr, "%s %.8g", j==0 && k==0?"":",", transmat->eigeninv[j][k]); fprintf(stderr,")\n"); fprintf(stderr, "# Transform into matrices and compute un-rotated vectors for profiles A and B\n"); fprintf(stderr, "codeFreq = matrix(codeFreq,nrow=20);\n"); fprintf(stderr, "eigeninv = matrix(eigeninv,nrow=20);\n"); fputs("unrotA = stat * (eigeninv %*% fA)\n", stderr); fputs("unrotB = stat * (eigeninv %*% fB)\n", stderr); fprintf(stderr,"# End of R block\n"); } assert(lkAB > 0); if (site_likelihoods != NULL) site_likelihoods[i] *= lkAB; lk *= lkAB; while (lk < LkUnderflow) { lk *= LkUnderflowInv; loglk -= LogLkUnderflow; } while (lk > LkUnderflowInv) { lk *= LkUnderflow; loglk += LogLkUnderflow; } } } else { assert(0); /* illegal nCodes */ } if (transmat != NULL) expeigenRates = myfree(expeigenRates, sizeof(numeric_t) * rates->nRateCategories * 20); loglk += log(lk); nLkCompute++; return(loglk); } double MLQuartetLogLk(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN*/double branch_lengths[5], /*OPTIONAL OUT*/double *site_likelihoods) { profile_t *pAB = PosteriorProfile(pA, pB, branch_lengths[0], branch_lengths[1], transmat, rates, nPos, /*nConstraints*/0); profile_t *pCD = PosteriorProfile(pC, pD, branch_lengths[2], branch_lengths[3], transmat, rates, nPos, /*nConstraints*/0); if (site_likelihoods != NULL) { int i; for (i = 0; i < nPos; i++) site_likelihoods[i] = 1.0; } /* Roughly, P(A,B,C,D) = P(A) P(B|A) P(D|C) P(AB | CD) */ double loglk = PairLogLk(pA, pB, branch_lengths[0]+branch_lengths[1], nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods) + PairLogLk(pC, pD, branch_lengths[2]+branch_lengths[3], nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods) + PairLogLk(pAB, pCD, branch_lengths[4], nPos, transmat, rates, /*OPTIONAL IN/OUT*/site_likelihoods); pAB = FreeProfile(pAB, nPos, /*nConstraints*/0); pCD = FreeProfile(pCD, nPos, /*nConstraints*/0); return(loglk); } double PairNegLogLk(double x, void *data) { quartet_opt_t *qo = (quartet_opt_t *)data; assert(qo != NULL); assert(qo->pair1 != NULL && qo->pair2 != NULL); qo->nEval++; double loglk = PairLogLk(qo->pair1, qo->pair2, x, qo->nPos, qo->transmat, qo->rates, /*site_lk*/NULL); assert(loglk < 1e100); if (verbose > 5) fprintf(stderr, "PairLogLk(%.4f) = %.4f\n", x, loglk); return(-loglk); } double MLQuartetOptimize(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN/OUT*/double branch_lengths[5], /*OPTIONAL OUT*/bool *pStarTest, /*OPTIONAL OUT*/double *site_likelihoods) { int j; double start_length[5]; for (j = 0; j < 5; j++) { start_length[j] = branch_lengths[j]; if (branch_lengths[j] < MLMinBranchLength) branch_lengths[j] = MLMinBranchLength; } quartet_opt_t qopt = { nPos, transmat, rates, /*nEval*/0, /*pair1*/NULL, /*pair2*/NULL }; double f2x, negloglk; if (pStarTest != NULL) *pStarTest = false; /* First optimize internal branch, then branch to A, B, C, D, in turn May use star test to quit after internal branch */ profile_t *pAB = PosteriorProfile(pA, pB, branch_lengths[LEN_A], branch_lengths[LEN_B], transmat, rates, nPos, /*nConstraints*/0); profile_t *pCD = PosteriorProfile(pC, pD, branch_lengths[LEN_C], branch_lengths[LEN_D], transmat, rates, nPos, /*nConstraints*/0); qopt.pair1 = pAB; qopt.pair2 = pCD; branch_lengths[LEN_I] = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/branch_lengths[LEN_I], /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); if (pStarTest != NULL) { assert(site_likelihoods == NULL); double loglkStar = -PairNegLogLk(MLMinBranchLength, &qopt); if (loglkStar < -negloglk - closeLogLkLimit) { *pStarTest = true; double off = PairLogLk(pA, pB, branch_lengths[LEN_A] + branch_lengths[LEN_B], qopt.nPos, qopt.transmat, qopt.rates, /*site_lk*/NULL) + PairLogLk(pC, pD, branch_lengths[LEN_C] + branch_lengths[LEN_D], qopt.nPos, qopt.transmat, qopt.rates, /*site_lk*/NULL); pAB = FreeProfile(pAB, nPos, /*nConstraints*/0); pCD = FreeProfile(pCD, nPos, /*nConstraints*/0); return (-negloglk + off); } } pAB = FreeProfile(pAB, nPos, /*nConstraints*/0); profile_t *pBCD = PosteriorProfile(pB, pCD, branch_lengths[LEN_B], branch_lengths[LEN_I], transmat, rates, nPos, /*nConstraints*/0); qopt.pair1 = pA; qopt.pair2 = pBCD; branch_lengths[LEN_A] = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/branch_lengths[LEN_A], /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); pBCD = FreeProfile(pBCD, nPos, /*nConstraints*/0); profile_t *pACD = PosteriorProfile(pA, pCD, branch_lengths[LEN_A], branch_lengths[LEN_I], transmat, rates, nPos, /*nConstraints*/0); qopt.pair1 = pB; qopt.pair2 = pACD; branch_lengths[LEN_B] = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/branch_lengths[LEN_B], /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); pACD = FreeProfile(pACD, nPos, /*nConstraints*/0); pCD = FreeProfile(pCD, nPos, /*nConstraints*/0); pAB = PosteriorProfile(pA, pB, branch_lengths[LEN_A], branch_lengths[LEN_B], transmat, rates, nPos, /*nConstraints*/0); profile_t *pABD = PosteriorProfile(pAB, pD, branch_lengths[LEN_I], branch_lengths[LEN_D], transmat, rates, nPos, /*nConstraints*/0); qopt.pair1 = pC; qopt.pair2 = pABD; branch_lengths[LEN_C] = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/branch_lengths[LEN_C], /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); pABD = FreeProfile(pABD, nPos, /*nConstraints*/0); profile_t *pABC = PosteriorProfile(pAB, pC, branch_lengths[LEN_I], branch_lengths[LEN_C], transmat, rates, nPos, /*nConstraints*/0); qopt.pair1 = pD; qopt.pair2 = pABC; branch_lengths[LEN_D] = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/branch_lengths[LEN_D], /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); /* Compute the total quartet likelihood PairLogLk(ABC,D) + PairLogLk(AB,C) + PairLogLk(A,B) */ double loglkABCvsD = -negloglk; if (site_likelihoods) { for (j = 0; j < nPos; j++) site_likelihoods[j] = 1.0; PairLogLk(pABC, pD, branch_lengths[LEN_D], qopt.nPos, qopt.transmat, qopt.rates, /*IN/OUT*/site_likelihoods); } double quartetloglk = loglkABCvsD + PairLogLk(pAB, pC, branch_lengths[LEN_I] + branch_lengths[LEN_C], qopt.nPos, qopt.transmat, qopt.rates, /*IN/OUT*/site_likelihoods) + PairLogLk(pA, pB, branch_lengths[LEN_A] + branch_lengths[LEN_B], qopt.nPos, qopt.transmat, qopt.rates, /*IN/OUT*/site_likelihoods); pABC = FreeProfile(pABC, nPos, /*nConstraints*/0); pAB = FreeProfile(pAB, nPos, /*nConstraints*/0); if (verbose > 3) { double loglkStart = MLQuartetLogLk(pA, pB, pC, pD, nPos, transmat, rates, start_length, /*site_lk*/NULL); fprintf(stderr, "Optimize loglk from %.5f to %.5f eval %d lengths from\n" " %.5f %.5f %.5f %.5f %.5f to\n" " %.5f %.5f %.5f %.5f %.5f\n", loglkStart, quartetloglk, qopt.nEval, start_length[0], start_length[1], start_length[2], start_length[3], start_length[4], branch_lengths[0], branch_lengths[1], branch_lengths[2], branch_lengths[3], branch_lengths[4]); } return(quartetloglk); } nni_t MLQuartetNNI(profile_t *profiles[4], /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, int nPos, int nConstraints, /*OUT*/double criteria[3], /* The three potential quartet log-likelihoods */ /*IN/OUT*/numeric_t len[5], bool bFast) { int i; double lenABvsCD[5] = {len[LEN_A], len[LEN_B], len[LEN_C], len[LEN_D], len[LEN_I]}; double lenACvsBD[5] = {len[LEN_A], len[LEN_C], len[LEN_B], len[LEN_D], len[LEN_I]}; /* Swap B & C */ double lenADvsBC[5] = {len[LEN_A], len[LEN_D], len[LEN_C], len[LEN_B], len[LEN_I]}; /* Swap B & D */ bool bConsiderAC = true; bool bConsiderAD = true; int iRound; int nRounds = mlAccuracy < 2 ? 2 : mlAccuracy; double penalty[3]; QuartetConstraintPenalties(profiles, nConstraints, /*OUT*/penalty); if (penalty[ABvsCD] > penalty[ACvsBD] || penalty[ABvsCD] > penalty[ADvsBC]) bFast = false; #ifdef OPENMP bFast = false; /* turn off star topology test */ #endif for (iRound = 0; iRound < nRounds; iRound++) { bool bStarTest = false; { #ifdef OPENMP #pragma omp parallel #pragma omp sections #endif { #ifdef OPENMP #pragma omp section #endif { criteria[ABvsCD] = MLQuartetOptimize(profiles[0], profiles[1], profiles[2], profiles[3], nPos, transmat, rates, /*IN/OUT*/lenABvsCD, bFast ? &bStarTest : NULL, /*site_likelihoods*/NULL) - penalty[ABvsCD]; /* subtract penalty b/c we are trying to maximize log lk */ } #ifdef OPENMP #pragma omp section #else if (bStarTest) { nStarTests++; criteria[ACvsBD] = -1e20; criteria[ADvsBC] = -1e20; len[LEN_I] = lenABvsCD[LEN_I]; return(ABvsCD); } #endif { if (bConsiderAC) criteria[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3], nPos, transmat, rates, /*IN/OUT*/lenACvsBD, NULL, /*site_likelihoods*/NULL) - penalty[ACvsBD]; } #ifdef OPENMP #pragma omp section #endif { if (bConsiderAD) criteria[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1], nPos, transmat, rates, /*IN/OUT*/lenADvsBC, NULL, /*site_likelihoods*/NULL) - penalty[ADvsBC]; } } } /* end parallel sections */ if (mlAccuracy < 2) { /* If clearly worse then ABvsCD, or have short internal branch length and worse, then give up */ if (criteria[ACvsBD] < criteria[ABvsCD] - closeLogLkLimit || (lenACvsBD[LEN_I] <= 2.0*MLMinBranchLength && criteria[ACvsBD] < criteria[ABvsCD])) bConsiderAC = false; if (criteria[ADvsBC] < criteria[ABvsCD] - closeLogLkLimit || (lenADvsBC[LEN_I] <= 2.0*MLMinBranchLength && criteria[ADvsBC] < criteria[ABvsCD])) bConsiderAD = false; if (!bConsiderAC && !bConsiderAD) break; /* If clearly better than either alternative, then give up (Comparison is probably biased in favor of ABvsCD anyway) */ if (criteria[ACvsBD] > criteria[ABvsCD] + closeLogLkLimit && criteria[ACvsBD] > criteria[ADvsBC] + closeLogLkLimit) break; if (criteria[ADvsBC] > criteria[ABvsCD] + closeLogLkLimit && criteria[ADvsBC] > criteria[ACvsBD] + closeLogLkLimit) break; } } /* end loop over rounds */ if (verbose > 2) { fprintf(stderr, "Optimized quartet for %d rounds: ABvsCD %.5f ACvsBD %.5f ADvsBC %.5f\n", iRound, criteria[ABvsCD], criteria[ACvsBD], criteria[ADvsBC]); } if (criteria[ACvsBD] > criteria[ABvsCD] && criteria[ACvsBD] > criteria[ADvsBC]) { for (i = 0; i < 5; i++) len[i] = lenACvsBD[i]; return(ACvsBD); } else if (criteria[ADvsBC] > criteria[ABvsCD] && criteria[ADvsBC] > criteria[ACvsBD]) { for (i = 0; i < 5; i++) len[i] = lenADvsBC[i]; return(ADvsBC); } else { for (i = 0; i < 5; i++) len[i] = lenABvsCD[i]; return(ABvsCD); } } double TreeLength(/*IN/OUT*/NJ_t *NJ, bool recomputeProfiles) { if (recomputeProfiles) { traversal_t traversal2 = InitTraversal(NJ); int j = NJ->root; while((j = TraversePostorder(j, NJ, /*IN/OUT*/traversal2, /*pUp*/NULL)) >= 0) { /* nothing to do for leaves or root */ if (j >= NJ->nSeq && j != NJ->root) SetProfile(/*IN/OUT*/NJ, j, /*noweight*/-1.0); } traversal2 = FreeTraversal(traversal2,NJ); } UpdateBranchLengths(/*IN/OUT*/NJ); double total_len = 0; int iNode; for (iNode = 0; iNode < NJ->maxnode; iNode++) total_len += NJ->branchlength[iNode]; return(total_len); } double TreeLogLk(/*IN*/NJ_t *NJ, /*OPTIONAL OUT*/double *site_loglk) { int i; if (NJ->nSeq < 2) return(0.0); double loglk = 0.0; double *site_likelihood = NULL; if (site_loglk != NULL) { site_likelihood = mymalloc(sizeof(double)*NJ->nPos); for (i = 0; i < NJ->nPos; i++) { site_likelihood[i] = 1.0; site_loglk[i] = 0.0; } } traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { int nChild = NJ->child[node].nChild; if (nChild == 0) continue; assert(nChild >= 2); int *children = NJ->child[node].child; double loglkchild = PairLogLk(NJ->profiles[children[0]], NJ->profiles[children[1]], NJ->branchlength[children[0]]+NJ->branchlength[children[1]], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/site_likelihood); loglk += loglkchild; if (site_likelihood != NULL) { /* prevent underflows */ for (i = 0; i < NJ->nPos; i++) { while(site_likelihood[i] < LkUnderflow) { site_likelihood[i] *= LkUnderflowInv; site_loglk[i] -= LogLkUnderflow; } } } if (verbose > 2) fprintf(stderr, "At %d: LogLk(%d:%.4f,%d:%.4f) = %.3f\n", node, children[0], NJ->branchlength[children[0]], children[1], NJ->branchlength[children[1]], loglkchild); if (NJ->child[node].nChild == 3) { assert(node == NJ->root); /* Infer the common parent of the 1st two to define the third... */ profile_t *pAB = PosteriorProfile(NJ->profiles[children[0]], NJ->profiles[children[1]], NJ->branchlength[children[0]], NJ->branchlength[children[1]], NJ->transmat, &NJ->rates, NJ->nPos, /*nConstraints*/0); double loglkup = PairLogLk(pAB, NJ->profiles[children[2]], NJ->branchlength[children[2]], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/site_likelihood); loglk += loglkup; if (verbose > 2) fprintf(stderr, "At root %d: LogLk((%d/%d),%d:%.3f) = %.3f\n", node, children[0], children[1], children[2], NJ->branchlength[children[2]], loglkup); pAB = FreeProfile(pAB, NJ->nPos, NJ->nConstraints); } } traversal = FreeTraversal(traversal,NJ); if (site_likelihood != NULL) { for (i = 0; i < NJ->nPos; i++) { site_loglk[i] += log(site_likelihood[i]); } site_likelihood = myfree(site_likelihood, sizeof(double)*NJ->nPos); } /* For Jukes-Cantor, with a tree of size 4, if the children of the root are (A,B), C, and D, then P(ABCD) = P(A) P(B|A) P(C|AB) P(D|ABC) Above we compute P(B|A) P(C|AB) P(D|ABC) -- note P(B|A) is at the child of root and P(C|AB) P(D|ABC) is at root. Similarly if the children of the root are C, D, and (A,B), then P(ABCD) = P(C|D) P(A|B) P(AB|CD) P(D), and above we compute that except for P(D) So we need to multiply by P(A) = 0.25, so we pay log(4) at each position (if ungapped). Each gapped position in any sequence reduces the payment by log(4) For JTT or GTR, we are computing P(A & B) and the posterior profiles are scaled to take the prior into account, so we do not need any correction. codeFreq[NOCODE] is scaled x higher so that P(-) = 1 not P(-)=1/nCodes, so gaps do not need to be corrected either. */ if (nCodes == 4 && NJ->transmat == NULL) { int nGaps = 0; double logNCodes = log((double)nCodes); for (i = 0; i < NJ->nPos; i++) { int nGapsThisPos = 0; for (node = 0; node < NJ->nSeq; node++) { unsigned char *codes = NJ->profiles[node]->codes; if (codes[i] == NOCODE) nGapsThisPos++; } nGaps += nGapsThisPos; if (site_loglk != NULL) { site_loglk[i] += nGapsThisPos * logNCodes; if (nCodes == 4 && NJ->transmat == NULL) site_loglk[i] -= logNCodes; } } loglk -= NJ->nPos * logNCodes; loglk += nGaps * logNCodes; /* do not pay for gaps -- only Jukes-Cantor */ } return(loglk); } void SetMLGtr(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL IN*/double *freq_in, /*OPTIONAL WRITE*/FILE *fpLog) { int i; assert(nCodes==4); gtr_opt_t gtr; gtr.NJ = NJ; gtr.fpLog = fpLog; if (freq_in != NULL) { for (i=0; i<4; i++) gtr.freq[i]=freq_in[i]; } else { /* n[] and sum were int in FastTree 2.1.9 and earlier -- this caused gtr analyses to fail on analyses with >2e9 positions */ long n[4] = {1,1,1,1}; /* pseudocounts */ for (i=0; i<NJ->nSeq; i++) { unsigned char *codes = NJ->profiles[i]->codes; int iPos; for (iPos=0; iPos<NJ->nPos; iPos++) if (codes[iPos] < 4) n[codes[iPos]]++; } long sum = n[0]+n[1]+n[2]+n[3]; for (i=0; i<4; i++) gtr.freq[i] = n[i]/(double)sum; } for (i=0; i<6; i++) gtr.rates[i] = 1.0; int nRounds = mlAccuracy < 2 ? 2 : mlAccuracy; for (i = 0; i < nRounds; i++) { for (gtr.iRate = 0; gtr.iRate < 6; gtr.iRate++) { ProgressReport("Optimizing GTR model, step %d of %d", i*6+gtr.iRate+1, 12, 0, 0); double negloglk, f2x; gtr.rates[gtr.iRate] = onedimenmin(/*xmin*/0.05, /*xguess*/gtr.rates[gtr.iRate], /*xmax*/20.0, GTRNegLogLk, /*data*/&gtr, /*ftol*/0.001, /*atol*/0.0001, /*OUT*/&negloglk, /*OUT*/&f2x); } } /* normalize gtr so last rate is 1 -- specifying that rate separately is useful for optimization only */ for (i = 0; i < 5; i++) gtr.rates[i] /= gtr.rates[5]; gtr.rates[5] = 1.0; if (verbose) { fprintf(stderr, "GTR Frequencies: %.4f %.4f %.4f %.4f\n", gtr.freq[0], gtr.freq[1], gtr.freq[2], gtr.freq[3]); fprintf(stderr, "GTR rates(ac ag at cg ct gt) %.4f %.4f %.4f %.4f %.4f %.4f\n", gtr.rates[0],gtr.rates[1],gtr.rates[2],gtr.rates[3],gtr.rates[4],gtr.rates[5]); } if (fpLog != NULL) { fprintf(fpLog, "GTRFreq\t%.4f\t%.4f\t%.4f\t%.4f\n", gtr.freq[0], gtr.freq[1], gtr.freq[2], gtr.freq[3]); fprintf(fpLog, "GTRRates\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\t%.4f\n", gtr.rates[0],gtr.rates[1],gtr.rates[2],gtr.rates[3],gtr.rates[4],gtr.rates[5]); } myfree(NJ->transmat, sizeof(transition_matrix_t)); NJ->transmat = CreateGTR(gtr.rates, gtr.freq); RecomputeMLProfiles(/*IN/OUT*/NJ); OptimizeAllBranchLengths(/*IN/OUT*/NJ); } double GTRNegLogLk(double x, void *data) { gtr_opt_t *gtr = (gtr_opt_t*)data; assert(nCodes == 4); assert(gtr->NJ != NULL); assert(gtr->iRate >= 0 && gtr->iRate < 6); assert(x > 0); transition_matrix_t *old = gtr->NJ->transmat; double rates[6]; int i; for (i = 0; i < 6; i++) rates[i] = gtr->rates[i]; rates[gtr->iRate] = x; FILE *fpLog = gtr->fpLog; if (fpLog) fprintf(fpLog, "GTR_Opt\tfreq %.5f %.5f %.5f %.5f rates %.5f %.5f %.5f %.5f %.5f %.5f\n", gtr->freq[0], gtr->freq[1], gtr->freq[2], gtr->freq[3], rates[0], rates[1], rates[2], rates[3], rates[4], rates[5]); gtr->NJ->transmat = CreateGTR(rates, gtr->freq); RecomputeMLProfiles(/*IN/OUT*/gtr->NJ); double loglk = TreeLogLk(gtr->NJ, /*site_loglk*/NULL); myfree(gtr->NJ->transmat, sizeof(transition_matrix_t)); gtr->NJ->transmat = old; /* Do not recompute profiles -- assume the caller will do that */ if (verbose > 2) fprintf(stderr, "GTR LogLk(%.5f %.5f %.5f %.5f %.5f %.5f) = %f\n", rates[0], rates[1], rates[2], rates[3], rates[4], rates[5], loglk); if (fpLog) fprintf(fpLog, "GTR_Opt\tGTR LogLk(%.5f %.5f %.5f %.5f %.5f %.5f) = %f\n", rates[0], rates[1], rates[2], rates[3], rates[4], rates[5], loglk); return(-loglk); } /* Caller must free the resulting vector of n rates */ numeric_t *MLSiteRates(int nRateCategories) { /* Even spacing from 1/nRate to nRate */ double logNCat = log((double)nRateCategories); double logMinRate = -logNCat; double logMaxRate = logNCat; double logd = (logMaxRate-logMinRate)/(double)(nRateCategories-1); numeric_t *rates = mymalloc(sizeof(numeric_t)*nRateCategories); int i; for (i = 0; i < nRateCategories; i++) rates[i] = exp(logMinRate + logd*(double)i); return(rates); } double *MLSiteLikelihoodsByRate(/*IN*/NJ_t *NJ, /*IN*/numeric_t *rates, int nRateCategories) { double *site_loglk = mymalloc(sizeof(double)*NJ->nPos*nRateCategories); /* save the original rates */ assert(NJ->rates.nRateCategories > 0); numeric_t *oldRates = NJ->rates.rates; NJ->rates.rates = mymalloc(sizeof(numeric_t) * NJ->rates.nRateCategories); /* Compute site likelihood for each rate */ int iPos; int iRate; for (iRate = 0; iRate < nRateCategories; iRate++) { int i; for (i = 0; i < NJ->rates.nRateCategories; i++) NJ->rates.rates[i] = rates[iRate]; RecomputeMLProfiles(/*IN/OUT*/NJ); double loglk = TreeLogLk(NJ, /*OUT*/&site_loglk[NJ->nPos*iRate]); ProgressReport("Site likelihoods with rate category %d of %d", iRate+1, nRateCategories, 0, 0); if(verbose > 2) { fprintf(stderr, "Rate %.3f Loglk %.3f SiteLogLk", rates[iRate], loglk); for (iPos = 0; iPos < NJ->nPos; iPos++) fprintf(stderr,"\t%.3f", site_loglk[NJ->nPos*iRate + iPos]); fprintf(stderr,"\n"); } } /* restore original rates and profiles */ myfree(NJ->rates.rates, sizeof(numeric_t) * NJ->rates.nRateCategories); NJ->rates.rates = oldRates; RecomputeMLProfiles(/*IN/OUT*/NJ); return(site_loglk); } void SetMLRates(/*IN/OUT*/NJ_t *NJ, int nRateCategories) { assert(nRateCategories > 0); AllocRateCategories(/*IN/OUT*/&NJ->rates, 1, NJ->nPos); /* set to 1 category of rate 1 */ if (nRateCategories == 1) { RecomputeMLProfiles(/*IN/OUT*/NJ); return; } numeric_t *rates = MLSiteRates(nRateCategories); double *site_loglk = MLSiteLikelihoodsByRate(/*IN*/NJ, /*IN*/rates, nRateCategories); /* Select best rate for each site, correcting for the prior For a prior, use a gamma distribution with shape parameter 3, scale 1/3, so Prior(rate) ~ rate**2 * exp(-3*rate) log Prior(rate) = C + 2 * log(rate) - 3 * rate */ double sumRates = 0; int iPos; int iRate; for (iPos = 0; iPos < NJ->nPos; iPos++) { int iBest = -1; double dBest = -1e20; for (iRate = 0; iRate < nRateCategories; iRate++) { double site_loglk_with_prior = site_loglk[NJ->nPos*iRate + iPos] + 2.0 * log(rates[iRate]) - 3.0 * rates[iRate]; if (site_loglk_with_prior > dBest) { iBest = iRate; dBest = site_loglk_with_prior; } } if (verbose > 2) fprintf(stderr, "Selected rate category %d rate %.3f for position %d\n", iBest, rates[iBest], iPos+1); NJ->rates.ratecat[iPos] = iBest; sumRates += rates[iBest]; } site_loglk = myfree(site_loglk, sizeof(double)*NJ->nPos*nRateCategories); /* Force the rates to average to 1 */ double avgRate = sumRates/NJ->nPos; for (iRate = 0; iRate < nRateCategories; iRate++) rates[iRate] /= avgRate; /* Save the rates */ NJ->rates.rates = myfree(NJ->rates.rates, sizeof(numeric_t) * NJ->rates.nRateCategories); NJ->rates.rates = rates; NJ->rates.nRateCategories = nRateCategories; /* Update profiles based on rates */ RecomputeMLProfiles(/*IN/OUT*/NJ); if (verbose) { fprintf(stderr, "Switched to using %d rate categories (CAT approximation)\n", nRateCategories); fprintf(stderr, "Rate categories were divided by %.3f so that average rate = 1.0\n", avgRate); fprintf(stderr, "CAT-based log-likelihoods may not be comparable across runs\n"); if (!gammaLogLk) fprintf(stderr, "Use -gamma for approximate but comparable Gamma(20) log-likelihoods\n"); } } double GammaLogLk(/*IN*/siteratelk_t *s, /*OPTIONAL OUT*/double *gamma_loglk_sites) { int iRate, iPos; double *dRate = mymalloc(sizeof(double) * s->nRateCats); for (iRate = 0; iRate < s->nRateCats; iRate++) { /* The probability density for each rate is approximated by the total density between the midpoints */ double pMin = iRate == 0 ? 0.0 : PGamma(s->mult * (s->rates[iRate-1] + s->rates[iRate])/2.0, s->alpha); double pMax = iRate == s->nRateCats-1 ? 1.0 : PGamma(s->mult * (s->rates[iRate]+s->rates[iRate+1])/2.0, s->alpha); dRate[iRate] = pMax-pMin; } double loglk = 0.0; for (iPos = 0; iPos < s->nPos; iPos++) { /* Prevent underflow on large trees by comparing to maximum loglk */ double maxloglk = -1e20; for (iRate = 0; iRate < s->nRateCats; iRate++) { double site_loglk = s->site_loglk[s->nPos*iRate + iPos]; if (site_loglk > maxloglk) maxloglk = site_loglk; } double rellk = 0; /* likelihood scaled by exp(maxloglk) */ for (iRate = 0; iRate < s->nRateCats; iRate++) { double lk = exp(s->site_loglk[s->nPos*iRate + iPos] - maxloglk); rellk += lk * dRate[iRate]; } double loglk_site = maxloglk + log(rellk); loglk += loglk_site; if (gamma_loglk_sites != NULL) gamma_loglk_sites[iPos] = loglk_site; } dRate = myfree(dRate, sizeof(double)*s->nRateCats); return(loglk); } double OptAlpha(double alpha, void *data) { siteratelk_t *s = (siteratelk_t *)data; s->alpha = alpha; return(-GammaLogLk(s, NULL)); } double OptMult(double mult, void *data) { siteratelk_t *s = (siteratelk_t *)data; s->mult = mult; return(-GammaLogLk(s, NULL)); } /* Input site_loglk must be for each rate */ double RescaleGammaLogLk(int nPos, int nRateCats, /*IN*/numeric_t *rates, /*IN*/double *site_loglk, /*OPTIONAL*/FILE *fpLog) { siteratelk_t s = { /*mult*/1.0, /*alpha*/1.0, nPos, nRateCats, rates, site_loglk }; double fx, f2x; int i; fx = -GammaLogLk(&s, NULL); if (verbose>2) fprintf(stderr, "Optimizing alpha, starting at loglk %.3f\n", -fx); for (i = 0; i < 10; i++) { ProgressReport("Optimizing alpha round %d", i+1, 0, 0, 0); double start = fx; s.alpha = onedimenmin(0.01, s.alpha, 10.0, OptAlpha, &s, 0.001, 0.001, &fx, &f2x); if (verbose>2) fprintf(stderr, "Optimize alpha round %d to %.3f lk %.3f\n", i+1, s.alpha, -fx); s.mult = onedimenmin(0.01, s.mult, 10.0, OptMult, &s, 0.001, 0.001, &fx, &f2x); if (verbose>2) fprintf(stderr, "Optimize mult round %d to %.3f lk %.3f\n", i+1, s.mult, -fx); if (fx > start - 0.001) { if (verbose>2) fprintf(stderr, "Optimizing alpha & mult converged\n"); break; } } double *gamma_loglk_sites = mymalloc(sizeof(double) * nPos); double gammaLogLk = GammaLogLk(&s, /*OUT*/gamma_loglk_sites); if (verbose > 0) fprintf(stderr, "Gamma(%d) LogLk = %.3f alpha = %.3f rescaling lengths by %.3f\n", nRateCats, gammaLogLk, s.alpha, 1/s.mult); if (fpLog) { int iPos; int iRate; fprintf(fpLog, "Gamma%dLogLk\t%.3f\tApproximate\tAlpha\t%.3f\tRescale\t%.3f\n", nRateCats, gammaLogLk, s.alpha, 1/s.mult); fprintf(fpLog, "Gamma%d\tSite\tLogLk", nRateCats); for (iRate = 0; iRate < nRateCats; iRate++) fprintf(fpLog, "\tr=%.3f", rates[iRate]/s.mult); fprintf(fpLog,"\n"); for (iPos = 0; iPos < nPos; iPos++) { fprintf(fpLog, "Gamma%d\t%d\t%.3f", nRateCats, iPos, gamma_loglk_sites[iPos]); for (iRate = 0; iRate < nRateCats; iRate++) fprintf(fpLog, "\t%.3f", site_loglk[nPos*iRate + iPos]); fprintf(fpLog,"\n"); } } gamma_loglk_sites = myfree(gamma_loglk_sites, sizeof(double) * nPos); return(1.0/s.mult); } double MLPairOptimize(profile_t *pA, profile_t *pB, int nPos, /*OPTIONAL*/transition_matrix_t *transmat, rates_t *rates, /*IN/OUT*/double *branch_length) { quartet_opt_t qopt = { nPos, transmat, rates, /*nEval*/0, /*pair1*/pA, /*pair2*/pB }; double f2x,negloglk; *branch_length = onedimenmin(/*xmin*/MLMinBranchLength, /*xguess*/*branch_length, /*xmax*/6.0, PairNegLogLk, /*data*/&qopt, /*ftol*/MLFTolBranchLength, /*atol*/MLMinBranchLengthTolerance, /*OUT*/&negloglk, /*OUT*/&f2x); return(-negloglk); /* the log likelihood */ } void OptimizeAllBranchLengths(/*IN/OUT*/NJ_t *NJ) { if (NJ->nSeq < 2) return; if (NJ->nSeq == 2) { int parent = NJ->root; assert(NJ->child[parent].nChild==2); int nodes[2] = { NJ->child[parent].child[0], NJ->child[parent].child[1] }; double length = 1.0; (void)MLPairOptimize(NJ->profiles[nodes[0]], NJ->profiles[nodes[1]], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/&length); NJ->branchlength[nodes[0]] = length/2.0; NJ->branchlength[nodes[1]] = length/2.0; return; }; traversal_t traversal = InitTraversal(NJ); profile_t **upProfiles = UpProfiles(NJ); int node = NJ->root; int iDone = 0; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { int nChild = NJ->child[node].nChild; if (nChild > 0) { if ((iDone % 100) == 0) ProgressReport("ML Lengths %d of %d splits", iDone+1, NJ->maxnode - NJ->nSeq, 0, 0); iDone++; /* optimize the branch lengths between self, parent, and children, with two iterations */ assert(nChild == 2 || nChild == 3); int nodes[3] = { NJ->child[node].child[0], NJ->child[node].child[1], nChild == 3 ? NJ->child[node].child[2] : node }; profile_t *profiles[3] = { NJ->profiles[nodes[0]], NJ->profiles[nodes[1]], nChild == 3 ? NJ->profiles[nodes[2]] : GetUpProfile(/*IN/OUT*/upProfiles, NJ, node, /*useML*/true) }; int iter; for (iter = 0; iter < 2; iter++) { int i; for (i = 0; i < 3; i++) { profile_t *pA = profiles[i]; int b1 = (i+1) % 3; int b2 = (i+2) % 3; profile_t *pB = PosteriorProfile(profiles[b1], profiles[b2], NJ->branchlength[nodes[b1]], NJ->branchlength[nodes[b2]], NJ->transmat, &NJ->rates, NJ->nPos, /*nConstraints*/0); double len = NJ->branchlength[nodes[i]]; if (len < MLMinBranchLength) len = MLMinBranchLength; (void)MLPairOptimize(pA, pB, NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/&len); NJ->branchlength[nodes[i]] = len; pB = FreeProfile(pB, NJ->nPos, /*nConstraints*/0); if (verbose>3) fprintf(stderr, "Optimize length for %d to %.3f\n", nodes[i], NJ->branchlength[nodes[i]]); } } if (node != NJ->root) { RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, /*useML*/true); DeleteUpProfile(upProfiles, NJ, node); } } } traversal = FreeTraversal(traversal,NJ); upProfiles = FreeUpProfiles(upProfiles,NJ); } void RecomputeMLProfiles(/*IN/OUT*/NJ_t *NJ) { traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (NJ->child[node].nChild == 2) { NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints); int *children = NJ->child[node].child; NJ->profiles[node] = PosteriorProfile(NJ->profiles[children[0]], NJ->profiles[children[1]], NJ->branchlength[children[0]], NJ->branchlength[children[1]], NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints); } } traversal = FreeTraversal(traversal, NJ); } void RecomputeProfiles(/*IN/OUT*/NJ_t *NJ, /*OPTIONAL*/distance_matrix_t *dmat) { traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (NJ->child[node].nChild == 2) { int *child = NJ->child[node].child; NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints); NJ->profiles[node] = AverageProfile(NJ->profiles[child[0]], NJ->profiles[child[1]], NJ->nPos, NJ->nConstraints, dmat, /*unweighted*/-1.0); } } traversal = FreeTraversal(traversal,NJ); } int NNI(/*IN/OUT*/NJ_t *NJ, int iRound, int nRounds, bool useML, /*IN/OUT*/nni_stats_t *stats, /*OUT*/double *dMaxDelta) { /* For each non-root node N, with children A,B, sibling C, and uncle D, we compare the current topology AB|CD to the alternate topologies AC|BD and AD|BC, by using the 4 relevant profiles. If useML is true, it uses quartet maximum likelihood, and it updates branch lengths as it goes. If useML is false, it uses the minimum-evolution criterion with log-corrected distances on profiles. (If logdist is false, then the log correction is not done.) If useML is false, then NNI() does NOT modify the branch lengths. Regardless of whether it changes the topology, it recomputes the profile for the node, using the pairwise distances and BIONJ-like weightings (if bionj is set). The parent's profile has changed, but recomputing it is not necessary because we will visit it before we need it (we use postorder, so we may visit the sibling and its children before we visit the parent, but we never consider an ancestor's profile, so that is OK). When we change the parent's profile, this alters the uncle's up-profile, so we remove that. Finally, if the topology has changed, we remove the up-profiles of the nodes. If we do an NNI during post-order traversal, the result is a bit tricky. E.g. if we are at node N, and have visited its children A and B but not its uncle C, and we do an NNI that swaps B & C, then the post-order traversal will visit C, and its children, but then on the way back up, it will skip N, as it has already visited it. So, the profile of N will not be recomputed: any changes beneath C will not be reflected in the profile of N, and the profile of N will be slightly stale. This will be corrected on the next round of NNIs. */ double supportThreshold = useML ? treeLogLkDelta : MEMinDelta; int i; *dMaxDelta = 0.0; int nNNIThisRound = 0; if (NJ->nSeq <= 3) return(0); /* nothing to do */ if (verbose > 2) { fprintf(stderr, "Beginning round %d of NNIs with ml? %d\n", iRound, useML?1:0); PrintNJInternal(/*WRITE*/stderr, NJ, /*useLen*/useML && iRound > 0 ? 1 : 0); } /* For each node the upProfile or NULL */ profile_t **upProfiles = UpProfiles(NJ); traversal_t traversal = InitTraversal(NJ); /* Identify nodes we can skip traversing into */ int node; if (fastNNI) { for (node = 0; node < NJ->maxnode; node++) { if (node != NJ->root && node >= NJ->nSeq && stats[node].age >= 2 && stats[node].subtreeAge >= 2 && stats[node].support > supportThreshold) { int nodeABCD[4]; SetupABCD(NJ, node, NULL, NULL, /*OUT*/nodeABCD, useML); for (i = 0; i < 4; i++) if (stats[nodeABCD[i]].age == 0 && stats[nodeABCD[i]].support > supportThreshold) break; if (i == 4) { SkipTraversalInto(node, /*IN/OUT*/traversal); if (verbose > 2) fprintf(stderr, "Skipping subtree at %d: child %d %d parent %d age %d subtreeAge %d support %.3f\n", node, nodeABCD[0], nodeABCD[1], NJ->parent[node], stats[node].age, stats[node].subtreeAge, stats[node].support); } } } } int iDone = 0; bool bUp; node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, &bUp)) >= 0) { if (node < NJ->nSeq || node == NJ->root) continue; /* nothing to do for leaves or root */ if (bUp) { if(verbose > 2) fprintf(stderr, "Going up back to node %d\n", node); /* No longer needed */ for (i = 0; i < NJ->child[node].nChild; i++) DeleteUpProfile(upProfiles, NJ, NJ->child[node].child[i]); DeleteUpProfile(upProfiles, NJ, node); RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, useML); continue; } if ((iDone % 100) == 0) { char buf[100]; sprintf(buf, "%s NNI round %%d of %%d, %%d of %%d splits", useML ? "ML" : "ME"); if (iDone > 0) sprintf(buf+strlen(buf), ", %d changes", nNNIThisRound); if (nNNIThisRound > 0) sprintf(buf+strlen(buf), " (max delta %.3f)", *dMaxDelta); ProgressReport(buf, iRound+1, nRounds, iDone+1, NJ->maxnode - NJ->nSeq); } iDone++; profile_t *profiles[4]; int nodeABCD[4]; /* Note -- during the first round of ML NNIs, we use the min-evo-based branch lengths, which may be suboptimal */ SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML); /* Given our 4 profiles, consider doing a swap */ int nodeA = nodeABCD[0]; int nodeB = nodeABCD[1]; int nodeC = nodeABCD[2]; int nodeD = nodeABCD[3]; nni_t choice = ABvsCD; if (verbose > 2) fprintf(stderr,"Considering NNI around %d: Swap A=%d B=%d C=%d D=up(%d) or parent %d\n", node, nodeA, nodeB, nodeC, nodeD, NJ->parent[node]); if (verbose > 3 && useML) { double len[5] = { NJ->branchlength[nodeA], NJ->branchlength[nodeB], NJ->branchlength[nodeC], NJ->branchlength[nodeD], NJ->branchlength[node] }; for (i=0; i < 5; i++) if (len[i] < MLMinBranchLength) len[i] = MLMinBranchLength; fprintf(stderr, "Starting quartet likelihood %.3f len %.3f %.3f %.3f %.3f %.3f\n", MLQuartetLogLk(profiles[0],profiles[1],profiles[2],profiles[3],NJ->nPos,NJ->transmat,&NJ->rates,len, /*site_lk*/NULL), len[0], len[1], len[2], len[3], len[4]); } numeric_t newlength[5]; double criteria[3]; if (useML) { for (i = 0; i < 4; i++) newlength[i] = NJ->branchlength[nodeABCD[i]]; newlength[4] = NJ->branchlength[node]; bool bFast = mlAccuracy < 2 && stats[node].age > 0; choice = MLQuartetNNI(profiles, NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints, /*OUT*/criteria, /*IN/OUT*/newlength, bFast); } else { choice = ChooseNNI(profiles, NJ->distance_matrix, NJ->nPos, NJ->nConstraints, /*OUT*/criteria); /* invert criteria so that higher is better, as in ML case, to simplify code below */ for (i = 0; i < 3; i++) criteria[i] = -criteria[i]; } if (choice == ACvsBD) { /* swap B and C */ ReplaceChild(/*IN/OUT*/NJ, node, nodeB, nodeC); ReplaceChild(/*IN/OUT*/NJ, NJ->parent[node], nodeC, nodeB); } else if (choice == ADvsBC) { /* swap A and C */ ReplaceChild(/*IN/OUT*/NJ, node, nodeA, nodeC); ReplaceChild(/*IN/OUT*/NJ, NJ->parent[node], nodeC, nodeA); } if (useML) { /* update branch length for the internal branch, and of any branches that lead to leaves, b/c those will not are not the internal branch for NNI and would not otherwise be set. */ if (choice == ADvsBC) { /* For ADvsBC, MLQuartetNNI swaps B with D, but we swap A with C */ double length2[5] = { newlength[LEN_C], newlength[LEN_D], newlength[LEN_A], newlength[LEN_B], newlength[LEN_I] }; int i; for (i = 0; i < 5; i++) newlength[i] = length2[i]; /* and swap A and C */ double tmp = newlength[LEN_A]; newlength[LEN_A] = newlength[LEN_C]; newlength[LEN_C] = tmp; } else if (choice == ACvsBD) { /* swap B and C */ double tmp = newlength[LEN_B]; newlength[LEN_B] = newlength[LEN_C]; newlength[LEN_C] = tmp; } NJ->branchlength[node] = newlength[LEN_I]; NJ->branchlength[nodeA] = newlength[LEN_A]; NJ->branchlength[nodeB] = newlength[LEN_B]; NJ->branchlength[nodeC] = newlength[LEN_C]; NJ->branchlength[nodeD] = newlength[LEN_D]; } if (verbose>2 && (choice != ABvsCD || verbose > 2)) fprintf(stderr,"NNI around %d: Swap A=%d B=%d C=%d D=out(C) -- choose %s %s %.4f\n", node, nodeA, nodeB, nodeC, choice == ACvsBD ? "AC|BD" : (choice == ABvsCD ? "AB|CD" : "AD|BC"), useML ? "delta-loglk" : "-deltaLen", criteria[choice] - criteria[ABvsCD]); if(verbose >= 3 && slow && useML) fprintf(stderr, "Old tree lk -- %.4f\n", TreeLogLk(NJ, /*site_likelihoods*/NULL)); /* update stats, *dMaxDelta, etc. */ if (choice == ABvsCD) { stats[node].age++; } else { if (useML) nML_NNI++; else nNNI++; nNNIThisRound++; stats[node].age = 0; stats[nodeA].age = 0; stats[nodeB].age = 0; stats[nodeC].age = 0; stats[nodeD].age = 0; } stats[node].delta = criteria[choice] - criteria[ABvsCD]; /* 0 if ABvsCD */ if (stats[node].delta > *dMaxDelta) *dMaxDelta = stats[node].delta; /* support is improvement of score for self over better of alternatives */ stats[node].support = 1e20; for (i = 0; i < 3; i++) if (choice != i && criteria[choice]-criteria[i] < stats[node].support) stats[node].support = criteria[choice]-criteria[i]; /* subtreeAge is the number of rounds since self or descendent had a significant improvement */ if (stats[node].delta > supportThreshold) stats[node].subtreeAge = 0; else { stats[node].subtreeAge++; for (i = 0; i < 2; i++) { int child = NJ->child[node].child[i]; if (stats[node].subtreeAge > stats[child].subtreeAge) stats[node].subtreeAge = stats[child].subtreeAge; } } /* update profiles and free up unneeded up-profiles */ if (choice == ABvsCD) { /* No longer needed */ DeleteUpProfile(upProfiles, NJ, nodeA); DeleteUpProfile(upProfiles, NJ, nodeB); DeleteUpProfile(upProfiles, NJ, nodeC); RecomputeProfile(/*IN/OUT*/NJ, /*IN/OUT*/upProfiles, node, useML); if(slow && useML) UpdateForNNI(NJ, node, upProfiles, useML); } else { UpdateForNNI(NJ, node, upProfiles, useML); } if(verbose > 2 && slow && useML) { /* Note we recomputed profiles back up to root already if slow */ PrintNJInternal(/*WRITE*/stderr, NJ, /*useLen*/true); fprintf(stderr, "New tree lk -- %.4f\n", TreeLogLk(NJ, /*site_likelihoods*/NULL)); } } /* end postorder traversal */ traversal = FreeTraversal(traversal,NJ); if (verbose>=2) { int nUp = 0; for (i = 0; i < NJ->maxnodes; i++) if (upProfiles[i] != NULL) nUp++; fprintf(stderr, "N up profiles at end of NNI: %d\n", nUp); } upProfiles = FreeUpProfiles(upProfiles,NJ); return(nNNIThisRound); } nni_stats_t *InitNNIStats(NJ_t *NJ) { nni_stats_t *stats = mymalloc(sizeof(nni_stats_t)*NJ->maxnode); const int LargeAge = 1000000; int i; for (i = 0; i < NJ->maxnode; i++) { stats[i].delta = 0; stats[i].support = 0; if (i == NJ->root || i < NJ->nSeq) { stats[i].age = LargeAge; stats[i].subtreeAge = LargeAge; } else { stats[i].age = 0; stats[i].subtreeAge = 0; } } return(stats); } nni_stats_t *FreeNNIStats(nni_stats_t *stats, NJ_t *NJ) { return(myfree(stats, sizeof(nni_stats_t)*NJ->maxnode)); } int FindSPRSteps(/*IN/OUT*/NJ_t *NJ, int nodeMove, /* the node to move multiple times */ int nodeAround, /* sibling or parent of node to NNI to start the chain */ /*IN/OUT*/profile_t **upProfiles, /*OUT*/spr_step_t *steps, int maxSteps, bool bFirstAC) { int iStep; for (iStep = 0; iStep < maxSteps; iStep++) { if (NJ->child[nodeAround].nChild != 2) break; /* no further to go */ /* Consider the NNIs around nodeAround */ profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, nodeAround, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false); double criteria[3]; (void) ChooseNNI(profiles, NJ->distance_matrix, NJ->nPos, NJ->nConstraints, /*OUT*/criteria); /* Do & save the swap */ spr_step_t *step = &steps[iStep]; if (iStep == 0 ? bFirstAC : criteria[ACvsBD] < criteria[ADvsBC]) { /* swap B & C to put AC together */ step->deltaLength = criteria[ACvsBD] - criteria[ABvsCD]; step->nodes[0] = nodeABCD[1]; step->nodes[1] = nodeABCD[2]; } else { /* swap AC to put AD together */ step->deltaLength = criteria[ADvsBC] - criteria[ABvsCD]; step->nodes[0] = nodeABCD[0]; step->nodes[1] = nodeABCD[2]; } if (verbose>3) { fprintf(stderr, "SPR chain step %d for %d around %d swap %d %d deltaLen %.5f\n", iStep+1, nodeAround, nodeMove, step->nodes[0], step->nodes[1], step->deltaLength); if (verbose>4) PrintNJInternal(stderr, NJ, /*useLen*/false); } ReplaceChild(/*IN/OUT*/NJ, nodeAround, step->nodes[0], step->nodes[1]); ReplaceChild(/*IN/OUT*/NJ, NJ->parent[nodeAround], step->nodes[1], step->nodes[0]); UpdateForNNI(/*IN/OUT*/NJ, nodeAround, /*IN/OUT*/upProfiles, /*useML*/false); /* set the new nodeAround -- either parent(nodeMove) or sibling(nodeMove) -- so that it different from current nodeAround */ int newAround[2] = { NJ->parent[nodeMove], Sibling(NJ, nodeMove) }; if (NJ->parent[nodeMove] == NJ->root) RootSiblings(NJ, nodeMove, /*OUT*/newAround); assert(newAround[0] == nodeAround || newAround[1] == nodeAround); assert(newAround[0] != newAround[1]); nodeAround = newAround[newAround[0] == nodeAround ? 1 : 0]; } return(iStep); } void UnwindSPRStep(/*IN/OUT*/NJ_t *NJ, /*IN*/spr_step_t *step, /*IN/OUT*/profile_t **upProfiles) { int parents[2]; int i; for (i = 0; i < 2; i++) { assert(step->nodes[i] >= 0 && step->nodes[i] < NJ->maxnodes); parents[i] = NJ->parent[step->nodes[i]]; assert(parents[i] >= 0); } assert(parents[0] != parents[1]); ReplaceChild(/*IN/OUT*/NJ, parents[0], step->nodes[0], step->nodes[1]); ReplaceChild(/*IN/OUT*/NJ, parents[1], step->nodes[1], step->nodes[0]); int iYounger = 0; if (NJ->parent[parents[0]] == parents[1]) { iYounger = 0; } else { assert(NJ->parent[parents[1]] == parents[0]); iYounger = 1; } UpdateForNNI(/*IN/OUT*/NJ, parents[iYounger], /*IN/OUT*/upProfiles, /*useML*/false); } /* Update the profile of node and its ancestor, and delete nearby out-profiles */ void UpdateForNNI(/*IN/OUT*/NJ_t *NJ, int node, /*IN/OUT*/profile_t **upProfiles, bool useML) { int i; if (slow) { /* exhaustive update */ for (i = 0; i < NJ->maxnodes; i++) DeleteUpProfile(upProfiles, NJ, i); /* update profiles back to root */ int ancestor; for (ancestor = node; ancestor >= 0; ancestor = NJ->parent[ancestor]) RecomputeProfile(/*IN/OUT*/NJ, upProfiles, ancestor, useML); /* remove any up-profiles made while doing that*/ for (i = 0; i < NJ->maxnodes; i++) DeleteUpProfile(upProfiles, NJ, i); } else { /* if fast, only update around self note that upProfile(parent) is still OK after an NNI, but up-profiles of uncles may not be */ DeleteUpProfile(upProfiles, NJ, node); for (i = 0; i < NJ->child[node].nChild; i++) DeleteUpProfile(upProfiles, NJ, NJ->child[node].child[i]); assert(node != NJ->root); int parent = NJ->parent[node]; int neighbors[2] = { parent, Sibling(NJ, node) }; if (parent == NJ->root) RootSiblings(NJ, node, /*OUT*/neighbors); DeleteUpProfile(upProfiles, NJ, neighbors[0]); DeleteUpProfile(upProfiles, NJ, neighbors[1]); int uncle = Sibling(NJ, parent); if (uncle >= 0) DeleteUpProfile(upProfiles, NJ, uncle); RecomputeProfile(/*IN/OUT*/NJ, upProfiles, node, useML); RecomputeProfile(/*IN/OUT*/NJ, upProfiles, parent, useML); } } void SPR(/*IN/OUT*/NJ_t *NJ, int maxSPRLength, int iRound, int nRounds) { /* Given a non-root node N with children A,B, sibling C, and uncle D, we can try to move A by doing three types of moves (4 choices): "down" -- swap A with a child of B (if B is not a leaf) [2 choices] "over" -- swap B with C "up" -- swap A with D We follow down moves with down moves, over moves with down moves, and up moves with either up or over moves. (Other choices are just backing up and hence useless.) As with NNIs, we keep track of up-profiles as we go. However, some of the regular profiles may also become "stale" so it is a bit trickier. We store the traversal before we do SPRs to avoid any possible infinite loop */ double last_tot_len = 0.0; if (NJ->nSeq <= 3 || maxSPRLength < 1) return; if (slow) last_tot_len = TreeLength(NJ, /*recomputeLengths*/true); int *nodeList = mymalloc(sizeof(int) * NJ->maxnodes); int nodeListLen = 0; traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { nodeList[nodeListLen++] = node; } assert(nodeListLen == NJ->maxnode); traversal = FreeTraversal(traversal,NJ); profile_t **upProfiles = UpProfiles(NJ); spr_step_t *steps = mymalloc(sizeof(spr_step_t) * maxSPRLength); /* current chain of SPRs */ int i; for (i = 0; i < nodeListLen; i++) { node = nodeList[i]; if ((i % 100) == 0) ProgressReport("SPR round %3d of %3d, %d of %d nodes", iRound+1, nRounds, i+1, nodeListLen); if (node == NJ->root) continue; /* nothing to do for root */ /* The nodes to NNI around */ int nodeAround[2] = { NJ->parent[node], Sibling(NJ, node) }; if (NJ->parent[node] == NJ->root) { /* NNI around both siblings instead */ RootSiblings(NJ, node, /*OUT*/nodeAround); } bool bChanged = false; int iAround; for (iAround = 0; iAround < 2 && bChanged == false; iAround++) { int ACFirst; for (ACFirst = 0; ACFirst < 2 && bChanged == false; ACFirst++) { if(verbose > 3) PrintNJInternal(stderr, NJ, /*useLen*/false); int chainLength = FindSPRSteps(/*IN/OUT*/NJ, node, nodeAround[iAround], upProfiles, /*OUT*/steps, maxSPRLength, (bool)ACFirst); double dMinDelta = 0.0; int iCBest = -1; double dTotDelta = 0.0; int iC; for (iC = 0; iC < chainLength; iC++) { dTotDelta += steps[iC].deltaLength; if (dTotDelta < dMinDelta) { dMinDelta = dTotDelta; iCBest = iC; } } if (verbose>3) { fprintf(stderr, "SPR %s %d around %d chainLength %d of %d deltaLength %.5f swaps:", iCBest >= 0 ? "move" : "abandoned", node,nodeAround[iAround],iCBest+1,chainLength,dMinDelta); for (iC = 0; iC < chainLength; iC++) fprintf(stderr, " (%d,%d)%.4f", steps[iC].nodes[0], steps[iC].nodes[1], steps[iC].deltaLength); fprintf(stderr,"\n"); } for (iC = chainLength - 1; iC > iCBest; iC--) UnwindSPRStep(/*IN/OUT*/NJ, /*IN*/&steps[iC], /*IN/OUT*/upProfiles); if(verbose > 3) PrintNJInternal(stderr, NJ, /*useLen*/false); while (slow && iCBest >= 0) { double expected_tot_len = last_tot_len + dMinDelta; double new_tot_len = TreeLength(NJ, /*recompute*/true); if (verbose > 2) fprintf(stderr, "Total branch-length is now %.4f was %.4f expected %.4f\n", new_tot_len, last_tot_len, expected_tot_len); if (new_tot_len < last_tot_len) { last_tot_len = new_tot_len; break; /* no rewinding necessary */ } if (verbose > 2) fprintf(stderr, "Rewinding SPR to %d\n",iCBest); UnwindSPRStep(/*IN/OUT*/NJ, /*IN*/&steps[iCBest], /*IN/OUT*/upProfiles); dMinDelta -= steps[iCBest].deltaLength; iCBest--; } if (iCBest >= 0) bChanged = true; } /* loop over which step to take at 1st NNI */ } /* loop over which node to pivot around */ if (bChanged) { nSPR++; /* the SPR move is OK */ /* make sure all the profiles are OK */ int j; for (j = 0; j < NJ->maxnodes; j++) DeleteUpProfile(upProfiles, NJ, j); int ancestor; for (ancestor = NJ->parent[node]; ancestor >= 0; ancestor = NJ->parent[ancestor]) RecomputeProfile(/*IN/OUT*/NJ, upProfiles, ancestor, /*useML*/false); } } /* end loop over subtrees to prune & regraft */ steps = myfree(steps, sizeof(spr_step_t) * maxSPRLength); upProfiles = FreeUpProfiles(upProfiles,NJ); nodeList = myfree(nodeList, sizeof(int) * NJ->maxnodes); } void RecomputeProfile(/*IN/OUT*/NJ_t *NJ, /*IN/OUT*/profile_t **upProfiles, int node, bool useML) { if (node < NJ->nSeq || node == NJ->root) return; /* no profile to compute */ assert(NJ->child[node].nChild==2); profile_t *profiles[4]; double weight = 0.5; if (useML || !bionj) { profiles[0] = NJ->profiles[NJ->child[node].child[0]]; profiles[1] = NJ->profiles[NJ->child[node].child[1]]; } else { int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML); weight = QuartetWeight(profiles, NJ->distance_matrix, NJ->nPos); } if (verbose>3) { if (useML) { fprintf(stderr, "Recompute %d from %d %d lengths %.4f %.4f\n", node, NJ->child[node].child[0], NJ->child[node].child[1], NJ->branchlength[NJ->child[node].child[0]], NJ->branchlength[NJ->child[node].child[1]]); } else { fprintf(stderr, "Recompute %d from %d %d weight %.3f\n", node, NJ->child[node].child[0], NJ->child[node].child[1], weight); } } NJ->profiles[node] = FreeProfile(NJ->profiles[node], NJ->nPos, NJ->nConstraints); if (useML) { NJ->profiles[node] = PosteriorProfile(profiles[0], profiles[1], NJ->branchlength[NJ->child[node].child[0]], NJ->branchlength[NJ->child[node].child[1]], NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints); } else { NJ->profiles[node] = AverageProfile(profiles[0], profiles[1], NJ->nPos, NJ->nConstraints, NJ->distance_matrix, weight); } } /* The BIONJ-like formula for the weight of A when building a profile for AB is 1/2 + (avgD(B,CD) - avgD(A,CD))/(2*d(A,B)) */ double QuartetWeight(profile_t *profiles[4], distance_matrix_t *dmat, int nPos) { if (!bionj) return(-1.0); /* even weighting */ double d[6]; CorrectedPairDistances(profiles, 4, dmat, nPos, /*OUT*/d); if (d[qAB] < 0.01) return -1.0; double weight = 0.5 + ((d[qBC]+d[qBD])-(d[qAC]+d[qAD]))/(4*d[qAB]); if (weight < 0) weight = 0; if (weight > 1) weight = 1; return (weight); } /* Resets the children entry of parent and also the parent entry of newchild */ void ReplaceChild(/*IN/OUT*/NJ_t *NJ, int parent, int oldchild, int newchild) { NJ->parent[newchild] = parent; int iChild; for (iChild = 0; iChild < NJ->child[parent].nChild; iChild++) { if (NJ->child[parent].child[iChild] == oldchild) { NJ->child[parent].child[iChild] = newchild; return; } } assert(0); } /* Recomputes all branch lengths For internal branches such as (A,B) vs. (C,D), uses the formula length(AB|CD) = (d(A,C)+d(A,D)+d(B,C)+d(B,D))/4 - d(A,B)/2 - d(C,D)/2 (where all distances are profile distances - diameters). For external branches (e.g. to leaves) A vs. (B,C), use the formula length(A|BC) = (d(A,B)+d(A,C)-d(B,C))/2 */ void UpdateBranchLengths(/*IN/OUT*/NJ_t *NJ) { if (NJ->nSeq < 2) return; else if (NJ->nSeq == 2) { int root = NJ->root; int nodeA = NJ->child[root].child[0]; int nodeB = NJ->child[root].child[1]; besthit_t h; ProfileDist(NJ->profiles[nodeA],NJ->profiles[nodeB], NJ->nPos, NJ->distance_matrix, /*OUT*/&h); if (logdist) h.dist = LogCorrect(h.dist); NJ->branchlength[nodeA] = h.dist/2.0; NJ->branchlength[nodeB] = h.dist/2.0; return; } profile_t **upProfiles = UpProfiles(NJ); traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { /* reset branch length of node (distance to its parent) */ if (node == NJ->root) continue; /* no branch length to set */ if (node < NJ->nSeq) { /* a leaf */ profile_t *profileA = NJ->profiles[node]; profile_t *profileB = NULL; profile_t *profileC = NULL; int sib = Sibling(NJ,node); if (sib == -1) { /* at root, have 2 siblings */ int sibs[2]; RootSiblings(NJ, node, /*OUT*/sibs); profileB = NJ->profiles[sibs[0]]; profileC = NJ->profiles[sibs[1]]; } else { profileB = NJ->profiles[sib]; profileC = GetUpProfile(/*IN/OUT*/upProfiles, NJ, NJ->parent[node], /*useML*/false); } profile_t *profiles[3] = {profileA,profileB,profileC}; double d[3]; /*AB,AC,BC*/ CorrectedPairDistances(profiles, 3, NJ->distance_matrix, NJ->nPos, /*OUT*/d); /* d(A,BC) = (dAB+dAC-dBC)/2 */ NJ->branchlength[node] = (d[0]+d[1]-d[2])/2.0; } else { profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false); double d[6]; CorrectedPairDistances(profiles, 4, NJ->distance_matrix, NJ->nPos, /*OUT*/d); NJ->branchlength[node] = (d[qAC]+d[qAD]+d[qBC]+d[qBD])/4.0 - (d[qAB]+d[qCD])/2.0; /* no longer needed */ DeleteUpProfile(upProfiles, NJ, nodeABCD[0]); DeleteUpProfile(upProfiles, NJ, nodeABCD[1]); } } traversal = FreeTraversal(traversal,NJ); upProfiles = FreeUpProfiles(upProfiles,NJ); } /* Pick columns for resampling, stored as returned_vector[iBoot*nPos + j] */ int *ResampleColumns(int nPos, int nBootstrap) { long lPos = nPos; /* to prevent overflow on very long alignments when multiplying nPos * nBootstrap */ int *col = (int*)mymalloc(sizeof(int)*lPos*(size_t)nBootstrap); int i; for (i = 0; i < nBootstrap; i++) { int j; for (j = 0; j < nPos; j++) { int pos = (int)(knuth_rand() * nPos); if (pos<0) pos = 0; else if (pos == nPos) pos = nPos-1; col[i*lPos + j] = pos; } } if (verbose > 5) { for (i=0; i < 3 && i < nBootstrap; i++) { fprintf(stderr,"Boot%d",i); int j; for (j = 0; j < nPos; j++) { fprintf(stderr,"\t%d",col[i*lPos+j]); } fprintf(stderr,"\n"); } } return(col); } void ReliabilityNJ(/*IN/OUT*/NJ_t *NJ, int nBootstrap) { /* For each non-root node N, with children A,B, parent P, sibling C, and grandparent G, we test the reliability of the split (A,B) versus rest by comparing the profiles of A, B, C, and the "up-profile" of P. Each node's upProfile is the average of its sibling's (down)-profile + its parent's up-profile (If node's parent is the root, then there are two siblings and we don't need an up-profile) To save memory, we do depth-first-search down from the root, and we only keep up-profiles for nodes in the active path. */ if (NJ->nSeq <= 3 || nBootstrap <= 0) return; /* nothing to do */ int *col = ResampleColumns(NJ->nPos, nBootstrap); profile_t **upProfiles = UpProfiles(NJ); traversal_t traversal = InitTraversal(NJ); int node = NJ->root; int iNodesDone = 0; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (node < NJ->nSeq || node == NJ->root) continue; /* nothing to do for leaves or root */ if(iNodesDone > 0 && (iNodesDone % 100) == 0) ProgressReport("Local bootstrap for %6d of %6d internal splits", iNodesDone, NJ->nSeq-3, 0, 0); iNodesDone++; profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false); NJ->support[node] = SplitSupport(profiles[0], profiles[1], profiles[2], profiles[3], NJ->distance_matrix, NJ->nPos, nBootstrap, col); /* no longer needed */ DeleteUpProfile(upProfiles, NJ, nodeABCD[0]); DeleteUpProfile(upProfiles, NJ, nodeABCD[1]); DeleteUpProfile(upProfiles, NJ, nodeABCD[2]); } traversal = FreeTraversal(traversal,NJ); upProfiles = FreeUpProfiles(upProfiles,NJ); col = myfree(col, sizeof(int)*((size_t)NJ->nPos)*nBootstrap); } profile_t *NewProfile(int nPos, int nConstraints) { profile_t *profile = (profile_t *)mymalloc(sizeof(profile_t)); profile->weights = mymalloc(sizeof(numeric_t)*nPos); profile->codes = mymalloc(sizeof(unsigned char)*nPos); profile->vectors = NULL; profile->nVectors = 0; profile->codeDist = NULL; if (nConstraints == 0) { profile->nOn = NULL; profile->nOff = NULL; } else { profile->nOn = mymalloc(sizeof(int)*nConstraints); profile->nOff = mymalloc(sizeof(int)*nConstraints); } return(profile); } profile_t *FreeProfile(profile_t *profile, int nPos, int nConstraints) { if(profile==NULL) return(NULL); myfree(profile->codes, nPos); myfree(profile->weights, nPos); myfree(profile->vectors, sizeof(numeric_t)*nCodes*profile->nVectors); myfree(profile->codeDist, sizeof(numeric_t)*nCodes*nPos); if (nConstraints > 0) { myfree(profile->nOn, sizeof(int)*nConstraints); myfree(profile->nOff, sizeof(int)*nConstraints); } return(myfree(profile, sizeof(profile_t))); } void SetupABCD(NJ_t *NJ, int node, /* the 4 profiles; the last one is an outprofile */ /*OPTIONAL OUT*/profile_t *profiles[4], /*OPTIONAL IN/OUT*/profile_t **upProfiles, /*OUT*/int nodeABCD[4], bool useML) { int parent = NJ->parent[node]; assert(parent >= 0); assert(NJ->child[node].nChild == 2); nodeABCD[0] = NJ->child[node].child[0]; /*A*/ nodeABCD[1] = NJ->child[node].child[1]; /*B*/ profile_t *profile4 = NULL; if (parent == NJ->root) { int sibs[2]; RootSiblings(NJ, node, /*OUT*/sibs); nodeABCD[2] = sibs[0]; nodeABCD[3] = sibs[1]; if (profiles == NULL) return; profile4 = NJ->profiles[sibs[1]]; } else { nodeABCD[2] = Sibling(NJ,node); assert(nodeABCD[2] >= 0); nodeABCD[3] = parent; if (profiles == NULL) return; profile4 = GetUpProfile(upProfiles,NJ,parent,useML); } assert(upProfiles != NULL); int i; for (i = 0; i < 3; i++) profiles[i] = NJ->profiles[nodeABCD[i]]; profiles[3] = profile4; } int Sibling(NJ_t *NJ, int node) { int parent = NJ->parent[node]; if (parent < 0 || parent == NJ->root) return(-1); int iChild; for(iChild=0;iChild<NJ->child[parent].nChild;iChild++) { if(NJ->child[parent].child[iChild] != node) return (NJ->child[parent].child[iChild]); } assert(0); return(-1); } void RootSiblings(NJ_t *NJ, int node, /*OUT*/int sibs[2]) { assert(NJ->parent[node] == NJ->root); assert(NJ->child[NJ->root].nChild == 3); int nSibs = 0; int iChild; for(iChild=0; iChild < NJ->child[NJ->root].nChild; iChild++) { int child = NJ->child[NJ->root].child[iChild]; if (child != node) sibs[nSibs++] = child; } assert(nSibs==2); } void TestSplitsML(/*IN/OUT*/NJ_t *NJ, /*OUT*/SplitCount_t *splitcount, int nBootstrap) { const double tolerance = 1e-6; splitcount->nBadSplits = 0; splitcount->nConstraintViolations = 0; splitcount->nBadBoth = 0; splitcount->nSplits = 0; splitcount->dWorstDeltaUnconstrained = 0; splitcount->dWorstDeltaConstrained = 0; profile_t **upProfiles = UpProfiles(NJ); traversal_t traversal = InitTraversal(NJ); int node = NJ->root; int *col = nBootstrap > 0 ? ResampleColumns(NJ->nPos, nBootstrap) : NULL; double *site_likelihoods[3]; int choice; for (choice = 0; choice < 3; choice++) site_likelihoods[choice] = mymalloc(sizeof(double)*NJ->nPos); int iNodesDone = 0; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (node < NJ->nSeq || node == NJ->root) continue; /* nothing to do for leaves or root */ if(iNodesDone > 0 && (iNodesDone % 100) == 0) ProgressReport("ML split tests for %6d of %6d internal splits", iNodesDone, NJ->nSeq-3, 0, 0); iNodesDone++; profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/true); double loglk[3]; double len[5]; int i; for (i = 0; i < 4; i++) len[i] = NJ->branchlength[nodeABCD[i]]; len[4] = NJ->branchlength[node]; double lenABvsCD[5] = {len[LEN_A], len[LEN_B], len[LEN_C], len[LEN_D], len[LEN_I]}; double lenACvsBD[5] = {len[LEN_A], len[LEN_C], len[LEN_B], len[LEN_D], len[LEN_I]}; /* Swap B & C */ double lenADvsBC[5] = {len[LEN_A], len[LEN_D], len[LEN_C], len[LEN_B], len[LEN_I]}; /* Swap B & D */ { #ifdef OPENMP #pragma omp parallel #pragma omp sections #endif { #ifdef OPENMP #pragma omp section #endif { /* Lengths are already optimized for ABvsCD */ loglk[ABvsCD] = MLQuartetLogLk(profiles[0], profiles[1], profiles[2], profiles[3], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenABvsCD, /*OUT*/site_likelihoods[ABvsCD]); } #ifdef OPENMP #pragma omp section #endif { loglk[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenACvsBD, /*pStarTest*/NULL, /*OUT*/site_likelihoods[ACvsBD]); } #ifdef OPENMP #pragma omp section #endif { loglk[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenADvsBC, /*pStarTest*/NULL, /*OUT*/site_likelihoods[ADvsBC]); } } } /* do a second pass on the better alternative if it is close */ if (loglk[ACvsBD] > loglk[ADvsBC]) { if (mlAccuracy > 1 || loglk[ACvsBD] > loglk[ABvsCD] - closeLogLkLimit) { loglk[ACvsBD] = MLQuartetOptimize(profiles[0], profiles[2], profiles[1], profiles[3], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenACvsBD, /*pStarTest*/NULL, /*OUT*/site_likelihoods[ACvsBD]); } } else { if (mlAccuracy > 1 || loglk[ADvsBC] > loglk[ABvsCD] - closeLogLkLimit) { loglk[ADvsBC] = MLQuartetOptimize(profiles[0], profiles[3], profiles[2], profiles[1], NJ->nPos, NJ->transmat, &NJ->rates, /*IN/OUT*/lenADvsBC, /*pStarTest*/NULL, /*OUT*/site_likelihoods[ADvsBC]); } } if (loglk[ABvsCD] >= loglk[ACvsBD] && loglk[ABvsCD] >= loglk[ADvsBC]) choice = ABvsCD; else if (loglk[ACvsBD] >= loglk[ABvsCD] && loglk[ACvsBD] >= loglk[ADvsBC]) choice = ACvsBD; else choice = ADvsBC; bool badSplit = loglk[choice] > loglk[ABvsCD] + treeLogLkDelta; /* ignore small changes in likelihood */ /* constraint penalties, indexed by nni_t (lower is better) */ double p[3]; QuartetConstraintPenalties(profiles, NJ->nConstraints, /*OUT*/p); bool bBadConstr = p[ABvsCD] > p[ACvsBD] + tolerance || p[ABvsCD] > p[ADvsBC] + tolerance; bool violateConstraint = false; int iC; for (iC=0; iC < NJ->nConstraints; iC++) { if (SplitViolatesConstraint(profiles, iC)) { violateConstraint = true; break; } } splitcount->nSplits++; if (violateConstraint) splitcount->nConstraintViolations++; if (badSplit) splitcount->nBadSplits++; if (badSplit && bBadConstr) splitcount->nBadBoth++; if (badSplit) { double delta = loglk[choice] - loglk[ABvsCD]; /* If ABvsCD is favored over the more likely NNI by constraints, then this is probably a bad split because of the constraint */ if (p[choice] > p[ABvsCD] + tolerance) splitcount->dWorstDeltaConstrained = MAX(delta, splitcount->dWorstDeltaConstrained); else splitcount->dWorstDeltaUnconstrained = MAX(delta, splitcount->dWorstDeltaUnconstrained); } if (nBootstrap>0) NJ->support[node] = badSplit ? 0.0 : SHSupport(NJ->nPos, nBootstrap, col, loglk, site_likelihoods); /* No longer needed */ DeleteUpProfile(upProfiles, NJ, nodeABCD[0]); DeleteUpProfile(upProfiles, NJ, nodeABCD[1]); DeleteUpProfile(upProfiles, NJ, nodeABCD[2]); } traversal = FreeTraversal(traversal,NJ); upProfiles = FreeUpProfiles(upProfiles,NJ); if (nBootstrap>0) col = myfree(col, sizeof(int)*((size_t)NJ->nPos)*nBootstrap); for (choice = 0; choice < 3; choice++) site_likelihoods[choice] = myfree(site_likelihoods[choice], sizeof(double)*NJ->nPos); } void TestSplitsMinEvo(NJ_t *NJ, /*OUT*/SplitCount_t *splitcount) { const double tolerance = 1e-6; splitcount->nBadSplits = 0; splitcount->nConstraintViolations = 0; splitcount->nBadBoth = 0; splitcount->nSplits = 0; splitcount->dWorstDeltaUnconstrained = 0.0; splitcount->dWorstDeltaConstrained = 0.0; profile_t **upProfiles = UpProfiles(NJ); traversal_t traversal = InitTraversal(NJ); int node = NJ->root; while((node = TraversePostorder(node, NJ, /*IN/OUT*/traversal, /*pUp*/NULL)) >= 0) { if (node < NJ->nSeq || node == NJ->root) continue; /* nothing to do for leaves or root */ profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, /*useML*/false); if (verbose>2) fprintf(stderr,"Testing Split around %d: A=%d B=%d C=%d D=up(%d) or node parent %d\n", node, nodeABCD[0], nodeABCD[1], nodeABCD[2], nodeABCD[3], NJ->parent[node]); double d[6]; /* distances, perhaps log-corrected distances, no constraint penalties */ CorrectedPairDistances(profiles, 4, NJ->distance_matrix, NJ->nPos, /*OUT*/d); /* alignment-based scores for each split (lower is better) */ double sABvsCD = d[qAB] + d[qCD]; double sACvsBD = d[qAC] + d[qBD]; double sADvsBC = d[qAD] + d[qBC]; /* constraint penalties, indexed by nni_t (lower is better) */ double p[3]; QuartetConstraintPenalties(profiles, NJ->nConstraints, /*OUT*/p); int nConstraintsViolated = 0; int iC; for (iC=0; iC < NJ->nConstraints; iC++) { if (SplitViolatesConstraint(profiles, iC)) { nConstraintsViolated++; if (verbose > 2) { double penalty[3] = {0.0,0.0,0.0}; (void)QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/penalty); fprintf(stderr, "Violate constraint %d at %d (children %d %d) penalties %.3f %.3f %.3f %d/%d %d/%d %d/%d %d/%d\n", iC, node, NJ->child[node].child[0], NJ->child[node].child[1], penalty[ABvsCD], penalty[ACvsBD], penalty[ADvsBC], profiles[0]->nOn[iC], profiles[0]->nOff[iC], profiles[1]->nOn[iC], profiles[1]->nOff[iC], profiles[2]->nOn[iC], profiles[2]->nOff[iC], profiles[3]->nOn[iC], profiles[3]->nOff[iC]); } } } double delta = sABvsCD - MIN(sACvsBD,sADvsBC); bool bBadDist = delta > tolerance; bool bBadConstr = p[ABvsCD] > p[ACvsBD] + tolerance || p[ABvsCD] > p[ADvsBC] + tolerance; splitcount->nSplits++; if (bBadDist) { nni_t choice = sACvsBD < sADvsBC ? ACvsBD : ADvsBC; /* If ABvsCD is favored over the shorter NNI by constraints, then this is probably a bad split because of the constraint */ if (p[choice] > p[ABvsCD] + tolerance) splitcount->dWorstDeltaConstrained = MAX(delta, splitcount->dWorstDeltaConstrained); else splitcount->dWorstDeltaUnconstrained = MAX(delta, splitcount->dWorstDeltaUnconstrained); } if (nConstraintsViolated > 0) splitcount->nConstraintViolations++; /* count splits with any violations, not #constraints in a splits */ if (bBadDist) splitcount->nBadSplits++; if (bBadDist && bBadConstr) splitcount->nBadBoth++; if (bBadConstr && verbose > 2) { /* Which NNI would be better */ double dist_advantage = 0; double constraint_penalty = 0; if (p[ACvsBD] < p[ADvsBC]) { dist_advantage = sACvsBD - sABvsCD; constraint_penalty = p[ABvsCD] - p[ACvsBD]; } else { dist_advantage = sADvsBC - sABvsCD; constraint_penalty = p[ABvsCD] - p[ADvsBC]; } fprintf(stderr, "Violate constraints %d distance_advantage %.3f constraint_penalty %.3f (children %d %d):", node, dist_advantage, constraint_penalty, NJ->child[node].child[0], NJ->child[node].child[1]); /* list the constraints with a penalty, meaning that ABCD all have non-zero values and that AB|CD worse than others */ for (iC = 0; iC < NJ->nConstraints; iC++) { double ppart[6]; if (QuartetConstraintPenaltiesPiece(profiles, iC, /*OUT*/ppart)) { if (ppart[qAB] + ppart[qCD] > ppart[qAD] + ppart[qBC] + tolerance || ppart[qAB] + ppart[qCD] > ppart[qAC] + ppart[qBD] + tolerance) fprintf(stderr, " %d (%d/%d %d/%d %d/%d %d/%d)", iC, profiles[0]->nOn[iC], profiles[0]->nOff[iC], profiles[1]->nOn[iC], profiles[1]->nOff[iC], profiles[2]->nOn[iC], profiles[2]->nOff[iC], profiles[3]->nOn[iC], profiles[3]->nOff[iC]); } } fprintf(stderr, "\n"); } /* no longer needed */ DeleteUpProfile(upProfiles, NJ, nodeABCD[0]); DeleteUpProfile(upProfiles, NJ, nodeABCD[1]); } traversal = FreeTraversal(traversal,NJ); upProfiles = FreeUpProfiles(upProfiles,NJ); } /* Computes support for (A,B),(C,D) compared to that for (A,C),(B,D) and (A,D),(B,C) */ double SplitSupport(profile_t *pA, profile_t *pB, profile_t *pC, profile_t *pD, /*OPTIONAL*/distance_matrix_t *dmat, int nPos, int nBootstrap, int *col) { int i,j; long lPos = nPos; /* to avoid overflow when multiplying */ /* Note distpieces are weighted */ double *distpieces[6]; double *weights[6]; for (j = 0; j < 6; j++) { distpieces[j] = (double*)mymalloc(sizeof(double)*nPos); weights[j] = (double*)mymalloc(sizeof(double)*nPos); } int iFreqA = 0; int iFreqB = 0; int iFreqC = 0; int iFreqD = 0; for (i = 0; i < nPos; i++) { numeric_t *fA = GET_FREQ(pA, i, /*IN/OUT*/iFreqA); numeric_t *fB = GET_FREQ(pB, i, /*IN/OUT*/iFreqB); numeric_t *fC = GET_FREQ(pC, i, /*IN/OUT*/iFreqC); numeric_t *fD = GET_FREQ(pD, i, /*IN/OUT*/iFreqD); weights[qAB][i] = pA->weights[i] * pB->weights[i]; weights[qAC][i] = pA->weights[i] * pC->weights[i]; weights[qAD][i] = pA->weights[i] * pD->weights[i]; weights[qBC][i] = pB->weights[i] * pC->weights[i]; weights[qBD][i] = pB->weights[i] * pD->weights[i]; weights[qCD][i] = pC->weights[i] * pD->weights[i]; distpieces[qAB][i] = weights[qAB][i] * ProfileDistPiece(pA->codes[i], pB->codes[i], fA, fB, dmat, NULL); distpieces[qAC][i] = weights[qAC][i] * ProfileDistPiece(pA->codes[i], pC->codes[i], fA, fC, dmat, NULL); distpieces[qAD][i] = weights[qAD][i] * ProfileDistPiece(pA->codes[i], pD->codes[i], fA, fD, dmat, NULL); distpieces[qBC][i] = weights[qBC][i] * ProfileDistPiece(pB->codes[i], pC->codes[i], fB, fC, dmat, NULL); distpieces[qBD][i] = weights[qBD][i] * ProfileDistPiece(pB->codes[i], pD->codes[i], fB, fD, dmat, NULL); distpieces[qCD][i] = weights[qCD][i] * ProfileDistPiece(pC->codes[i], pD->codes[i], fC, fD, dmat, NULL); } assert(iFreqA == pA->nVectors); assert(iFreqB == pB->nVectors); assert(iFreqC == pC->nVectors); assert(iFreqD == pD->nVectors); double totpieces[6]; double totweights[6]; double dists[6]; for (j = 0; j < 6; j++) { totpieces[j] = 0.0; totweights[j] = 0.0; for (i = 0; i < nPos; i++) { totpieces[j] += distpieces[j][i]; totweights[j] += weights[j][i]; } dists[j] = totweights[j] > 0.01 ? totpieces[j]/totweights[j] : 3.0; if (logdist) dists[j] = LogCorrect(dists[j]); } /* Support1 = Support(AB|CD over AC|BD) = d(A,C)+d(B,D)-d(A,B)-d(C,D) Support2 = Support(AB|CD over AD|BC) = d(A,D)+d(B,C)-d(A,B)-d(C,D) */ double support1 = dists[qAC] + dists[qBD] - dists[qAB] - dists[qCD]; double support2 = dists[qAD] + dists[qBC] - dists[qAB] - dists[qCD]; if (support1 < 0 || support2 < 0) { nSuboptimalSplits++; /* Another split seems superior */ } assert(nBootstrap > 0); int nSupport = 0; int iBoot; for (iBoot=0;iBoot<nBootstrap;iBoot++) { int *colw = &col[lPos*iBoot]; for (j = 0; j < 6; j++) { double totp = 0; double totw = 0; double *d = distpieces[j]; double *w = weights[j]; for (i=0; i<nPos; i++) { int c = colw[i]; totp += d[c]; totw += w[c]; } dists[j] = totw > 0.01 ? totp/totw : 3.0; if (logdist) dists[j] = LogCorrect(dists[j]); } support1 = dists[qAC] + dists[qBD] - dists[qAB] - dists[qCD]; support2 = dists[qAD] + dists[qBC] - dists[qAB] - dists[qCD]; if (support1 > 0 && support2 > 0) nSupport++; } /* end loop over bootstrap replicates */ for (j = 0; j < 6; j++) { distpieces[j] = myfree(distpieces[j], sizeof(double)*nPos); weights[j] = myfree(weights[j], sizeof(double)*nPos); } return( nSupport/(double)nBootstrap ); } double SHSupport(int nPos, int nBootstrap, int *col, double loglk[3], double *site_likelihoods[3]) { long lPos = nPos; /* to avoid overflow when multiplying */ assert(nBootstrap>0); double delta1 = loglk[0]-loglk[1]; double delta2 = loglk[0]-loglk[2]; double delta = delta1 < delta2 ? delta1 : delta2; double *siteloglk[3]; int i,j; for (i = 0; i < 3; i++) { siteloglk[i] = mymalloc(sizeof(double)*nPos); for (j = 0; j < nPos; j++) siteloglk[i][j] = log(site_likelihoods[i][j]); } int nSupport = 0; int iBoot; for (iBoot = 0; iBoot < nBootstrap; iBoot++) { double resampled[3]; for (i = 0; i < 3; i++) resampled[i] = -loglk[i]; for (j = 0; j < nPos; j++) { int pos = col[iBoot*lPos+j]; for (i = 0; i < 3; i++) resampled[i] += siteloglk[i][pos]; } int iBest = 0; for (i = 1; i < 3; i++) if (resampled[i] > resampled[iBest]) iBest = i; double resample1 = resampled[iBest] - resampled[(iBest+1)%3]; double resample2 = resampled[iBest] - resampled[(iBest+2)%3]; double resampleDelta = resample1 < resample2 ? resample1 : resample2; if (resampleDelta < delta) nSupport++; } for (i=0;i<3;i++) siteloglk[i] = myfree(siteloglk[i], sizeof(double)*nPos); return(nSupport/(double)nBootstrap); } void SetDistCriterion(/*IN/OUT*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *hit) { if (hit->i < NJ->nSeq && hit->j < NJ->nSeq) { SeqDist(NJ->profiles[hit->i]->codes, NJ->profiles[hit->j]->codes, NJ->nPos, NJ->distance_matrix, /*OUT*/hit); } else { ProfileDist(NJ->profiles[hit->i], NJ->profiles[hit->j], NJ->nPos, NJ->distance_matrix, /*OUT*/hit); hit->dist -= (NJ->diameter[hit->i] + NJ->diameter[hit->j]); } hit->dist += constraintWeight * (double)JoinConstraintPenalty(NJ, hit->i, hit->j); SetCriterion(NJ,nActive,/*IN/OUT*/hit); } void SetCriterion(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *join) { if(join->i < 0 || join->j < 0 || NJ->parent[join->i] >= 0 || NJ->parent[join->j] >= 0) return; assert(NJ->nOutDistActive[join->i] >= nActive); assert(NJ->nOutDistActive[join->j] >= nActive); int nDiffAllow = tophitsMult > 0 ? (int)(nActive*staleOutLimit) : 0; if (NJ->nOutDistActive[join->i] - nActive > nDiffAllow) SetOutDistance(NJ, join->i, nActive); if (NJ->nOutDistActive[join->j] - nActive > nDiffAllow) SetOutDistance(NJ, join->j, nActive); double outI = NJ->outDistances[join->i]; if (NJ->nOutDistActive[join->i] != nActive) outI *= (nActive-1)/(double)(NJ->nOutDistActive[join->i]-1); double outJ = NJ->outDistances[join->j]; if (NJ->nOutDistActive[join->j] != nActive) outJ *= (nActive-1)/(double)(NJ->nOutDistActive[join->j]-1); join->criterion = join->dist - (outI+outJ)/(double)(nActive-2); if (verbose > 2 && nActive <= 5) { fprintf(stderr, "Set Criterion to join %d %d with nActive=%d dist+penalty %.3f criterion %.3f\n", join->i, join->j, nActive, join->dist, join->criterion); } } void SetOutDistance(NJ_t *NJ, int iNode, int nActive) { if (NJ->nOutDistActive[iNode] == nActive) return; /* May be called by InitNJ before we have parents */ assert(iNode>=0 && (NJ->parent == NULL || NJ->parent[iNode]<0)); besthit_t dist; ProfileDist(NJ->profiles[iNode], NJ->outprofile, NJ->nPos, NJ->distance_matrix, &dist); outprofileOps++; /* out(A) = sum(X!=A) d(A,X) = sum(X!=A) (profiledist(A,X) - diam(A) - diam(X)) = sum(X!=A) profiledist(A,X) - (N-1)*diam(A) - (totdiam - diam(A)) in the absence of gaps: profiledist(A,out) = mean profiledist(A, all active nodes) sum(X!=A) profiledist(A,X) = N * profiledist(A,out) - profiledist(A,A) With gaps, we need to take the weights of the comparisons into account, where w(Ai) is the weight of position i in profile A: w(A,B) = sum_i w(Ai) * w(Bi) d(A,B) = sum_i w(Ai) * w(Bi) * d(Ai,Bi) / w(A,B) sum(X!=A) profiledist(A,X) ~= (N-1) * profiledist(A, Out w/o A) profiledist(A, Out w/o A) = sum_X!=A sum_i d(Ai,Xi) * w(Ai) * w(Bi) / ( sum_X!=A sum_i w(Ai) * w(Bi) ) d(A, Out) = sum_A sum_i d(Ai,Xi) * w(Ai) * w(Bi) / ( sum_X sum_i w(Ai) * w(Bi) ) and so we get profiledist(A,out w/o A) = (top of d(A,Out) - top of d(A,A)) / (weight of d(A,Out) - weight of d(A,A)) top = dist * weight with another correction of nActive because the weight of the out-profile is the average weight not the total weight. */ double top = (nActive-1) * (dist.dist * dist.weight * nActive - NJ->selfweight[iNode] * NJ->selfdist[iNode]); double bottom = (dist.weight * nActive - NJ->selfweight[iNode]); double pdistOutWithoutA = top/bottom; NJ->outDistances[iNode] = bottom > 0.01 ? pdistOutWithoutA - NJ->diameter[iNode] * (nActive-1) - (NJ->totdiam - NJ->diameter[iNode]) : 3.0; NJ->nOutDistActive[iNode] = nActive; if(verbose>3 && iNode < 5) fprintf(stderr,"NewOutDist for %d %f from dist %f selfd %f diam %f totdiam %f newActive %d\n", iNode, NJ->outDistances[iNode], dist.dist, NJ->selfdist[iNode], NJ->diameter[iNode], NJ->totdiam, nActive); if (verbose>6 && (iNode % 10) == 0) { /* Compute the actual out-distance and compare */ double total = 0.0; double total_pd = 0.0; int j; for (j=0;j<NJ->maxnode;j++) { if (j!=iNode && (NJ->parent==NULL || NJ->parent[j]<0)) { besthit_t bh; ProfileDist(NJ->profiles[iNode], NJ->profiles[j], NJ->nPos, NJ->distance_matrix, /*OUT*/&bh); total_pd += bh.dist; total += bh.dist - (NJ->diameter[iNode] + NJ->diameter[j]); } } fprintf(stderr,"OutDist for Node %d %f truth %f profiled %f truth %f pd_err %f\n", iNode, NJ->outDistances[iNode], total, pdistOutWithoutA, total_pd,fabs(pdistOutWithoutA-total_pd)); } } top_hits_t *FreeTopHits(top_hits_t *tophits) { if (tophits == NULL) return(NULL); int iNode; for (iNode = 0; iNode < tophits->maxnodes; iNode++) { top_hits_list_t *l = &tophits->top_hits_lists[iNode]; if (l->hits != NULL) l->hits = myfree(l->hits, sizeof(hit_t) * l->nHits); } tophits->top_hits_lists = myfree(tophits->top_hits_lists, sizeof(top_hits_list_t) * tophits->maxnodes); tophits->visible = myfree(tophits->visible, sizeof(hit_t*) * tophits->maxnodes); tophits->topvisible = myfree(tophits->topvisible, sizeof(int) * tophits->nTopVisible); #ifdef OPENMP for (iNode = 0; iNode < tophits->maxnodes; iNode++) omp_destroy_lock(&tophits->locks[iNode]); tophits->locks = myfree(tophits->locks, sizeof(omp_lock_t) * tophits->maxnodes); #endif return(myfree(tophits, sizeof(top_hits_t))); } top_hits_t *InitTopHits(NJ_t *NJ, int m) { int iNode; assert(m > 0); top_hits_t *tophits = mymalloc(sizeof(top_hits_t)); tophits->m = m; tophits->q = (int)(0.5 + tophits2Mult * sqrt(tophits->m)); if (!useTopHits2nd || tophits->q >= tophits->m) tophits->q = 0; tophits->maxnodes = NJ->maxnodes; tophits->top_hits_lists = mymalloc(sizeof(top_hits_list_t) * tophits->maxnodes); tophits->visible = mymalloc(sizeof(hit_t) * tophits->maxnodes); tophits->nTopVisible = (int)(0.5 + topvisibleMult*m); tophits->topvisible = mymalloc(sizeof(int) * tophits->nTopVisible); #ifdef OPENMP tophits->locks = mymalloc(sizeof(omp_lock_t) * tophits->maxnodes); for (iNode = 0; iNode < tophits->maxnodes; iNode++) omp_init_lock(&tophits->locks[iNode]); #endif int i; for (i = 0; i < tophits->nTopVisible; i++) tophits->topvisible[i] = -1; /* empty */ tophits->topvisibleAge = 0; for (iNode = 0; iNode < tophits->maxnodes; iNode++) { top_hits_list_t *l = &tophits->top_hits_lists[iNode]; l->nHits = 0; l->hits = NULL; l->hitSource = -1; l->age = 0; hit_t *v = &tophits->visible[iNode]; v->j = -1; v->dist = 1e20; } return(tophits); } /* Helper function for sorting in SetAllLeafTopHits, and the global variables it needs */ NJ_t *CompareSeedNJ = NULL; int *CompareSeedGaps = NULL; int CompareSeeds(const void *c1, const void *c2) { int seed1 = *(int *)c1; int seed2 = *(int *)c2; int gapdiff = CompareSeedGaps[seed1] - CompareSeedGaps[seed2]; if (gapdiff != 0) return(gapdiff); /* fewer gaps is better */ double outdiff = CompareSeedNJ->outDistances[seed1] - CompareSeedNJ->outDistances[seed2]; if(outdiff < 0) return(-1); /* closer to more nodes is better */ if(outdiff > 0) return(1); return(0); } /* Using the seed heuristic and the close global variable */ void SetAllLeafTopHits(/*IN/UPDATE*/NJ_t *NJ, /*IN/OUT*/top_hits_t *tophits) { double close = tophitsClose; if (close < 0) { if (fastest && NJ->nSeq >= 50000) { close = 0.99; } else { double logN = log((double)NJ->nSeq)/log(2.0); close = logN/(logN+2.0); } } /* Sort the potential seeds, by a combination of nGaps and NJ->outDistances We don't store nGaps so we need to compute that */ int *nGaps = (int*)mymalloc(sizeof(int)*NJ->nSeq); int iNode; for(iNode=0; iNode<NJ->nSeq; iNode++) { nGaps[iNode] = (int)(0.5 + NJ->nPos - NJ->selfweight[iNode]); } int *seeds = (int*)mymalloc(sizeof(int)*NJ->nSeq); for (iNode=0; iNode<NJ->nSeq; iNode++) seeds[iNode] = iNode; CompareSeedNJ = NJ; CompareSeedGaps = nGaps; qsort(/*IN/OUT*/seeds, NJ->nSeq, sizeof(int), CompareSeeds); CompareSeedNJ = NULL; CompareSeedGaps = NULL; /* For each seed, save its top 2*m hits and then look for close neighbors */ assert(2 * tophits->m <= NJ->nSeq); int iSeed; int nHasTopHits = 0; #ifdef OPENMP #pragma omp parallel for schedule(dynamic, 50) #endif for(iSeed=0; iSeed < NJ->nSeq; iSeed++) { int seed = seeds[iSeed]; if (iSeed > 0 && (iSeed % 100) == 0) { #ifdef OPENMP #pragma omp critical #endif ProgressReport("Top hits for %6d of %6d seqs (at seed %6d)", nHasTopHits, NJ->nSeq, iSeed, 0); } if (tophits->top_hits_lists[seed].nHits > 0) { if(verbose>2) fprintf(stderr, "Skipping seed %d\n", seed); continue; } besthit_t *besthitsSeed = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->nSeq); besthit_t *besthitsNeighbor = (besthit_t*)mymalloc(sizeof(besthit_t) * 2 * tophits->m); besthit_t bestjoin; if(verbose>2) fprintf(stderr,"Trying seed %d\n", seed); SetBestHit(seed, NJ, /*nActive*/NJ->nSeq, /*OUT*/&bestjoin, /*OUT*/besthitsSeed); /* sort & save top hits of self. besthitsSeed is now sorted. */ SortSaveBestHits(seed, /*IN/SORT*/besthitsSeed, /*IN-SIZE*/NJ->nSeq, /*OUT-SIZE*/tophits->m, /*IN/OUT*/tophits); nHasTopHits++; /* find "close" neighbors and compute their top hits */ double neardist = besthitsSeed[2 * tophits->m - 1].dist * close; /* must have at least average weight, rem higher is better and allow a bit more than average, e.g. if we are looking for within 30% away, 20% more gaps than usual seems OK Alternatively, have a coverage requirement in case neighbor is short If fastest, consider the top q/2 hits to be close neighbors, regardless */ double nearweight = 0; int iClose; for (iClose = 0; iClose < 2 * tophits->m; iClose++) nearweight += besthitsSeed[iClose].weight; nearweight = nearweight/(2.0 * tophits->m); /* average */ nearweight *= (1.0-2.0*neardist/3.0); double nearcover = 1.0 - neardist/2.0; if(verbose>2) fprintf(stderr,"Distance limit for close neighbors %f weight %f ungapped %d\n", neardist, nearweight, NJ->nPos-nGaps[seed]); for (iClose = 0; iClose < tophits->m; iClose++) { besthit_t *closehit = &besthitsSeed[iClose]; int closeNode = closehit->j; if (tophits->top_hits_lists[closeNode].nHits > 0) continue; /* If within close-distance, or identical, use as close neighbor */ bool close = closehit->dist <= neardist && (closehit->weight >= nearweight || closehit->weight >= (NJ->nPos-nGaps[closeNode])*nearcover); bool identical = closehit->dist < 1e-6 && fabs(closehit->weight - (NJ->nPos - nGaps[seed])) < 1e-5 && fabs(closehit->weight - (NJ->nPos - nGaps[closeNode])) < 1e-5; if (useTopHits2nd && iClose < tophits->q && (close || identical)) { nHasTopHits++; nClose2Used++; int nUse = MIN(tophits->q * tophits2Safety, 2 * tophits->m); besthit_t *besthitsClose = mymalloc(sizeof(besthit_t) * nUse); TransferBestHits(NJ, /*nActive*/NJ->nSeq, closeNode, /*IN*/besthitsSeed, /*SIZE*/nUse, /*OUT*/besthitsClose, /*updateDistance*/true); SortSaveBestHits(closeNode, /*IN/SORT*/besthitsClose, /*IN-SIZE*/nUse, /*OUT-SIZE*/tophits->q, /*IN/OUT*/tophits); tophits->top_hits_lists[closeNode].hitSource = seed; besthitsClose = myfree(besthitsClose, sizeof(besthit_t) * nUse); } else if (close || identical || (fastest && iClose < (tophits->q+1)/2)) { nHasTopHits++; nCloseUsed++; if(verbose>2) fprintf(stderr, "Near neighbor %d (rank %d weight %f ungapped %d %d)\n", closeNode, iClose, besthitsSeed[iClose].weight, NJ->nPos-nGaps[seed], NJ->nPos-nGaps[closeNode]); /* compute top 2*m hits */ TransferBestHits(NJ, /*nActive*/NJ->nSeq, closeNode, /*IN*/besthitsSeed, /*SIZE*/2 * tophits->m, /*OUT*/besthitsNeighbor, /*updateDistance*/true); SortSaveBestHits(closeNode, /*IN/SORT*/besthitsNeighbor, /*IN-SIZE*/2 * tophits->m, /*OUT-SIZE*/tophits->m, /*IN/OUT*/tophits); /* And then try for a second level of transfer. We assume we are in a good area, because of the 1st level of transfer, and in a small neighborhood, because q is small (32 for 1 million sequences), so we do not make any close checks. */ int iClose2; for (iClose2 = 0; iClose2 < tophits->q && iClose2 < 2 * tophits->m; iClose2++) { int closeNode2 = besthitsNeighbor[iClose2].j; assert(closeNode2 >= 0); if (tophits->top_hits_lists[closeNode2].hits == NULL) { nClose2Used++; nHasTopHits++; int nUse = MIN(tophits->q * tophits2Safety, 2 * tophits->m); besthit_t *besthitsClose2 = mymalloc(sizeof(besthit_t) * nUse); TransferBestHits(NJ, /*nActive*/NJ->nSeq, closeNode2, /*IN*/besthitsNeighbor, /*SIZE*/nUse, /*OUT*/besthitsClose2, /*updateDistance*/true); SortSaveBestHits(closeNode2, /*IN/SORT*/besthitsClose2, /*IN-SIZE*/nUse, /*OUT-SIZE*/tophits->q, /*IN/OUT*/tophits); tophits->top_hits_lists[closeNode2].hitSource = closeNode; besthitsClose2 = myfree(besthitsClose2, sizeof(besthit_t) * nUse); } /* end if should do 2nd-level transfer */ } } } /* end loop over close candidates */ besthitsSeed = myfree(besthitsSeed, sizeof(besthit_t)*NJ->nSeq); besthitsNeighbor = myfree(besthitsNeighbor, sizeof(besthit_t) * 2 * tophits->m); } /* end loop over seeds */ for (iNode=0; iNode<NJ->nSeq; iNode++) { top_hits_list_t *l = &tophits->top_hits_lists[iNode]; assert(l->hits != NULL); assert(l->hits[0].j >= 0); assert(l->hits[0].j < NJ->nSeq); assert(l->hits[0].j != iNode); tophits->visible[iNode] = l->hits[0]; } if (verbose >= 2) fprintf(stderr, "#Close neighbors among leaves: 1st-level %ld 2nd-level %ld seeds %ld\n", nCloseUsed, nClose2Used, NJ->nSeq-nCloseUsed-nClose2Used); nGaps = myfree(nGaps, sizeof(int)*NJ->nSeq); seeds = myfree(seeds, sizeof(int)*NJ->nSeq); /* Now add a "checking phase" where we ensure that the q or 2*sqrt(m) hits of i are represented in j (if they should be) */ long lReplace = 0; int nCheck = tophits->q > 0 ? tophits->q : (int)(0.5 + 2.0*sqrt(tophits->m)); for (iNode = 0; iNode < NJ->nSeq; iNode++) { if ((iNode % 100) == 0) ProgressReport("Checking top hits for %6d of %6d seqs", iNode+1, NJ->nSeq, 0, 0); top_hits_list_t *lNode = &tophits->top_hits_lists[iNode]; int iHit; for (iHit = 0; iHit < nCheck && iHit < lNode->nHits; iHit++) { besthit_t bh = HitToBestHit(iNode, lNode->hits[iHit]); SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bh); top_hits_list_t *lTarget = &tophits->top_hits_lists[bh.j]; /* If this criterion is worse than the nCheck-1 entry of the target, then skip the check. This logic is based on assuming that the list is sorted, which is true initially but may not be true later. Still, is a good heuristic. */ assert(nCheck > 0); assert(nCheck <= lTarget->nHits); besthit_t bhCheck = HitToBestHit(bh.j, lTarget->hits[nCheck-1]); SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bhCheck); if (bhCheck.criterion < bh.criterion) continue; /* no check needed */ /* Check if this is present in the top-hit list */ int iHit2; bool bFound = false; for (iHit2 = 0; iHit2 < lTarget->nHits && !bFound; iHit2++) if (lTarget->hits[iHit2].j == iNode) bFound = true; if (!bFound) { /* Find the hit with the worst criterion and replace it with this one */ int iWorst = -1; double dWorstCriterion = -1e20; for (iHit2 = 0; iHit2 < lTarget->nHits; iHit2++) { besthit_t bh2 = HitToBestHit(bh.j, lTarget->hits[iHit2]); SetCriterion(NJ, /*nActive*/NJ->nSeq, /*IN/OUT*/&bh2); if (bh2.criterion > dWorstCriterion) { iWorst = iHit2; dWorstCriterion = bh2.criterion; } } if (dWorstCriterion > bh.criterion) { assert(iWorst >= 0); lTarget->hits[iWorst].j = iNode; lTarget->hits[iWorst].dist = bh.dist; lReplace++; /* and perhaps update visible */ besthit_t v; bool bSuccess = GetVisible(NJ, /*nActive*/NJ->nSeq, tophits, bh.j, /*OUT*/&v); assert(bSuccess); if (bh.criterion < v.criterion) tophits->visible[bh.j] = lTarget->hits[iWorst]; } } } } if (verbose >= 2) fprintf(stderr, "Replaced %ld top hit entries\n", lReplace); } /* Updates out-distances but does not reset or update visible set */ void GetBestFromTopHits(int iNode, /*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN*/top_hits_t *tophits, /*OUT*/besthit_t *bestjoin) { assert(iNode >= 0); assert(NJ->parent[iNode] < 0); top_hits_list_t *l = &tophits->top_hits_lists[iNode]; assert(l->nHits > 0); assert(l->hits != NULL); if(!fastest) SetOutDistance(NJ, iNode, nActive); /* ensure out-distances are not stale */ bestjoin->i = -1; bestjoin->j = -1; bestjoin->dist = 1e20; bestjoin->criterion = 1e20; int iBest; for(iBest=0; iBest < l->nHits; iBest++) { besthit_t bh = HitToBestHit(iNode, l->hits[iBest]); if (UpdateBestHit(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&bh, /*update dist*/true)) { SetCriterion(/*IN/OUT*/NJ, nActive, /*IN/OUT*/&bh); /* make sure criterion is correct */ if (bh.criterion < bestjoin->criterion) *bestjoin = bh; } } assert(bestjoin->j >= 0); /* a hit was found */ assert(bestjoin->i == iNode); } int ActiveAncestor(/*IN*/NJ_t *NJ, int iNode) { if (iNode < 0) return(iNode); while(NJ->parent[iNode] >= 0) iNode = NJ->parent[iNode]; return(iNode); } bool UpdateBestHit(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/besthit_t *hit, bool bUpdateDist) { int i = ActiveAncestor(/*IN*/NJ, hit->i); int j = ActiveAncestor(/*IN*/NJ, hit->j); if (i < 0 || j < 0 || i == j) { hit->i = -1; hit->j = -1; hit->weight = 0; hit->dist = 1e20; hit->criterion = 1e20; return(false); } if (i != hit->i || j != hit->j) { hit->i = i; hit->j = j; if (bUpdateDist) { SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit); } else { hit->dist = -1e20; hit->criterion = 1e20; } } return(true); } bool GetVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits, int iNode, /*OUT*/besthit_t *visible) { if (iNode < 0 || NJ->parent[iNode] >= 0) return(false); hit_t *v = &tophits->visible[iNode]; if (v->j < 0 || NJ->parent[v->j] >= 0) return(false); *visible = HitToBestHit(iNode, *v); SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/visible); return(true); } besthit_t *UniqueBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/SORT*/besthit_t *combined, int nCombined, /*OUT*/int *nUniqueOut) { int iHit; for (iHit = 0; iHit < nCombined; iHit++) { besthit_t *hit = &combined[iHit]; UpdateBestHit(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit, /*update*/false); } qsort(/*IN/OUT*/combined, nCombined, sizeof(besthit_t), CompareHitsByIJ); besthit_t *uniqueList = (besthit_t*)mymalloc(sizeof(besthit_t)*nCombined); int nUnique = 0; int iSavedLast = -1; /* First build the new list */ for (iHit = 0; iHit < nCombined; iHit++) { besthit_t *hit = &combined[iHit]; if (hit->i < 0 || hit->j < 0) continue; if (iSavedLast >= 0) { /* toss out duplicates */ besthit_t *saved = &combined[iSavedLast]; if (saved->i == hit->i && saved->j == hit->j) continue; } assert(nUnique < nCombined); assert(hit->j >= 0 && NJ->parent[hit->j] < 0); uniqueList[nUnique++] = *hit; iSavedLast = iHit; } *nUniqueOut = nUnique; /* Then do any updates to the criterion or the distances in parallel */ #ifdef OPENMP #pragma omp parallel for schedule(dynamic, 50) #endif for (iHit = 0; iHit < nUnique; iHit++) { besthit_t *hit = &uniqueList[iHit]; if (hit->dist < 0.0) SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit); else SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/hit); } return(uniqueList); } /* Create a top hit list for the new node, either from children (if there are enough best hits left) or by a "refresh" Also set visible set for newnode Also update visible set for other nodes if we stumble across a "better" hit */ void TopHitJoin(int newnode, /*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits) { long startProfileOps = profileOps; long startOutProfileOps = outprofileOps; assert(NJ->child[newnode].nChild == 2); top_hits_list_t *lNew = &tophits->top_hits_lists[newnode]; assert(lNew->hits == NULL); /* Copy the hits */ int i; top_hits_list_t *lChild[2]; for (i = 0; i< 2; i++) { lChild[i] = &tophits->top_hits_lists[NJ->child[newnode].child[i]]; assert(lChild[i]->hits != NULL && lChild[i]->nHits > 0); } int nCombined = lChild[0]->nHits + lChild[1]->nHits; besthit_t *combinedList = (besthit_t*)mymalloc(sizeof(besthit_t)*nCombined); HitsToBestHits(lChild[0]->hits, lChild[0]->nHits, NJ->child[newnode].child[0], /*OUT*/combinedList); HitsToBestHits(lChild[1]->hits, lChild[1]->nHits, NJ->child[newnode].child[1], /*OUT*/combinedList + lChild[0]->nHits); int nUnique; /* UniqueBestHits() replaces children (used in the calls to HitsToBestHits) with active ancestors, so all distances & criteria will be recomputed */ besthit_t *uniqueList = UniqueBestHits(/*IN/UPDATE*/NJ, nActive, /*IN/SORT*/combinedList, nCombined, /*OUT*/&nUnique); int nUniqueAlloc = nCombined; combinedList = myfree(combinedList, sizeof(besthit_t)*nCombined); /* Forget the top-hit lists of the joined nodes */ for (i = 0; i < 2; i++) { lChild[i]->hits = myfree(lChild[i]->hits, sizeof(hit_t) * lChild[i]->nHits); lChild[i]->nHits = 0; } /* Use the average age, rounded up, by 1 Versions 2.0 and earlier used the maximum age, which leads to more refreshes without improving the accuracy of the NJ phase. Intuitively, if one of them was just refreshed then another refresh is unlikely to help. */ lNew->age = (lChild[0]->age+lChild[1]->age+1)/2 + 1; /* If top hit ages always match (perfectly balanced), then a limit of log2(m) would mean a refresh after m joins, which is about what we want. */ int tophitAgeLimit = MAX(1, (int)(0.5 + log((double)tophits->m)/log(2.0))); /* Either use the merged list as candidate top hits, or move from 2nd level to 1st level, or do a refresh UniqueBestHits eliminates hits to self, so if nUnique==nActive-1, we've already done the exhaustive search. Either way, we set tophits, visible(newnode), update visible of its top hits, and modify topvisible: if we do a refresh, then we reset it, otherwise we update */ bool bSecondLevel = lChild[0]->hitSource >= 0 && lChild[1]->hitSource >= 0; bool bUseUnique = nUnique==nActive-1 || (lNew->age <= tophitAgeLimit && nUnique >= (bSecondLevel ? (int)(0.5 + tophits2Refresh * tophits->q) : (int)(0.5 + tophits->m * tophitsRefresh) )); if (bUseUnique && verbose > 2) fprintf(stderr,"Top hits for %d from combined %d nActive=%d tophitsage %d %s\n", newnode,nUnique,nActive,lNew->age, bSecondLevel ? "2ndlevel" : "1stlevel"); if (!bUseUnique && bSecondLevel && lNew->age <= tophitAgeLimit) { int source = ActiveAncestor(NJ, lChild[0]->hitSource); if (source == newnode) source = ActiveAncestor(NJ, lChild[1]->hitSource); /* In parallel mode, it is possible that we would select a node as the hit-source and then over-write that top hit with a short list. So we need this sanity check. */ if (source != newnode && source >= 0 && tophits->top_hits_lists[source].hitSource < 0) { /* switch from 2nd-level to 1st-level top hits -- compute top hits list of node from what we have so far plus the active source plus its top hits */ top_hits_list_t *lSource = &tophits->top_hits_lists[source]; assert(lSource->hitSource < 0); assert(lSource->nHits > 0); int nMerge = 1 + lSource->nHits + nUnique; besthit_t *mergeList = mymalloc(sizeof(besthit_t) * nMerge); memcpy(/*to*/mergeList, /*from*/uniqueList, nUnique * sizeof(besthit_t)); int iMerge = nUnique; mergeList[iMerge].i = newnode; mergeList[iMerge].j = source; SetDistCriterion(NJ, nActive, /*IN/OUT*/&mergeList[iMerge]); iMerge++; HitsToBestHits(lSource->hits, lSource->nHits, newnode, /*OUT*/mergeList+iMerge); for (i = 0; i < lSource->nHits; i++) { SetDistCriterion(NJ, nActive, /*IN/OUT*/&mergeList[iMerge]); iMerge++; } assert(iMerge == nMerge); uniqueList = myfree(uniqueList, nUniqueAlloc * sizeof(besthit_t)); uniqueList = UniqueBestHits(/*IN/UPDATE*/NJ, nActive, /*IN/SORT*/mergeList, nMerge, /*OUT*/&nUnique); nUniqueAlloc = nMerge; mergeList = myfree(mergeList, sizeof(besthit_t)*nMerge); assert(nUnique > 0); bUseUnique = nUnique >= (int)(0.5 + tophits->m * tophitsRefresh); bSecondLevel = false; if (bUseUnique && verbose > 2) fprintf(stderr, "Top hits for %d from children and source %d's %d hits, nUnique %d\n", newnode, source, lSource->nHits, nUnique); } } if (bUseUnique) { if (bSecondLevel) { /* pick arbitrarily */ lNew->hitSource = lChild[0]->hitSource; } int nSave = MIN(nUnique, bSecondLevel ? tophits->q : tophits->m); assert(nSave>0); if (verbose > 2) fprintf(stderr, "Combined %d ops so far %ld\n", nUnique, profileOps - startProfileOps); SortSaveBestHits(newnode, /*IN/SORT*/uniqueList, /*nIn*/nUnique, /*nOut*/nSave, /*IN/OUT*/tophits); assert(lNew->hits != NULL); /* set by sort/save */ tophits->visible[newnode] = lNew->hits[0]; UpdateTopVisible(/*IN*/NJ, nActive, newnode, &tophits->visible[newnode], /*IN/OUT*/tophits); UpdateVisible(/*IN/UPDATE*/NJ, nActive, /*IN*/uniqueList, nSave, /*IN/OUT*/tophits); } else { /* need to refresh: set top hits for node and for its top hits */ if(verbose > 2) fprintf(stderr,"Top hits for %d by refresh (%d unique age %d) nActive=%d\n", newnode,nUnique,lNew->age,nActive); nRefreshTopHits++; lNew->age = 0; int iNode; /* ensure all out-distances are up to date ahead of time to avoid any data overwriting issues. */ #ifdef OPENMP #pragma omp parallel for schedule(dynamic, 50) #endif for (iNode = 0; iNode < NJ->maxnode; iNode++) { if (NJ->parent[iNode] < 0) { if (fastest) { besthit_t bh; bh.i = iNode; bh.j = iNode; bh.dist = 0; SetCriterion(/*IN/UPDATE*/NJ, nActive, &bh); } else { SetOutDistance(/*IN/UDPATE*/NJ, iNode, nActive); } } } /* exhaustively get the best 2*m hits for newnode, set visible, and save the top m */ besthit_t *allhits = (besthit_t*)mymalloc(sizeof(besthit_t)*NJ->maxnode); assert(2 * tophits->m <= NJ->maxnode); besthit_t bh; SetBestHit(newnode, NJ, nActive, /*OUT*/&bh, /*OUT*/allhits); qsort(/*IN/OUT*/allhits, NJ->maxnode, sizeof(besthit_t), CompareHitsByCriterion); SortSaveBestHits(newnode, /*IN/SORT*/allhits, /*nIn*/NJ->maxnode, /*nOut*/tophits->m, /*IN/OUT*/tophits); /* Do not need to call UpdateVisible because we set visible below */ /* And use the top 2*m entries to expand other best-hit lists, but only for top m */ int iHit; #ifdef OPENMP #pragma omp parallel for schedule(dynamic, 50) #endif for (iHit=0; iHit < tophits->m; iHit++) { if (allhits[iHit].i < 0) continue; int iNode = allhits[iHit].j; assert(iNode>=0); if (NJ->parent[iNode] >= 0) continue; top_hits_list_t *l = &tophits->top_hits_lists[iNode]; int nHitsOld = l->nHits; assert(nHitsOld <= tophits->m); l->age = 0; /* Merge: old hits into 0->nHitsOld and hits from iNode above that */ besthit_t *bothList = (besthit_t*)mymalloc(sizeof(besthit_t) * 3 * tophits->m); HitsToBestHits(/*IN*/l->hits, nHitsOld, iNode, /*OUT*/bothList); /* does not compute criterion */ for (i = 0; i < nHitsOld; i++) SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&bothList[i]); if (nActive <= 2 * tophits->m) l->hitSource = -1; /* abandon the 2nd-level top-hits heuristic */ int nNewHits = l->hitSource >= 0 ? tophits->q : tophits->m; assert(nNewHits > 0); TransferBestHits(/*IN/UPDATE*/NJ, nActive, iNode, /*IN*/allhits, /*nOldHits*/2 * nNewHits, /*OUT*/&bothList[nHitsOld], /*updateDist*/false); /* rely on UniqueBestHits to update dist and/or criterion */ int nUnique2; besthit_t *uniqueList2 = UniqueBestHits(/*IN/UPDATE*/NJ, nActive, /*IN/SORT*/bothList, nHitsOld + 2 * nNewHits, /*OUT*/&nUnique2); assert(nUnique2 > 0); bothList = myfree(bothList,3 * tophits->m * sizeof(besthit_t)); /* Note this will overwrite l, but we saved nHitsOld */ SortSaveBestHits(iNode, /*IN/SORT*/uniqueList2, /*nIn*/nUnique2, /*nOut*/nNewHits, /*IN/OUT*/tophits); /* will update topvisible below */ tophits->visible[iNode] = tophits->top_hits_lists[iNode].hits[0]; uniqueList2 = myfree(uniqueList2, (nHitsOld + 2 * tophits->m) * sizeof(besthit_t)); } ResetTopVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits); /* outside of the parallel phase */ allhits = myfree(allhits,sizeof(besthit_t)*NJ->maxnode); } uniqueList = myfree(uniqueList, nUniqueAlloc * sizeof(besthit_t)); if (verbose > 2) { fprintf(stderr, "New top-hit list for %d profile-ops %ld (out-ops %ld): source %d age %d members ", newnode, profileOps - startProfileOps, outprofileOps - startOutProfileOps, lNew->hitSource, lNew->age); int i; for (i = 0; i < lNew->nHits; i++) fprintf(stderr, " %d", lNew->hits[i].j); fprintf(stderr,"\n"); } } void UpdateVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN*/besthit_t *tophitsNode, int nTopHits, /*IN/OUT*/top_hits_t *tophits) { int iHit; for(iHit = 0; iHit < nTopHits; iHit++) { besthit_t *hit = &tophitsNode[iHit]; if (hit->i < 0) continue; /* possible empty entries */ assert(NJ->parent[hit->i] < 0); assert(hit->j >= 0 && NJ->parent[hit->j] < 0); besthit_t visible; bool bSuccess = GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, hit->j, /*OUT*/&visible); if (!bSuccess || hit->criterion < visible.criterion) { if (bSuccess) nVisibleUpdate++; hit_t *v = &tophits->visible[hit->j]; v->j = hit->i; v->dist = hit->dist; UpdateTopVisible(NJ, nActive, hit->j, v, /*IN/OUT*/tophits); if(verbose>5) fprintf(stderr,"NewVisible %d %d %f\n", hit->j,v->j,v->dist); } } /* end loop over hits */ } /* Update the top-visible list to perhaps include visible[iNode] */ void UpdateTopVisible(/*IN*/NJ_t * NJ, int nActive, int iIn, /*IN*/hit_t *hit, /*IN/OUT*/top_hits_t *tophits) { assert(tophits != NULL); bool bIn = false; /* placed in the list */ int i; /* First, if the list is not full, put it in somewhere */ for (i = 0; i < tophits->nTopVisible && !bIn; i++) { int iNode = tophits->topvisible[i]; if (iNode == iIn) { /* this node is already in the top hit list */ bIn = true; } else if (iNode < 0 || NJ->parent[iNode] >= 0) { /* found an empty spot */ bIn = true; tophits->topvisible[i] = iIn; } } int iPosWorst = -1; double dCriterionWorst = -1e20; if (!bIn) { /* Search for the worst hit */ for (i = 0; i < tophits->nTopVisible && !bIn; i++) { int iNode = tophits->topvisible[i]; assert(iNode >= 0 && NJ->parent[iNode] < 0 && iNode != iIn); besthit_t visible; if (!GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&visible)) { /* found an empty spot */ tophits->topvisible[i] = iIn; bIn = true; } else if (visible.i == hit->j && visible.j == iIn) { /* the reverse hit is already in the top hit list */ bIn = true; } else if (visible.criterion >= dCriterionWorst) { iPosWorst = i; dCriterionWorst = visible.criterion; } } } if (!bIn && iPosWorst >= 0) { besthit_t visible = HitToBestHit(iIn, *hit); SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/&visible); if (visible.criterion < dCriterionWorst) { if (verbose > 2) { int iOld = tophits->topvisible[iPosWorst]; fprintf(stderr, "TopVisible replace %d=>%d with %d=>%d\n", iOld, tophits->visible[iOld].j, visible.i, visible.j); } tophits->topvisible[iPosWorst] = iIn; } } if (verbose > 2) { fprintf(stderr, "Updated TopVisible: "); for (i = 0; i < tophits->nTopVisible; i++) { int iNode = tophits->topvisible[i]; if (iNode >= 0 && NJ->parent[iNode] < 0) { besthit_t bh = HitToBestHit(iNode, tophits->visible[iNode]); SetDistCriterion(NJ, nActive, &bh); fprintf(stderr, " %d=>%d:%.4f", bh.i, bh.j, bh.criterion); } } fprintf(stderr,"\n"); } } /* Recompute the topvisible list */ void ResetTopVisible(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits) { besthit_t *visibleSorted = mymalloc(sizeof(besthit_t)*nActive); int nVisible = 0; /* #entries in visibleSorted */ int iNode; for (iNode = 0; iNode < NJ->maxnode; iNode++) { /* skip joins involving stale nodes */ if (NJ->parent[iNode] >= 0) continue; besthit_t v; if (GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&v)) { assert(nVisible < nActive); visibleSorted[nVisible++] = v; } } assert(nVisible > 0); qsort(/*IN/OUT*/visibleSorted,nVisible,sizeof(besthit_t),CompareHitsByCriterion); /* Only keep the top m items, and try to avoid duplicating i->j with j->i Note that visible(i) -> j does not necessarily imply visible(j) -> i, so we store what the pairing was (or -1 for not used yet) */ int *inTopVisible = malloc(sizeof(int) * NJ->maxnodes); int i; for (i = 0; i < NJ->maxnodes; i++) inTopVisible[i] = -1; if (verbose > 2) fprintf(stderr, "top-hit search: nActive %d nVisible %d considering up to %d items\n", nActive, nVisible, tophits->m); /* save the sorted indices in topvisible */ int iSave = 0; for (i = 0; i < nVisible && iSave < tophits->nTopVisible; i++) { besthit_t *v = &visibleSorted[i]; if (inTopVisible[v->i] != v->j) { /* not seen already */ tophits->topvisible[iSave++] = v->i; inTopVisible[v->i] = v->j; inTopVisible[v->j] = v->i; } } while(iSave < tophits->nTopVisible) tophits->topvisible[iSave++] = -1; myfree(visibleSorted, sizeof(besthit_t)*nActive); myfree(inTopVisible, sizeof(int) * NJ->maxnodes); tophits->topvisibleAge = 0; if (verbose > 2) { fprintf(stderr, "Reset TopVisible: "); for (i = 0; i < tophits->nTopVisible; i++) { int iNode = tophits->topvisible[i]; if (iNode < 0) break; fprintf(stderr, " %d=>%d", iNode, tophits->visible[iNode].j); } fprintf(stderr,"\n"); } } /* Find best hit to do in O(N*log(N) + m*L*log(N)) time, by copying and sorting the visible list updating out-distances for the top (up to m) candidates selecting the best hit if !fastest then local hill-climbing for a better join, using best-hit lists only, and updating all out-distances in every best-hit list */ void TopHitNJSearch(/*IN/UPDATE*/NJ_t *NJ, int nActive, /*IN/OUT*/top_hits_t *tophits, /*OUT*/besthit_t *join) { /* first, do we have at least m/2 candidates in topvisible? And remember the best one */ int nCandidate = 0; int iNodeBestCandidate = -1; double dBestCriterion = 1e20; int i; for (i = 0; i < tophits->nTopVisible; i++) { int iNode = tophits->topvisible[i]; besthit_t visible; if (GetVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits, iNode, /*OUT*/&visible)) { nCandidate++; if (iNodeBestCandidate < 0 || visible.criterion < dBestCriterion) { iNodeBestCandidate = iNode; dBestCriterion = visible.criterion; } } } tophits->topvisibleAge++; /* Note we may have only nActive/2 joins b/c we try to store them once */ if (2 * tophits->topvisibleAge > tophits->m || (3*nCandidate < tophits->nTopVisible && 3*nCandidate < nActive)) { /* recompute top visible */ if (verbose > 2) fprintf(stderr, "Resetting the top-visible list at nActive=%d\n",nActive); /* If age is low, then our visible set is becoming too sparse, because we have recently recomputed the top visible subset. This is very rare but can happen with -fastest. A quick-and-dirty solution is to walk up the parents to get additional entries in top hit lists. To ensure that the visible set becomes full, pick an arbitrary node if walking up terminates at self. */ if (tophits->topvisibleAge <= 2) { if (verbose > 2) fprintf(stderr, "Expanding visible set by walking up to active nodes at nActive=%d\n", nActive); int iNode; for (iNode = 0; iNode < NJ->maxnode; iNode++) { if (NJ->parent[iNode] >= 0) continue; hit_t *v = &tophits->visible[iNode]; int newj = ActiveAncestor(NJ, v->j); if (newj >= 0 && newj != v->j) { if (newj == iNode) { /* pick arbitrarily */ newj = 0; while (NJ->parent[newj] >= 0 || newj == iNode) newj++; } assert(newj >= 0 && newj < NJ->maxnodes && newj != iNode && NJ->parent[newj] < 0); /* Set v to point to newj */ besthit_t bh = { iNode, newj, -1e20, -1e20, -1e20 }; SetDistCriterion(NJ, nActive, /*IN/OUT*/&bh); v->j = newj; v->dist = bh.dist; } } } ResetTopVisible(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/tophits); /* and recurse to try again */ TopHitNJSearch(NJ, nActive, tophits, join); return; } if (verbose > 2) fprintf(stderr, "Top-visible list size %d (nActive %d m %d)\n", nCandidate, nActive, tophits->m); assert(iNodeBestCandidate >= 0 && NJ->parent[iNodeBestCandidate] < 0); bool bSuccess = GetVisible(NJ, nActive, tophits, iNodeBestCandidate, /*OUT*/join); assert(bSuccess); assert(join->i >= 0 && NJ->parent[join->i] < 0); assert(join->j >= 0 && NJ->parent[join->j] < 0); if(fastest) return; int changed; do { changed = 0; besthit_t bestI; GetBestFromTopHits(join->i, NJ, nActive, tophits, /*OUT*/&bestI); assert(bestI.i == join->i); if (bestI.j != join->j && bestI.criterion < join->criterion) { changed = 1; if (verbose>2) fprintf(stderr,"BetterI\t%d\t%d\t%d\t%d\t%f\t%f\n", join->i,join->j,bestI.i,bestI.j, join->criterion,bestI.criterion); *join = bestI; } besthit_t bestJ; GetBestFromTopHits(join->j, NJ, nActive, tophits, /*OUT*/&bestJ); assert(bestJ.i == join->j); if (bestJ.j != join->i && bestJ.criterion < join->criterion) { changed = 1; if (verbose>2) fprintf(stderr,"BetterJ\t%d\t%d\t%d\t%d\t%f\t%f\n", join->i,join->j,bestJ.i,bestJ.j, join->criterion,bestJ.criterion); *join = bestJ; } if(changed) nHillBetter++; } while(changed); } int NGaps(/*IN*/NJ_t *NJ, int iNode) { assert(iNode < NJ->nSeq); int nGaps = 0; int p; for(p=0; p<NJ->nPos; p++) { if (NJ->profiles[iNode]->codes[p] == NOCODE) nGaps++; } return(nGaps); } int CompareHitsByCriterion(const void *c1, const void *c2) { const besthit_t *hit1 = (besthit_t*)c1; const besthit_t *hit2 = (besthit_t*)c2; if (hit1->criterion < hit2->criterion) return(-1); if (hit1->criterion > hit2->criterion) return(1); return(0); } int CompareHitsByIJ(const void *c1, const void *c2) { const besthit_t *hit1 = (besthit_t*)c1; const besthit_t *hit2 = (besthit_t*)c2; return hit1->i != hit2->i ? hit1->i - hit2->i : hit1->j - hit2->j; } void SortSaveBestHits(int iNode, /*IN/SORT*/besthit_t *besthits, int nIn, int nOut, /*IN/OUT*/top_hits_t *tophits) { assert(nIn > 0); assert(nOut > 0); top_hits_list_t *l = &tophits->top_hits_lists[iNode]; /* */ qsort(/*IN/OUT*/besthits,nIn,sizeof(besthit_t),CompareHitsByCriterion); /* First count how many we will save Not sure if removing duplicates is actually necessary. */ int nSave = 0; int jLast = -1; int iBest; for (iBest = 0; iBest < nIn && nSave < nOut; iBest++) { if (besthits[iBest].i < 0) continue; assert(besthits[iBest].i == iNode); int j = besthits[iBest].j; if (j != iNode && j != jLast && j >= 0) { nSave++; jLast = j; } } assert(nSave > 0); #ifdef OPENMP omp_set_lock(&tophits->locks[iNode]); #endif if (l->hits != NULL) { l->hits = myfree(l->hits, l->nHits * sizeof(hit_t)); l->nHits = 0; } l->hits = mymalloc(sizeof(hit_t) * nSave); l->nHits = nSave; int iSave = 0; jLast = -1; for (iBest = 0; iBest < nIn && iSave < nSave; iBest++) { int j = besthits[iBest].j; if (j != iNode && j != jLast && j >= 0) { l->hits[iSave].j = j; l->hits[iSave].dist = besthits[iBest].dist; iSave++; jLast = j; } } #ifdef OPENMP omp_unset_lock(&tophits->locks[iNode]); #endif assert(iSave == nSave); } void TransferBestHits(/*IN/UPDATE*/NJ_t *NJ, int nActive, int iNode, /*IN*/besthit_t *oldhits, int nOldHits, /*OUT*/besthit_t *newhits, bool updateDistances) { assert(iNode >= 0); assert(NJ->parent[iNode] < 0); int iBest; for(iBest = 0; iBest < nOldHits; iBest++) { besthit_t *old = &oldhits[iBest]; besthit_t *new = &newhits[iBest]; new->i = iNode; new->j = ActiveAncestor(/*IN*/NJ, old->j); new->dist = old->dist; /* may get reset below */ new->weight = old->weight; new->criterion = old->criterion; if(new->j < 0 || new->j == iNode) { new->weight = 0; new->dist = -1e20; new->criterion = 1e20; } else if (new->i != old->i || new->j != old->j) { if (updateDistances) SetDistCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/new); else { new->dist = -1e20; new->criterion = 1e20; } } else { if (updateDistances) SetCriterion(/*IN/UPDATE*/NJ, nActive, /*IN/OUT*/new); else new->criterion = 1e20; /* leave dist alone */ } } } void HitsToBestHits(/*IN*/hit_t *hits, int nHits, int iNode, /*OUT*/besthit_t *newhits) { int i; for (i = 0; i < nHits; i++) { hit_t *hit = &hits[i]; besthit_t *bh = &newhits[i]; bh->i = iNode; bh->j = hit->j; bh->dist = hit->dist; bh->criterion = 1e20; bh->weight = -1; /* not the true value -- we compute these directly when needed */ } } besthit_t HitToBestHit(int i, hit_t hit) { besthit_t bh; bh.i = i; bh.j = hit.j; bh.dist = hit.dist; bh.criterion = 1e20; bh.weight = -1; return(bh); } char *OpenMPString(void) { #ifdef OPENMP static char buf[100]; sprintf(buf, ", OpenMP (%d threads)", omp_get_max_threads()); return(buf); #else return(""); #endif } /* Algorithm 26.2.17 from Abromowitz and Stegun, Handbook of Mathematical Functions Absolute accuracy of only about 1e-7, which is enough for us */ double pnorm(double x) { double b1 = 0.319381530; double b2 = -0.356563782; double b3 = 1.781477937; double b4 = -1.821255978; double b5 = 1.330274429; double p = 0.2316419; double c = 0.39894228; if(x >= 0.0) { double t = 1.0 / ( 1.0 + p * x ); return (1.0 - c * exp( -x * x / 2.0 ) * t * ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 )); } /*else*/ double t = 1.0 / ( 1.0 - p * x ); return ( c * exp( -x * x / 2.0 ) * t * ( t *( t * ( t * ( t * b5 + b4 ) + b3 ) + b2 ) + b1 )); } void *mymalloc(size_t sz) { if (sz == 0) return(NULL); void *new = malloc(sz); if (new == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } szAllAlloc += sz; mymallocUsed += sz; #ifdef TRACK_MEMORY struct mallinfo mi = mallinfo(); if (mi.arena+mi.hblkhd > maxmallocHeap) maxmallocHeap = mi.arena+mi.hblkhd; #endif /* gcc malloc should always return 16-byte-aligned values... */ assert(IS_ALIGNED(new)); return (new); } void *mymemdup(void *data, size_t sz) { if(data==NULL) return(NULL); void *new = mymalloc(sz); memcpy(/*to*/new, /*from*/data, sz); return(new); } void *myrealloc(void *data, size_t szOld, size_t szNew, bool bCopy) { if (data == NULL && szOld == 0) return(mymalloc(szNew)); if (data == NULL || szOld == 0 || szNew == 0) { fprintf(stderr,"Empty myrealloc\n"); exit(1); } if (szOld == szNew) return(data); void *new = NULL; if (bCopy) { /* Try to reduce memory fragmentation by allocating anew and copying Seems to help in practice */ new = mymemdup(data, szNew); myfree(data, szOld); } else { new = realloc(data,szNew); if (new == NULL) { fprintf(stderr, "Out of memory\n"); exit(1); } assert(IS_ALIGNED(new)); szAllAlloc += (szNew-szOld); mymallocUsed += (szNew-szOld); #ifdef TRACK_MEMORY struct mallinfo mi = mallinfo(); if (mi.arena+mi.hblkhd > maxmallocHeap) maxmallocHeap = mi.arena+mi.hblkhd; #endif } return(new); } void *myfree(void *p, size_t sz) { if(p==NULL) return(NULL); free(p); mymallocUsed -= sz; return(NULL); } /******************************************************************************/ /* Minimization of a 1-dimensional function by Brent's method (Numerical Recipes) * Borrowed from Tree-Puzzle 5.1 util.c under GPL * Modified by M.N.P to pass in the accessory data for the optimization function, * to use 2x bounds around the starting guess and expand them if necessary, * and to use both a fractional and an absolute tolerance */ #define ITMAX 100 #define CGOLD 0.3819660 #define TINY 1.0e-20 #define ZEPS 1.0e-10 #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); #define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) /* Brents method in one dimension */ double brent(double ax, double bx, double cx, double (*f)(double, void *), void *data, double ftol, double atol, double *foptx, double *f2optx, double fax, double fbx, double fcx) { int iter; double a,b,d=0,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; double xw,wv,vx; double e=0.0; a=(ax < cx ? ax : cx); b=(ax > cx ? ax : cx); x=bx; fx=fbx; if (fax < fcx) { w=ax; fw=fax; v=cx; fv=fcx; } else { w=cx; fw=fcx; v=ax; fv=fax; } for (iter=1;iter<=ITMAX;iter++) { xm=0.5*(a+b); tol1=ftol*fabs(x); tol2=2.0*(tol1+ZEPS); if (fabs(x-xm) <= (tol2-0.5*(b-a)) || fabs(a-b) < atol) { *foptx = fx; xw = x-w; wv = w-v; vx = v-x; *f2optx = 2.0*(fv*xw + fx*wv + fw*vx)/ (v*v*xw + x*x*wv + w*w*vx); return x; } if (fabs(e) > tol1) { r=(x-w)*(fx-fv); q=(x-v)*(fx-fw); p=(x-v)*q-(x-w)*r; q=2.0*(q-r); if (q > 0.0) p = -p; q=fabs(q); etemp=e; e=d; if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) d=CGOLD*(e=(x >= xm ? a-x : b-x)); else { d=p/q; u=x+d; if (u-a < tol2 || b-u < tol2) d=SIGN(tol1,xm-x); } } else { d=CGOLD*(e=(x >= xm ? a-x : b-x)); } u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); fu=(*f)(u,data); if (fu <= fx) { if (u >= x) a=x; else b=x; SHFT(v,w,x,u) SHFT(fv,fw,fx,fu) } else { if (u < x) a=u; else b=u; if (fu <= fw || w == x) { v=w; w=u; fv=fw; fw=fu; } else if (fu <= fv || v == x || v == w) { v=u; fv=fu; } } } *foptx = fx; xw = x-w; wv = w-v; vx = v-x; *f2optx = 2.0*(fv*xw + fx*wv + fw*vx)/ (v*v*xw + x*x*wv + w*w*vx); return x; } /* brent */ #undef ITMAX #undef CGOLD #undef ZEPS #undef SHFT #undef SIGN /* one-dimensional minimization - as input a lower and an upper limit and a trial value for the minimum is needed: xmin < xguess < xmax the function and a fractional tolerance has to be specified onedimenmin returns the optimal x value and the value of the function and its second derivative at this point */ double onedimenmin(double xmin, double xguess, double xmax, double (*f)(double,void*), void *data, double ftol, double atol, /*OUT*/double *fx, /*OUT*/double *f2x) { double optx, ax, bx, cx, fa, fb, fc; /* first attempt to bracketize minimum */ if (xguess == xmin) { ax = xmin; bx = 2.0*xguess; cx = 10.0*xguess; } else if (xguess <= 2.0 * xmin) { ax = xmin; bx = xguess; cx = 5.0*xguess; } else { ax = 0.5*xguess; bx = xguess; cx = 2.0*xguess; } if (cx > xmax) cx = xmax; if (bx >= cx) bx = 0.5*(ax+cx); if (verbose > 4) fprintf(stderr, "onedimenmin lo %.4f guess %.4f hi %.4f range %.4f %.4f\n", ax, bx, cx, xmin, xmax); /* ideally this range includes the true minimum, i.e., fb < fa and fb < fc if not, we gradually expand the boundaries until it does, or we near the boundary of the allowed range and use that */ fa = (*f)(ax,data); fb = (*f)(bx,data); fc = (*f)(cx,data); while(fa < fb && ax > xmin) { ax = (ax+xmin)/2.0; if (ax < 2.0*xmin) /* give up on shrinking the region */ ax = xmin; fa = (*f)(ax,data); } while(fc < fb && cx < xmax) { cx = (cx+xmax)/2.0; if (cx > xmax * 0.95) cx = xmax; fc = (*f)(cx,data); } optx = brent(ax, bx, cx, f, data, ftol, atol, fx, f2x, fa, fb, fc); if (verbose > 4) fprintf(stderr, "onedimenmin reaches optimum f(%.4f) = %.4f f2x %.4f\n", optx, *fx, *f2x); return optx; /* return optimal x */ } /* onedimenmin */ /* Numerical code for the gamma distribution is modified from the PhyML 3 code (GNU public license) of Stephane Guindon */ double LnGamma (double alpha) { /* returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places. Stirling's formula is used for the central polynomial part of the procedure. Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function. Communications of the Association for Computing Machinery, 9:684 */ double x=alpha, f=0, z; if (x<7) { f=1; z=x-1; while (++z<7) f*=z; x=z; f=-(double)log(f); } z = 1/(x*x); return f + (x-0.5)*(double)log(x) - x + .918938533204673 + (((-.000595238095238*z+.000793650793651)*z-.002777777777778)*z +.083333333333333)/x; } double IncompleteGamma(double x, double alpha, double ln_gamma_alpha) { /* returns the incomplete gamma ratio I(x,alpha) where x is the upper limit of the integration and alpha is the shape parameter. returns (-1) if in error ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant. (1) series expansion if (alpha>x || x<=1) (2) continued fraction otherwise RATNEST FORTRAN by Bhattacharjee GP (1970) The incomplete gamma integral. Applied Statistics, 19: 285-287 (AS32) */ int i; double p=alpha, g=ln_gamma_alpha; double accurate=1e-8, overflow=1e30; double factor, gin=0, rn=0, a=0,b=0,an=0,dif=0, term=0, pn[6]; if (x==0) return (0); if (x<0 || p<=0) return (-1); factor=(double)exp(p*(double)log(x)-x-g); if (x>1 && x>=p) goto l30; /* (1) series expansion */ gin=1; term=1; rn=p; l20: rn++; term*=x/rn; gin+=term; if (term > accurate) goto l20; gin*=factor/p; goto l50; l30: /* (2) continued fraction */ a=1-p; b=a+x+1; term=0; pn[0]=1; pn[1]=x; pn[2]=x+1; pn[3]=x*b; gin=pn[2]/pn[3]; l32: a++; b+=2; term++; an=a*term; for (i=0; i<2; i++) pn[i+4]=b*pn[i+2]-an*pn[i]; if (pn[5] == 0) goto l35; rn=pn[4]/pn[5]; dif=fabs(gin-rn); if (dif>accurate) goto l34; if (dif<=accurate*rn) goto l42; l34: gin=rn; l35: for (i=0; i<4; i++) pn[i]=pn[i+2]; if (fabs(pn[4]) < overflow) goto l32; for (i=0; i<4; i++) pn[i]/=overflow; goto l32; l42: gin=1-factor*gin; l50: return (gin); } double PGamma(double x, double alpha) { /* scale = 1/alpha */ return IncompleteGamma(x*alpha,alpha,LnGamma(alpha)); } /* helper function to subtract timval structures */ /* Subtract the `struct timeval' values X and Y, storing the result in RESULT. Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } double clockDiff(/*IN*/struct timeval *clock_start) { struct timeval time_now, elapsed; gettimeofday(/*OUT*/&time_now,NULL); timeval_subtract(/*OUT*/&elapsed,/*IN*/&time_now,/*IN*/clock_start); return(elapsed.tv_sec + elapsed.tv_usec*1e-6); } /* The random number generator is taken from D E Knuth http://www-cs-faculty.stanford.edu/~knuth/taocp.html */ /* This program by D E Knuth is in the public domain and freely copyable. * It is explained in Seminumerical Algorithms, 3rd edition, Section 3.6 * (or in the errata to the 2nd edition --- see * http://www-cs-faculty.stanford.edu/~knuth/taocp.html * in the changes to Volume 2 on pages 171 and following). */ /* N.B. The MODIFICATIONS introduced in the 9th printing (2002) are included here; there's no backwards compatibility with the original. */ /* This version also adopts Brendan McKay's suggestion to accommodate naive users who forget to call ran_start(seed). */ /* If you find any bugs, please report them immediately to * [email protected] * (and you will be rewarded if the bug is genuine). Thanks! */ /************ see the book for explanations and caveats! *******************/ /************ in particular, you need two's complement arithmetic **********/ #define KK 100 /* the long lag */ #define LL 37 /* the short lag */ #define MM (1L<<30) /* the modulus */ #define mod_diff(x,y) (((x)-(y))&(MM-1)) /* subtraction mod MM */ long ran_x[KK]; /* the generator state */ #ifdef __STDC__ void ran_array(long aa[],int n) #else void ran_array(aa,n) /* put n new random numbers in aa */ long *aa; /* destination */ int n; /* array length (must be at least KK) */ #endif { register int i,j; for (j=0;j<KK;j++) aa[j]=ran_x[j]; for (;j<n;j++) aa[j]=mod_diff(aa[j-KK],aa[j-LL]); for (i=0;i<LL;i++,j++) ran_x[i]=mod_diff(aa[j-KK],aa[j-LL]); for (;i<KK;i++,j++) ran_x[i]=mod_diff(aa[j-KK],ran_x[i-LL]); } /* the following routines are from exercise 3.6--15 */ /* after calling ran_start, get new randoms by, e.g., "x=ran_arr_next()" */ #define QUALITY 1009 /* recommended quality level for high-res use */ long ran_arr_buf[QUALITY]; long ran_arr_dummy=-1, ran_arr_started=-1; long *ran_arr_ptr=&ran_arr_dummy; /* the next random number, or -1 */ #define TT 70 /* guaranteed separation between streams */ #define is_odd(x) ((x)&1) /* units bit of x */ #ifdef __STDC__ void ran_start(long seed) #else void ran_start(seed) /* do this before using ran_array */ long seed; /* selector for different streams */ #endif { register int t,j; long x[KK+KK-1]; /* the preparation buffer */ register long ss=(seed+2)&(MM-2); for (j=0;j<KK;j++) { x[j]=ss; /* bootstrap the buffer */ ss<<=1; if (ss>=MM) ss-=MM-2; /* cyclic shift 29 bits */ } x[1]++; /* make x[1] (and only x[1]) odd */ for (ss=seed&(MM-1),t=TT-1; t; ) { for (j=KK-1;j>0;j--) x[j+j]=x[j], x[j+j-1]=0; /* "square" */ for (j=KK+KK-2;j>=KK;j--) x[j-(KK-LL)]=mod_diff(x[j-(KK-LL)],x[j]), x[j-KK]=mod_diff(x[j-KK],x[j]); if (is_odd(ss)) { /* "multiply by z" */ for (j=KK;j>0;j--) x[j]=x[j-1]; x[0]=x[KK]; /* shift the buffer cyclically */ x[LL]=mod_diff(x[LL],x[KK]); } if (ss) ss>>=1; else t--; } for (j=0;j<LL;j++) ran_x[j+KK-LL]=x[j]; for (;j<KK;j++) ran_x[j-LL]=x[j]; for (j=0;j<10;j++) ran_array(x,KK+KK-1); /* warm things up */ ran_arr_ptr=&ran_arr_started; } #define ran_arr_next() (*ran_arr_ptr>=0? *ran_arr_ptr++: ran_arr_cycle()) long ran_arr_cycle() { if (ran_arr_ptr==&ran_arr_dummy) ran_start(314159L); /* the user forgot to initialize */ ran_array(ran_arr_buf,QUALITY); ran_arr_buf[KK]=-1; ran_arr_ptr=ran_arr_buf+1; return ran_arr_buf[0]; } /* end of code from Knuth */ double knuth_rand() { return(9.31322574615479e-10 * ran_arr_next()); /* multiply by 2**-30 */ } hashstrings_t *MakeHashtable(char **strings, int nStrings) { hashstrings_t *hash = (hashstrings_t*)mymalloc(sizeof(hashstrings_t)); hash->nBuckets = 8*nStrings; hash->buckets = (hashbucket_t*)mymalloc(sizeof(hashbucket_t) * hash->nBuckets); int i; for (i=0; i < hash->nBuckets; i++) { hash->buckets[i].string = NULL; hash->buckets[i].nCount = 0; hash->buckets[i].first = -1; } for (i=0; i < nStrings; i++) { hashiterator_t hi = FindMatch(hash, strings[i]); if (hash->buckets[hi].string == NULL) { /* save a unique entry */ assert(hash->buckets[hi].nCount == 0); hash->buckets[hi].string = strings[i]; hash->buckets[hi].nCount = 1; hash->buckets[hi].first = i; } else { /* record a duplicate entry */ assert(hash->buckets[hi].string != NULL); assert(strcmp(hash->buckets[hi].string, strings[i]) == 0); assert(hash->buckets[hi].first >= 0); hash->buckets[hi].nCount++; } } return(hash); } hashstrings_t *FreeHashtable(hashstrings_t* hash) { if (hash != NULL) { myfree(hash->buckets, sizeof(hashbucket_t) * hash->nBuckets); myfree(hash, sizeof(hashstrings_t)); } return(NULL); } #define MAXADLER 65521 hashiterator_t FindMatch(hashstrings_t *hash, char *string) { /* Adler-32 checksum */ unsigned int hashA = 1; unsigned int hashB = 0; char *p; for (p = string; *p != '\0'; p++) { hashA = ((unsigned int)*p + hashA); hashB = hashA+hashB; } hashA %= MAXADLER; hashB %= MAXADLER; hashiterator_t hi = (hashB*65536+hashA) % hash->nBuckets; while(hash->buckets[hi].string != NULL && strcmp(hash->buckets[hi].string, string) != 0) { hi++; if (hi >= hash->nBuckets) hi = 0; } return(hi); } char *GetHashString(hashstrings_t *hash, hashiterator_t hi) { return(hash->buckets[hi].string); } int HashCount(hashstrings_t *hash, hashiterator_t hi) { return(hash->buckets[hi].nCount); } int HashFirst(hashstrings_t *hash, hashiterator_t hi) { return(hash->buckets[hi].first); } uniquify_t *UniquifyAln(alignment_t *aln) { int nUniqueSeq = 0; char **uniqueSeq = (char**)mymalloc(aln->nSeq * sizeof(char*)); /* iUnique -> seq */ int *uniqueFirst = (int*)mymalloc(aln->nSeq * sizeof(int)); /* iUnique -> iFirst in aln */ int *alnNext = (int*)mymalloc(aln->nSeq * sizeof(int)); /* i in aln -> next, or -1 */ int *alnToUniq = (int*)mymalloc(aln->nSeq * sizeof(int)); /* i in aln -> iUnique; many -> -1 */ int i; for (i = 0; i < aln->nSeq; i++) { uniqueSeq[i] = NULL; uniqueFirst[i] = -1; alnNext[i] = -1; alnToUniq[i] = -1; } hashstrings_t *hashseqs = MakeHashtable(aln->seqs, aln->nSeq); for (i=0; i<aln->nSeq; i++) { hashiterator_t hi = FindMatch(hashseqs,aln->seqs[i]); int first = HashFirst(hashseqs,hi); if (first == i) { uniqueSeq[nUniqueSeq] = aln->seqs[i]; uniqueFirst[nUniqueSeq] = i; alnToUniq[i] = nUniqueSeq; nUniqueSeq++; } else { int last = first; while (alnNext[last] != -1) last = alnNext[last]; assert(last>=0); alnNext[last] = i; assert(alnToUniq[last] >= 0 && alnToUniq[last] < nUniqueSeq); alnToUniq[i] = alnToUniq[last]; } } assert(nUniqueSeq>0); hashseqs = FreeHashtable(hashseqs); uniquify_t *uniquify = (uniquify_t*)mymalloc(sizeof(uniquify_t)); uniquify->nSeq = aln->nSeq; uniquify->nUnique = nUniqueSeq; uniquify->uniqueFirst = uniqueFirst; uniquify->alnNext = alnNext; uniquify->alnToUniq = alnToUniq; uniquify->uniqueSeq = uniqueSeq; return(uniquify); } uniquify_t *FreeUniquify(uniquify_t *unique) { if (unique != NULL) { myfree(unique->uniqueFirst, sizeof(int)*unique->nSeq); myfree(unique->alnNext, sizeof(int)*unique->nSeq); myfree(unique->alnToUniq, sizeof(int)*unique->nSeq); myfree(unique->uniqueSeq, sizeof(char*)*unique->nSeq); myfree(unique,sizeof(uniquify_t)); unique = NULL; } return(unique); } traversal_t InitTraversal(NJ_t *NJ) { traversal_t worked = (bool*)mymalloc(sizeof(bool)*NJ->maxnodes); int i; for (i=0; i<NJ->maxnodes; i++) worked[i] = false; return(worked); } void SkipTraversalInto(int node, /*IN/OUT*/traversal_t traversal) { traversal[node] = true; } int TraversePostorder(int node, NJ_t *NJ, /*IN/OUT*/traversal_t traversal, /*OPTIONAL OUT*/bool *pUp) { if (pUp) *pUp = false; while(1) { assert(node >= 0); /* move to a child if possible */ bool found = false; int iChild; for (iChild=0; iChild < NJ->child[node].nChild; iChild++) { int child = NJ->child[node].child[iChild]; if (!traversal[child]) { node = child; found = true; break; } } if (found) continue; /* keep moving down */ if (!traversal[node]) { traversal[node] = true; return(node); } /* If we've already done this node, need to move up */ if (node == NJ->root) return(-1); /* nowhere to go -- done traversing */ node = NJ->parent[node]; /* If we go up to someplace that was already marked as visited, this is due to a change in topology, so return it marked as "up" */ if (pUp && traversal[node]) { *pUp = true; return(node); } } } traversal_t FreeTraversal(traversal_t traversal, NJ_t *NJ) { myfree(traversal, sizeof(bool)*NJ->maxnodes); return(NULL); } profile_t **UpProfiles(NJ_t *NJ) { profile_t **upProfiles = (profile_t**)mymalloc(sizeof(profile_t*)*NJ->maxnodes); int i; for (i=0; i<NJ->maxnodes; i++) upProfiles[i] = NULL; return(upProfiles); } profile_t *GetUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int outnode, bool useML) { assert(outnode != NJ->root && outnode >= NJ->nSeq); /* not for root or leaves */ if (upProfiles[outnode] != NULL) return(upProfiles[outnode]); int depth; int *pathToRoot = PathToRoot(NJ, outnode, /*OUT*/&depth); int i; /* depth-1 is root */ for (i = depth-2; i>=0; i--) { int node = pathToRoot[i]; if (upProfiles[node] == NULL) { /* Note -- SetupABCD may call GetUpProfile, but it should do it farther up in the path to the root */ profile_t *profiles[4]; int nodeABCD[4]; SetupABCD(NJ, node, /*OUT*/profiles, /*IN/OUT*/upProfiles, /*OUT*/nodeABCD, useML); if (useML) { /* If node is a child of root, then the 4th profile is of the 2nd root-sibling of node Otherwise, the 4th profile is the up-profile of the parent of node, and that is the branch-length we need */ double lenC = NJ->branchlength[nodeABCD[2]]; double lenD = NJ->branchlength[nodeABCD[3]]; if (verbose > 3) { fprintf(stderr, "Computing UpProfile for node %d with lenC %.4f lenD %.4f pair-loglk %.3f\n", node, lenC, lenD, PairLogLk(profiles[2],profiles[3],lenC+lenD,NJ->nPos,NJ->transmat,&NJ->rates, /*site_lk*/NULL)); PrintNJInternal(stderr, NJ, /*useLen*/true); } upProfiles[node] = PosteriorProfile(/*C*/profiles[2], /*D*/profiles[3], lenC, lenD, NJ->transmat, &NJ->rates, NJ->nPos, NJ->nConstraints); } else { profile_t *profilesCDAB[4] = { profiles[2], profiles[3], profiles[0], profiles[1] }; double weight = QuartetWeight(profilesCDAB, NJ->distance_matrix, NJ->nPos); if (verbose>3) fprintf(stderr, "Compute upprofile of %d from %d and parents (vs. children %d %d) with weight %.3f\n", node, nodeABCD[2], nodeABCD[0], nodeABCD[1], weight); upProfiles[node] = AverageProfile(profiles[2], profiles[3], NJ->nPos, NJ->nConstraints, NJ->distance_matrix, weight); } } } FreePath(pathToRoot,NJ); assert(upProfiles[outnode] != NULL); return(upProfiles[outnode]); } profile_t *DeleteUpProfile(/*IN/OUT*/profile_t **upProfiles, NJ_t *NJ, int node) { assert(node>=0 && node < NJ->maxnodes); if (upProfiles[node] != NULL) upProfiles[node] = FreeProfile(upProfiles[node], NJ->nPos, NJ->nConstraints); /* returns NULL */ return(NULL); } profile_t **FreeUpProfiles(profile_t **upProfiles, NJ_t *NJ) { int i; int nUsed = 0; for (i=0; i < NJ->maxnodes; i++) { if (upProfiles[i] != NULL) nUsed++; DeleteUpProfile(upProfiles, NJ, i); } myfree(upProfiles, sizeof(profile_t*)*NJ->maxnodes); if (verbose >= 3) fprintf(stderr,"FreeUpProfiles -- freed %d\n", nUsed); return(NULL); } int *PathToRoot(NJ_t *NJ, int node, /*OUT*/int *outDepth) { int *pathToRoot = (int*)mymalloc(sizeof(int)*NJ->maxnodes); int depth = 0; int ancestor = node; while(ancestor >= 0) { pathToRoot[depth] = ancestor; ancestor = NJ->parent[ancestor]; depth++; } *outDepth = depth; return(pathToRoot); } int *FreePath(int *path, NJ_t *NJ) { myfree(path, sizeof(int)*NJ->maxnodes); return(NULL); } transition_matrix_t *CreateGTR(double *r/*ac ag at cg ct gt*/, double *f/*acgt*/) { double matrix[4][MAXCODES]; assert(nCodes==4); int i, j; /* Place rates onto a symmetric matrix, but correct by f(target), so that stationary distribution f[] is maintained Leave diagonals as 0 (CreateTransitionMatrix will fix them) */ int imat = 0; for (i = 0; i < nCodes; i++) { matrix[i][i] = 0; for (j = i+1; j < nCodes; j++) { double rate = r[imat++]; assert(rate > 0); /* Want t(matrix) * f to be 0 */ matrix[i][j] = rate * f[i]; matrix[j][i] = rate * f[j]; } } /* Compute average mutation rate */ double total_rate = 0; for (i = 0; i < nCodes; i++) for (j = 0; j < nCodes; j++) total_rate += f[i] * matrix[i][j]; assert(total_rate > 1e-6); double inv = 1.0/total_rate; for (i = 0; i < nCodes; i++) for (j = 0; j < nCodes; j++) matrix[i][j] *= inv; return(CreateTransitionMatrix(matrix,f)); } transition_matrix_t *CreateTransitionMatrix(/*IN*/double matrix[MAXCODES][MAXCODES], /*IN*/double stat[MAXCODES]) { int i,j,k; transition_matrix_t *transmat = mymalloc(sizeof(transition_matrix_t)); double sqrtstat[20]; for (i = 0; i < nCodes; i++) { transmat->stat[i] = stat[i]; transmat->statinv[i] = 1.0/stat[i]; sqrtstat[i] = sqrt(stat[i]); } double sym[20*20]; /* symmetrized matrix M' */ /* set diagonals so columns sums are 0 before symmetrization */ for (i = 0; i < nCodes; i++) for (j = 0; j < nCodes; j++) sym[nCodes*i+j] = matrix[i][j]; for (j = 0; j < nCodes; j++) { double sum = 0; sym[nCodes*j+j] = 0; for (i = 0; i < nCodes; i++) sum += sym[nCodes*i+j]; sym[nCodes*j+j] = -sum; } /* M' = S**-1 M S */ for (i = 0; i < nCodes; i++) for (j = 0; j < nCodes; j++) sym[nCodes*i+j] *= sqrtstat[j]/sqrtstat[i]; /* eigen decomposition of M' -- note that eigenW is the transpose of what we want, which is eigenvectors in columns */ double eigenW[20*20], eval[20], e[20]; for (i = 0; i < nCodes*nCodes; i++) eigenW[i] = sym[i]; tred2(eigenW, nCodes, nCodes, eval, e); tqli(eval, e, nCodes , nCodes, eigenW); /* save eigenvalues */ for (i = 0; i < nCodes; i++) transmat->eigenval[i] = eval[i]; /* compute eigen decomposition of M into t(codeFreq): V = S*W */ /* compute inverse of V in eigeninv: V**-1 = t(W) S**-1 */ for (i = 0; i < nCodes; i++) { for (j = 0; j < nCodes; j++) { transmat->eigeninv[i][j] = eigenW[nCodes*i+j] / sqrtstat[j]; transmat->eigeninvT[j][i] = transmat->eigeninv[i][j]; } } for (i = 0; i < nCodes; i++) for (j = 0; j < nCodes; j++) transmat->codeFreq[i][j] = eigenW[j*nCodes+i] * sqrtstat[i]; /* codeFreq[NOCODE] is the rotation of (1,1,...) not (1/nCodes,1/nCodes,...), which gives correct posterior probabilities */ for (j = 0; j < nCodes; j++) { transmat->codeFreq[NOCODE][j] = 0.0; for (i = 0; i < nCodes; i++) transmat->codeFreq[NOCODE][j] += transmat->codeFreq[i][j]; } /* save some posterior probabilities for approximating later: first, we compute P(B | A, t) for t = approxMLnearT, by using V * exp(L*t) * V**-1 */ double expvalues[MAXCODES]; for (i = 0; i < nCodes; i++) expvalues[i] = exp(approxMLnearT * transmat->eigenval[i]); double LVinv[MAXCODES][MAXCODES]; /* exp(L*t) * V**-1 */ for (i = 0; i < nCodes; i++) { for (j = 0; j < nCodes; j++) LVinv[i][j] = transmat->eigeninv[i][j] * expvalues[i]; } /* matrix transform for converting A -> B given t: transt[i][j] = P(j->i | t) */ double transt[MAXCODES][MAXCODES]; for (i = 0; i < nCodes; i++) { for (j = 0; j < nCodes; j++) { transt[i][j] = 0; for (k = 0; k < nCodes; k++) transt[i][j] += transmat->codeFreq[i][k] * LVinv[k][j]; } } /* nearP[i][j] = P(parent = j | both children are i) = P(j | i,i) ~ stat(j) * P(j->i | t)**2 */ for (i = 0; i < nCodes; i++) { double nearP[MAXCODES]; double tot = 0; for (j = 0; j < nCodes; j++) { assert(transt[j][i] > 0); assert(transmat->stat[j] > 0); nearP[j] = transmat->stat[j] * transt[i][j] * transt[i][j]; tot += nearP[j]; } assert(tot > 0); for (j = 0; j < nCodes; j++) nearP[j] *= 1.0/tot; /* save nearP in transmat->nearP[i][] */ for (j = 0; j < nCodes; j++) transmat->nearP[i][j] = nearP[j]; /* multiply by 1/stat and rotate nearP */ for (j = 0; j < nCodes; j++) nearP[j] /= transmat->stat[j]; for (j = 0; j < nCodes; j++) { double rot = 0; for (k = 0; k < nCodes; k++) rot += nearP[k] * transmat->codeFreq[i][j]; transmat->nearFreq[i][j] = rot; } } return(transmat); assert(0); } distance_matrix_t *TransMatToDistanceMat(transition_matrix_t *transmat) { if (transmat == NULL) return(NULL); distance_matrix_t *dmat = mymalloc(sizeof(distance_matrix_t)); int i, j; for (i=0; i<nCodes; i++) { for (j=0; j<nCodes; j++) { dmat->distances[i][j] = 0; /* never actually used */ dmat->eigeninv[i][j] = transmat->eigeninv[i][j]; dmat->codeFreq[i][j] = transmat->codeFreq[i][j]; } } /* eigentot . rotated-vector is the total frequency of the unrotated vector (used to normalize in NormalizeFreq() For transition matrices, we rotate by transpose of eigenvectors, so we need to multiply by the inverse matrix by 1....1 to get this vector, or in other words, sum the columns */ for(i = 0; i<nCodes; i++) { dmat->eigentot[i] = 0.0; for (j = 0; j<nCodes; j++) dmat->eigentot[i] += transmat->eigeninv[i][j]; } return(dmat); } /* Numerical recipes code for eigen decomposition (actually taken from RAxML rev_functions.c) */ void tred2 (double *a, const int n, const int np, double *d, double *e) { #define a(i,j) a[(j-1)*np + (i-1)] #define e(i) e[i-1] #define d(i) d[i-1] int i, j, k, l; double f, g, h, hh, scale; for (i = n; i > 1; i--) { l = i-1; h = 0; scale = 0; if ( l > 1 ) { for ( k = 1; k <= l; k++ ) scale += fabs(a(i,k)); if (scale == 0) e(i) = a(i,l); else { for (k = 1; k <= l; k++) { a(i,k) /= scale; h += a(i,k) * a(i,k); } f = a(i,l); g = -sqrt(h); if (f < 0) g = -g; e(i) = scale *g; h -= f*g; a(i,l) = f-g; f = 0; for (j = 1; j <=l ; j++) { a(j,i) = a(i,j) / h; g = 0; for (k = 1; k <= j; k++) g += a(j,k)*a(i,k); for (k = j+1; k <= l; k++) g += a(k,j)*a(i,k); e(j) = g/h; f += e(j)*a(i,j); } hh = f/(h+h); for (j = 1; j <= l; j++) { f = a(i,j); g = e(j) - hh * f; e(j) = g; for (k = 1; k <= j; k++) a(j,k) -= f*e(k) + g*a(i,k); } } } else e(i) = a(i,l); d(i) = h; } d(1) = 0; e(1) = 0; for (i = 1; i <= n; i++) { l = i-1; if (d(i) != 0) { for (j = 1; j <=l; j++) { g = 0; for (k = 1; k <= l; k++) g += a(i,k)*a(k,j); for (k=1; k <=l; k++) a(k,j) -= g * a(k,i); } } d(i) = a(i,i); a(i,i) = 1; for (j=1; j<=l; j++) a(i,j) = a(j,i) = 0; } return; #undef a #undef e #undef d } double pythag(double a, double b) { double absa = fabs(a), absb = fabs(b); return (absa > absb) ? absa * sqrt(1+ (absb/absa)*(absb/absa)) : absb == 0 ? 0 : absb * sqrt(1+ (absa/absb)*(absa/absb)); } void tqli(double *d, double *e, int n, int np, double *z) { #define z(i,j) z[(j-1)*np + (i-1)] #define e(i) e[i-1] #define d(i) d[i-1] int i = 0, iter = 0, k = 0, l = 0, m = 0; double b = 0, c = 0, dd = 0, f = 0, g = 0, p = 0, r = 0, s = 0; for(i=2; i<=n; i++) e(i-1) = e(i); e(n) = 0; for (l = 1; l <= n; l++) { iter = 0; labelExtra: for (m = l; (m < n); m++) { dd = fabs(d(m))+fabs(d(m+1)); if (fabs(e(m))+dd == dd) break; } if (m != l) { assert(iter < 30); iter++; g = (d(l+1)-d(l))/(2*e(l)); r = pythag(g,1.); g = d(m)-d(l)+e(l)/(g+(g<0?-r:r)); s = 1; c = 1; p = 0; for (i = m-1; i>=l; i--) { f = s*e(i); b = c*e(i); r = pythag(f,g); e(i+1) = r; if (r == 0) { d (i+1) -= p; e (m) = 0; goto labelExtra; } s = f/r; c = g/r; g = d(i+1)-p; r = (d(i)-g)*s + 2*c*b; p = s*r; d(i+1) = g + p; g = c*r - b; for (k=1; k <= n; k++) { f = z(k,i+1); z(k,i+1) = s * z(k,i) + c*f; z(k,i) = c * z(k,i) - s*f; } } d(l) -= p; e(l) = g; e(m) = 0; goto labelExtra; } } return; #undef z #undef e #undef d } #ifdef USE_SSE3 inline float mm_sum(register __m128 sum) { #if 1 /* stupider but faster */ float f[4] ALIGNED; _mm_store_ps(f,sum); return(f[0]+f[1]+f[2]+f[3]); #else /* first we get sum[0]+sum[1], sum[2]+sum[3] by selecting 0/1 and 2/3 */ sum = _mm_add_ps(sum,_mm_shuffle_ps(sum,sum,_MM_SHUFFLE(0,1,2,3))); /* then get sum[0]+sum[1]+sum[2]+sum[3] by selecting 0/1 and 0/1 */ sum = _mm_add_ps(sum,_mm_shuffle_ps(sum,sum,_MM_SHUFFLE(0,1,0,1))); float f; _mm_store_ss(&f, sum); /* save the lowest word */ return(f); #endif } #endif void vector_multiply(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n, /*OUT*/numeric_t *fOut) { #ifdef USE_SSE3 int i; for (i = 0; i < n; i += 4) { __m128 a, b, c; a = _mm_load_ps(f1+i); b = _mm_load_ps(f2+i); c = _mm_mul_ps(a, b); _mm_store_ps(fOut+i,c); } #else int i; for (i = 0; i < n; i++) fOut[i] = f1[i]*f2[i]; #endif } numeric_t vector_multiply_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, int n) { #ifdef USE_SSE3 if (n == 4) return(f1[0]*f2[0]+f1[1]*f2[1]+f1[2]*f2[2]+f1[3]*f2[3]); __m128 sum = _mm_setzero_ps(); int i; for (i = 0; i < n; i += 4) { __m128 a, b, c; a = _mm_load_ps(f1+i); b = _mm_load_ps(f2+i); c = _mm_mul_ps(a, b); sum = _mm_add_ps(c, sum); } return(mm_sum(sum)); #else int i; numeric_t out = 0.0; for (i=0; i < n; i++) out += f1[i]*f2[i]; return(out); #endif } /* sum(f1*f2*f3) */ numeric_t vector_multiply3_sum(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t* f3, int n) { #ifdef USE_SSE3 __m128 sum = _mm_setzero_ps(); int i; for (i = 0; i < n; i += 4) { __m128 a1, a2, a3; a1 = _mm_load_ps(f1+i); a2 = _mm_load_ps(f2+i); a3 = _mm_load_ps(f3+i); sum = _mm_add_ps(_mm_mul_ps(_mm_mul_ps(a1,a2),a3),sum); } return(mm_sum(sum)); #else int i; numeric_t sum = 0.0; for (i = 0; i < n; i++) sum += f1[i]*f2[i]*f3[i]; return(sum); #endif } numeric_t vector_dot_product_rot(/*IN*/numeric_t *f1, /*IN*/numeric_t *f2, /*IN*/numeric_t *fBy, int n) { #ifdef USE_SSE3 __m128 sum1 = _mm_setzero_ps(); __m128 sum2 = _mm_setzero_ps(); int i; for (i = 0; i < n; i += 4) { __m128 a1, a2, aBy; a1 = _mm_load_ps(f1+i); a2 = _mm_load_ps(f2+i); aBy = _mm_load_ps(fBy+i); sum1 = _mm_add_ps(_mm_mul_ps(a1, aBy), sum1); sum2 = _mm_add_ps(_mm_mul_ps(a2, aBy), sum2); } return(mm_sum(sum1)*mm_sum(sum2)); #else int i; numeric_t out1 = 0.0; numeric_t out2 = 0.0; for (i=0; i < n; i++) { out1 += f1[i]*fBy[i]; out2 += f2[i]*fBy[i]; } return(out1*out2); #endif } numeric_t vector_sum(/*IN*/numeric_t *f1, int n) { #ifdef USE_SSE3 if (n==4) return(f1[0]+f1[1]+f1[2]+f1[3]); __m128 sum = _mm_setzero_ps(); int i; for (i = 0; i < n; i+=4) { __m128 a; a = _mm_load_ps(f1+i); sum = _mm_add_ps(a, sum); } return(mm_sum(sum)); #else numeric_t out = 0.0; int i; for (i = 0; i < n; i++) out += f1[i]; return(out); #endif } void vector_multiply_by(/*IN/OUT*/numeric_t *f, /*IN*/numeric_t fBy, int n) { int i; #ifdef USE_SSE3 __m128 c = _mm_set1_ps(fBy); for (i = 0; i < n; i += 4) { __m128 a, b; a = _mm_load_ps(f+i); b = _mm_mul_ps(a,c); _mm_store_ps(f+i,b); } #else for (i = 0; i < n; i++) f[i] *= fBy; #endif } void vector_add_mult(/*IN/OUT*/numeric_t *fTot, /*IN*/numeric_t *fAdd, numeric_t weight, int n) { #ifdef USE_SSE3 int i; __m128 w = _mm_set1_ps(weight); for (i = 0; i < n; i += 4) { __m128 tot, add; tot = _mm_load_ps(fTot+i); add = _mm_load_ps(fAdd+i); _mm_store_ps(fTot+i, _mm_add_ps(tot, _mm_mul_ps(add,w))); } #else int i; for (i = 0; i < n; i++) fTot[i] += fAdd[i] * weight; #endif } void matrixt_by_vector4(/*IN*/numeric_t mat[4][MAXCODES], /*IN*/numeric_t vec[4], /*OUT*/numeric_t out[4]) { #ifdef USE_SSE3 /*__m128 v = _mm_load_ps(vec);*/ __m128 o = _mm_setzero_ps(); int j; /* result is a sum of vectors: sum(k) v[k] * mat[k][] */ for (j = 0; j < 4; j++) { __m128 m = _mm_load_ps(&mat[j][0]); __m128 vj = _mm_load1_ps(&vec[j]); /* is it faster to shuffle v? */ o = _mm_add_ps(o, _mm_mul_ps(vj,m)); } _mm_store_ps(out, o); #else int j,k; for (j = 0; j < 4; j++) { double sum = 0; for (k = 0; k < 4; k++) sum += vec[k] * mat[k][j]; out[j] = sum; } #endif } distance_matrix_t matrixBLOSUM45 = { /*distances*/ { {0, 1.31097856157468, 1.06573001937323, 1.2682782988532, 0.90471293383305, 1.05855446876905, 1.05232790675508, 0.769574440593014, 1.27579668305679, 0.964604099952603, 0.987178199640556, 1.05007594438157, 1.05464162250736, 1.1985987403937, 0.967404475245526, 0.700490199584332, 0.880060189098976, 1.09748548316685, 1.28141710375267, 0.800038509951648}, {1.31097856157468, 0, 0.8010890222701, 0.953340718498495, 1.36011107208122, 0.631543775840481, 0.791014908659279, 1.15694899265629, 0.761152570032029, 1.45014917711188, 1.17792001455227, 0.394661075648738, 0.998807558909651, 1.135143404599, 1.15432562628921, 1.05309036790541, 1.05010474413616, 1.03938321130789, 0.963216908696184, 1.20274751778601}, {1.06573001937323, 0.8010890222701, 0, 0.488217214273568, 1.10567116937273, 0.814970207038261, 0.810176440932339, 0.746487413974582, 0.61876156253224, 1.17886558630004, 1.52003670190022, 0.808442678243754, 1.2889025816028, 1.16264109995678, 1.18228799147301, 0.679475681649858, 0.853658619686283, 1.68988558988005, 1.24297493464833, 1.55207513886163}, {1.2682782988532, 0.953340718498495, 0.488217214273568, 0, 1.31581050011876, 0.769778474953791, 0.482077627352988, 0.888361752320536, 0.736360849050364, 1.76756333403346, 1.43574761894039, 0.763612910719347, 1.53386612356483, 1.74323672079854, 0.886347403928663, 0.808614044804528, 1.01590147813779, 1.59617804551619, 1.1740494822217, 1.46600946033173}, {0.90471293383305, 1.36011107208122, 1.10567116937273, 1.31581050011876, 0, 1.3836789310481, 1.37553994252576, 1.26740695314856, 1.32361065635259, 1.26087264215993, 1.02417540515351, 1.37259631233791, 1.09416720447891, 0.986982088723923, 1.59321190226694, 0.915638787768407, 0.913042853922533, 1.80744143643002, 1.3294417177004, 0.830022143283238}, {1.05855446876905, 0.631543775840481, 0.814970207038261, 0.769778474953791, 1.3836789310481, 0, 0.506942797642807, 1.17699648087288, 0.614595446514896, 1.17092829494457, 1.19833088638994, 0.637341078675405, 0.806490842729072, 1.83315144709714, 0.932064479113502, 0.850321696813199, 1.06830084665916, 1.05739353225849, 0.979907428113788, 1.5416250309563}, {1.05232790675508, 0.791014908659279, 0.810176440932339, 0.482077627352988, 1.37553994252576, 0.506942797642807, 0, 1.17007322676118, 0.769786956320484, 1.46659942462342, 1.19128214039009, 0.633592151371708, 1.27269395724349, 1.44641491621774, 0.735428579892476, 0.845319988414402, 1.06201695511881, 1.324395996498, 1.22734387448031, 1.53255698189437}, {0.769574440593014, 1.15694899265629, 0.746487413974582, 0.888361752320536, 1.26740695314856, 1.17699648087288, 1.17007322676118, 0, 1.1259007054424, 1.7025415585924, 1.38293205218175, 1.16756929156758, 1.17264582493965, 1.33271035269688, 1.07564768421292, 0.778868281341681, 1.23287107008366, 0.968539655354582, 1.42479529031801, 1.41208067821187}, {1.27579668305679, 0.761152570032029, 0.61876156253224, 0.736360849050364, 1.32361065635259, 0.614595446514896, 0.769786956320484, 1.1259007054424, 0, 1.4112324673522, 1.14630894167097, 0.967795284542623, 0.771479459384692, 1.10468029976148, 1.12334774065132, 1.02482926701639, 1.28754326478771, 1.27439749294131, 0.468683841672724, 1.47469999960758}, {0.964604099952603, 1.45014917711188, 1.17886558630004, 1.76756333403346, 1.26087264215993, 1.17092829494457, 1.46659942462342, 1.7025415585924, 1.4112324673522, 0, 0.433350517223017, 1.463460928818, 0.462965544381851, 0.66291968000662, 1.07010201755441, 1.23000200130049, 0.973485453109068, 0.963546200571036, 0.708724769805536, 0.351200119909572}, {0.987178199640556, 1.17792001455227, 1.52003670190022, 1.43574761894039, 1.02417540515351, 1.19833088638994, 1.19128214039009, 1.38293205218175, 1.14630894167097, 0.433350517223017, 0, 1.49770950074319, 0.473800072611076, 0.538473125003292, 1.37979627224964, 1.5859723170438, 0.996267398224516, 0.986095542821092, 0.725310666139274, 0.570542199221932}, {1.05007594438157, 0.394661075648738, 0.808442678243754, 0.763612910719347, 1.37259631233791, 0.637341078675405, 0.633592151371708, 1.16756929156758, 0.967795284542623, 1.463460928818, 1.49770950074319, 0, 1.0079761868248, 1.44331961488922, 0.924599080166146, 1.06275728888356, 1.05974425835993, 1.04892430642749, 0.972058829603409, 1.21378822764856}, {1.05464162250736, 0.998807558909651, 1.2889025816028, 1.53386612356483, 1.09416720447891, 0.806490842729072, 1.27269395724349, 1.17264582493965, 0.771479459384692, 0.462965544381851, 0.473800072611076, 1.0079761868248, 0, 0.72479754849538, 1.1699868662153, 1.34481214251794, 1.06435197383538, 1.05348497728858, 0.774878150710318, 0.609532859331199}, {1.1985987403937, 1.135143404599, 1.16264109995678, 1.74323672079854, 0.986982088723923, 1.83315144709714, 1.44641491621774, 1.33271035269688, 1.10468029976148, 0.66291968000662, 0.538473125003292, 1.44331961488922, 0.72479754849538, 0, 1.32968844979665, 1.21307373491949, 0.960087571600877, 0.475142555482979, 0.349485367759138, 0.692733248746636}, {0.967404475245526, 1.15432562628921, 1.18228799147301, 0.886347403928663, 1.59321190226694, 0.932064479113502, 0.735428579892476, 1.07564768421292, 1.12334774065132, 1.07010201755441, 1.37979627224964, 0.924599080166146, 1.1699868662153, 1.32968844979665, 0, 0.979087429691819, 0.97631161216338, 1.21751652292503, 1.42156458605332, 1.40887880416009}, {0.700490199584332, 1.05309036790541, 0.679475681649858, 0.808614044804528, 0.915638787768407, 0.850321696813199, 0.845319988414402, 0.778868281341681, 1.02482926701639, 1.23000200130049, 1.5859723170438, 1.06275728888356, 1.34481214251794, 1.21307373491949, 0.979087429691819, 0, 0.56109848274013, 1.76318885009194, 1.29689226231656, 1.02015839286433}, {0.880060189098976, 1.05010474413616, 0.853658619686283, 1.01590147813779, 0.913042853922533, 1.06830084665916, 1.06201695511881, 1.23287107008366, 1.28754326478771, 0.973485453109068, 0.996267398224516, 1.05974425835993, 1.06435197383538, 0.960087571600877, 0.97631161216338, 0.56109848274013, 0, 1.39547634461879, 1.02642577026706, 0.807404666228614}, {1.09748548316685, 1.03938321130789, 1.68988558988005, 1.59617804551619, 1.80744143643002, 1.05739353225849, 1.324395996498, 0.968539655354582, 1.27439749294131, 0.963546200571036, 0.986095542821092, 1.04892430642749, 1.05348497728858, 0.475142555482979, 1.21751652292503, 1.76318885009194, 1.39547634461879, 0, 0.320002937404137, 1.268589159299}, {1.28141710375267, 0.963216908696184, 1.24297493464833, 1.1740494822217, 1.3294417177004, 0.979907428113788, 1.22734387448031, 1.42479529031801, 0.468683841672724, 0.708724769805536, 0.725310666139274, 0.972058829603409, 0.774878150710318, 0.349485367759138, 1.42156458605332, 1.29689226231656, 1.02642577026706, 0.320002937404137, 0, 0.933095433689795}, {0.800038509951648, 1.20274751778601, 1.55207513886163, 1.46600946033173, 0.830022143283238, 1.5416250309563, 1.53255698189437, 1.41208067821187, 1.47469999960758, 0.351200119909572, 0.570542199221932, 1.21378822764856, 0.609532859331199, 0.692733248746636, 1.40887880416009, 1.02015839286433, 0.807404666228614, 1.268589159299, 0.933095433689795, 0} }, /*eigeninv*/ { {-0.216311217101265, -0.215171653035930, -0.217000020881064, -0.232890860601250, -0.25403526530177, -0.211569372858927, -0.218073620637049, -0.240585637190076, -0.214507049619293, -0.228476323330312, -0.223235445346107, -0.216116483840334, -0.206903836810903, -0.223553828183343, -0.236937609127783, -0.217652789023588, -0.211982652566286, -0.245995223308316, -0.206187718714279, -0.227670670439422}, {-0.0843931919568687, -0.0342164464991033, 0.393702284928246, -0.166018266253027, 0.0500896782860136, -0.262731388032538, 0.030139964190519, -0.253997503551094, -0.0932603349591988, -0.32884667697173, 0.199966846276877, -0.117543453869516, 0.196248237055757, -0.456448703853250, 0.139286961076387, 0.241166801918811, -0.0783508285295053, 0.377438091416498, 0.109499076984234, 0.128581669647144}, {-0.0690428674271772, 0.0133858672878363, -0.208289917312908, 0.161232925220819, 0.0735806288007248, -0.316269599838174, -0.0640708424745702, -0.117078801507436, 0.360805085405857, 0.336899760384943, 0.0332447078185156, 0.132954055834276, 0.00595209121998118, -0.157755611190327, -0.199839273133436, 0.193688928807663, 0.0970290928040946, 0.374683975138541, -0.478110944870958, -0.243290196936098}, {0.117284581850481, 0.310399467781876, -0.143513477698805, 0.088808130300351, 0.105747812943691, -0.373871701179853, 0.189069306295134, 0.133258225034741, -0.213043549687694, 0.301303731259140, -0.182085224761849, -0.161971915020789, 0.229301173581378, -0.293586313243755, -0.0260480060747498, -0.0217953684540699, 0.0202675755458796, -0.160134624443657, 0.431950096999465, -0.329885160320501}, {0.256496969244703, 0.0907408349583135, 0.0135731083898029, 0.477557831930769, -0.0727379669280703, 0.101732675207959, -0.147293025369251, -0.348325291603251, -0.255678082078362, -0.187092643740172, -0.177164064346593, -0.225921480146133, 0.422318841046522, 0.319959853469398, -0.0623652546300045, 0.0824203908606883, -0.102057926881110, 0.120728407576411, -0.156845807891241, -0.123528163091204}, {-0.00906668858975576, -0.0814722888231236, -0.0762715085459023, 0.055819989938286, -0.0540516675257271, -0.0070589302769034, -0.315813159989213, -0.0103527463419808, -0.194634331372293, -0.0185860407566822, 0.50134169352609, 0.384531812730061, -0.0405008616742061, 0.0781033650669525, 0.069334900096687, 0.396455180448549, -0.204065801866462, -0.215272089630713, 0.171046818996465, -0.396393364716348}, {0.201971098571663, 0.489747667606921, 0.00226258734592836, 0.0969514005747054, 0.0853921636903791, 0.0862068740282345, -0.465412154271164, -0.130516676347786, 0.165513616974634, 0.0712238027886633, 0.140746943067963, -0.325919272273406, -0.421213488261598, -0.163508199065965, 0.269695802810568, -0.110296405171437, -0.106834099902202, 0.00509414588152415, 0.00909215239544615, 0.0500401865589727}, {0.515854176692456, -0.087468413428258, 0.102796468891449, -0.06046105990993, -0.212014383772414, -0.259853648383794, -0.0997372883043333, -0.109934574535736, 0.284891018406112, -0.250578342940183, 0.142174204994568, 0.210384918947619, 0.118803190788946, -0.0268434355996836, 0.0103721198836548, -0.355555176478458, 0.428042332431476, -0.150610175411631, 0.0464090887952940, -0.140238796382057}, {-0.239392215229762, -0.315483492656425, 0.100205194952396, 0.197830195325302, 0.40178804665223, 0.195809461460298, -0.407817115321684, 0.0226836686147386, -0.169780276210306, 0.0818161585952184, -0.172886230584939, 0.174982644851064, 0.0868786992159535, -0.198450519980824, 0.168581078329968, -0.361514336004068, 0.238668430084722, 0.165494019791904, 0.110437707249228, -0.169592003035203}, {-0.313151735678025, 0.10757884850664, -0.49249098807229, 0.0993472335619114, -0.148695715250836, 0.0573801136941699, -0.190040373500722, 0.254848437434773, 0.134147888304352, -0.352719341442756, 0.0839609323513986, -0.207904182300122, 0.253940523323376, -0.109832138553288, 0.0980084518687944, 0.209026594443723, 0.406236051871548, -0.0521120230935943, 0.0554108014592302, 0.134681046631955}, {-0.102905214421384, 0.235803606800009, 0.213414976431981, -0.253606415825635, 0.00945656859370683, 0.259551282655855, 0.159527348902192, 0.083218761193016, -0.286815935191867, 0.0135069477264877, 0.336758103107357, -0.271707359524149, -0.0400009875851839, 0.0871186292716414, -0.171506310409388, -0.0954276577211755, 0.393467571460712, 0.111732846649458, -0.239886066474217, -0.426474828195231}, {-0.0130795552324104, 0.0758967690968058, -0.165099404017689, -0.46035152559912, 0.409888158016031, -0.0235053940299396, 0.0699393201709723, -0.161320910316996, 0.226111732196825, -0.177811841258496, -0.219073917645916, -0.00703219376737286, 0.162831878334912, 0.271670554900684, 0.451033612762052, 0.0820942662443393, -0.0904983490498446, -0.0587000279313978, -0.0938852980928252, -0.306078621571843}, {0.345092040577428, -0.257721588971295, -0.301689123771848, -0.0875212184538126, 0.161012613069275, 0.385104899829821, 0.118355290985046, -0.241723794416731, 0.083201920119646, -0.0809095291508749, -0.0820275390511991, -0.115569770103317, -0.250105681098033, -0.164197583037664, -0.299481453795592, 0.255906951902366, 0.129042051416371, 0.203761730442746, 0.347550071284268, -0.109264854744020}, {0.056345924962239, 0.072536751679082, 0.303127492633681, -0.368877185781648, -0.343024497082421, 0.206879529669083, -0.413012709639426, 0.078538816203612, 0.103382383425097, 0.288319996147499, -0.392663258459423, 0.0319588502083897, 0.220316797792669, -0.0563686494606947, -0.0869286063283735, 0.323677017794391, 0.0984875197088935, -0.0303289828821742, 0.0450197853450979, -0.0261771221270139}, {-0.253701638374729, -0.148922815783583, 0.111794052194159, 0.157313977830326, -0.269846001260543, -0.222989872703583, 0.115441028189268, -0.350456582262355, -0.0409581422905941, 0.174078744248002, -0.130673397086811, -0.123963802708056, -0.351609207081548, 0.281548012920868, 0.340382662112428, 0.180262131025562, 0.3895263830793, 0.0121546812430960, 0.214830943227063, -0.0617782909660214}, {-0.025854479416026, 0.480654788977767, -0.138024550829229, -0.130191670810919, 0.107816875829919, -0.111243997319276, -0.0679814460571245, -0.183167991080677, -0.363355166018786, -0.183934891092050, -0.216097125080962, 0.520240628803255, -0.179616013606479, 0.0664131536100941, -0.178350708111064, 0.0352047611606709, 0.223857228692892, 0.128363679623513, -0.000403433628490731, 0.224972110977704}, {0.159207394033448, -0.0371517305736114, -0.294302634912281, -0.0866954375908417, -0.259998567870054, 0.284966673982689, 0.205356416771391, -0.257613708650298, -0.264820519037270, 0.293359248624603, 0.0997476397434102, 0.151390539497369, 0.165571346773648, -0.347569523551258, 0.43792310820533, -0.0723248163210163, 0.0379214984816955, -0.0542758730251438, -0.258020301801603, 0.128680501102363}, {0.316853842351797, -0.153950010941153, -0.13387065213508, -0.0702971390607613, -0.202558481846057, -0.172941438694837, -0.068882524588574, 0.524738203063889, -0.271670479920716, -0.112864756695310, -0.146831636946145, -0.0352336188578041, -0.211108490884767, 0.097857111349555, 0.276459740956662, 0.0231297536754823, -0.0773173324868396, 0.487208384389438, -0.0734191389266824, -0.113198765573319}, {-0.274285525741087, 0.227334266052039, -0.0973746625709059, -0.00965256583655389, -0.402438444750043, 0.198586229519026, 0.0958135064575833, -0.108934376958686, 0.253641732094319, -0.0551918478254021, 0.0243640218331436, 0.181936272247179, 0.090952738347629, 0.0603352483029044, -0.0043821671755761, -0.347720824658591, -0.267879988539971, 0.403804652116592, 0.337654323971186, -0.241509293972297}, {-0.0197089518344238, 0.139681034626696, 0.251980475788267, 0.341846624362846, -0.075141195125153, 0.2184951591319, 0.268870823491343, 0.150392399018138, 0.134592404015057, -0.337050200539163, -0.313109373497998, 0.201993318439135, -0.217140733851970, -0.337622749083808, 0.135253284365068, 0.181729249828045, -0.00627813335422765, -0.197218833324039, -0.194060005031698, -0.303055888528004} }, /*eigenval*/ { 20.29131, 0.5045685, 0.2769945, 0.1551147, 0.03235484, -0.04127639, -0.3516426, -0.469973, -0.5835191, -0.6913107, -0.7207972, -0.7907875, -0.9524307, -1.095310, -1.402153, -1.424179, -1.936704, -2.037965, -3.273561, -5.488734 }, /*eigentot and codeFreq left out, these are initialized elsewhere*/ }; /* The JTT92 matrix, D. T. Jones, W. R. Taylor, & J. M. Thorton, CABIOS 8:275 (1992) Derived from the PhyML source code (models.c) by filling in the other side of the symmetric matrix, scaling the entries by the stationary rate (to give the rate of a->b not b|a), to set the diagonals so the rows sum to 0, to rescale the matrix so that the implied rate of evolution is 1. The resulting matrix is the transpose (I think). */ #if 0 { int i,j; for (i=0; i<20; i++) for (j=0; j<i; j++) daa[j*20+i] = daa[i*20+j]; for (i = 0; i < 20; i++) for (j = 0; j < 20; j++) daa[i*20+j] *= pi[j] / 100.0; double mr = 0; /* mean rate */ for (i = 0; i < 20; i++) { double sum = 0; for (j = 0; j < 20; j++) sum += daa[i*20+j]; daa[i*20+i] = -sum; mr += pi[i] * sum; } for (i = 0; i < 20*20; i++) daa[i] /= mr; } #endif double statJTT92[MAXCODES] = {0.07674789,0.05169087,0.04264509,0.05154407,0.01980301,0.04075195,0.06182989,0.07315199,0.02294399,0.05376110,0.09190390,0.05867583,0.02382594,0.04012589,0.05090097,0.06876503,0.05856501,0.01426057,0.03210196,0.06600504}; double matrixJTT92[MAXCODES][MAXCODES] = { { -1.247831,0.044229,0.041179,0.061769,0.042704,0.043467,0.08007,0.136501,0.02059,0.027453,0.022877,0.02669,0.041179,0.011439,0.14794,0.288253,0.362223,0.006863,0.008388,0.227247 }, { 0.029789,-1.025965,0.023112,0.008218,0.058038,0.159218,0.014895,0.070364,0.168463,0.011299,0.019517,0.33179,0.022599,0.002568,0.038007,0.051874,0.032871,0.064714,0.010272,0.008731 }, { 0.022881,0.019068,-1.280568,0.223727,0.014407,0.03644,0.024576,0.034322,0.165676,0.019915,0.005085,0.11144,0.012712,0.004237,0.006356,0.213134,0.098304,0.00339,0.029661,0.00678 }, { 0.041484,0.008194,0.270413,-1.044903,0.005121,0.025095,0.392816,0.066579,0.05736,0.005634,0.003585,0.013316,0.007682,0.002049,0.007682,0.030217,0.019462,0.002049,0.023559,0.015877 }, { 0.011019,0.022234,0.00669,0.001968,-0.56571,0.001771,0.000984,0.011609,0.013577,0.003345,0.004526,0.001377,0.0061,0.015348,0.002755,0.043878,0.008264,0.022628,0.041124,0.012199 }, { 0.02308,0.125524,0.034823,0.019841,0.003644,-1.04415,0.130788,0.010528,0.241735,0.003644,0.029154,0.118235,0.017411,0.00162,0.066406,0.021461,0.020651,0.007288,0.009718,0.008098 }, { 0.064507,0.017816,0.035632,0.471205,0.003072,0.198435,-0.944343,0.073107,0.015973,0.007372,0.005529,0.111197,0.011058,0.003072,0.011058,0.01843,0.019659,0.006143,0.0043,0.027646 }, { 0.130105,0.099578,0.058874,0.09449,0.042884,0.018898,0.086495,-0.647831,0.016717,0.004361,0.004361,0.019625,0.010176,0.003634,0.017444,0.146096,0.023986,0.039976,0.005815,0.034162 }, { 0.006155,0.074775,0.089138,0.025533,0.01573,0.1361,0.005927,0.005243,-1.135695,0.003648,0.012767,0.010259,0.007523,0.009119,0.026217,0.016642,0.010487,0.001824,0.130629,0.002508 }, { 0.01923,0.011752,0.025106,0.005876,0.009081,0.004808,0.00641,0.003205,0.008547,-1.273602,0.122326,0.011218,0.25587,0.047542,0.005342,0.021367,0.130873,0.004808,0.017094,0.513342 }, { 0.027395,0.0347,0.010958,0.006392,0.021003,0.065748,0.008219,0.005479,0.051137,0.209115,-0.668139,0.012784,0.354309,0.226465,0.093143,0.053877,0.022829,0.047485,0.021916,0.16437 }, { 0.020405,0.376625,0.153332,0.015158,0.004081,0.170239,0.105525,0.015741,0.026235,0.012243,0.008162,-0.900734,0.037896,0.002332,0.012243,0.027401,0.06005,0.00583,0.004664,0.008162 }, { 0.012784,0.010416,0.007102,0.003551,0.007339,0.01018,0.004261,0.003314,0.007812,0.113397,0.091854,0.015388,-1.182051,0.01018,0.003788,0.006865,0.053503,0.005682,0.004261,0.076466 }, { 0.00598,0.001993,0.003987,0.001595,0.031098,0.001595,0.001993,0.001993,0.015948,0.035484,0.098877,0.001595,0.017144,-0.637182,0.006778,0.03668,0.004784,0.021131,0.213701,0.024719 }, { 0.098117,0.037426,0.007586,0.007586,0.007081,0.082944,0.009104,0.012138,0.058162,0.005058,0.051587,0.010621,0.008092,0.008598,-0.727675,0.144141,0.059679,0.003035,0.005058,0.011632 }, { 0.258271,0.069009,0.343678,0.040312,0.152366,0.036213,0.020498,0.137334,0.049878,0.02733,0.040312,0.032113,0.019814,0.06286,0.194728,-1.447863,0.325913,0.023914,0.043045,0.025964 }, { 0.276406,0.037242,0.135003,0.022112,0.02444,0.029677,0.018621,0.019203,0.026768,0.142567,0.014548,0.059936,0.131511,0.006983,0.068665,0.27757,-1.335389,0.006983,0.01222,0.065174 }, { 0.001275,0.017854,0.001134,0.000567,0.016295,0.002551,0.001417,0.007793,0.001134,0.001275,0.007368,0.001417,0.003401,0.00751,0.00085,0.004959,0.0017,-0.312785,0.010061,0.003542 }, { 0.003509,0.006379,0.022328,0.014673,0.066664,0.007655,0.002233,0.002552,0.182769,0.010207,0.007655,0.002552,0.005741,0.170967,0.00319,0.020095,0.006698,0.022647,-0.605978,0.005103 }, { 0.195438,0.011149,0.010493,0.020331,0.040662,0.013117,0.029512,0.030824,0.007214,0.630254,0.11805,0.009182,0.211834,0.040662,0.015084,0.024922,0.073453,0.016396,0.010493,-1.241722 } }; double statWAG01[MAXCODES] = {0.0866279,0.043972, 0.0390894,0.0570451,0.0193078,0.0367281,0.0580589,0.0832518,0.0244314,0.048466, 0.086209, 0.0620286,0.0195027,0.0384319,0.0457631,0.0695179,0.0610127,0.0143859,0.0352742,0.0708956}; double matrixWAG01[MAXCODES][MAXCODES] = { {-1.117151, 0.050147, 0.046354, 0.067188, 0.093376, 0.082607, 0.143908, 0.128804, 0.028817, 0.017577, 0.036177, 0.082395, 0.081234, 0.019138, 0.130789, 0.306463, 0.192846, 0.010286, 0.021887, 0.182381}, {0.025455, -0.974318, 0.029321, 0.006798, 0.024376, 0.140086, 0.020267, 0.026982, 0.098628, 0.008629, 0.022967, 0.246964, 0.031527, 0.004740, 0.031358, 0.056495, 0.025586, 0.053714, 0.017607, 0.011623}, {0.020916, 0.026065, -1.452438, 0.222741, 0.010882, 0.063328, 0.038859, 0.046176, 0.162306, 0.022737, 0.005396, 0.123567, 0.008132, 0.003945, 0.008003, 0.163042, 0.083283, 0.002950, 0.044553, 0.008051}, {0.044244, 0.008819, 0.325058, -0.989665, 0.001814, 0.036927, 0.369645, 0.051822, 0.055719, 0.002361, 0.005077, 0.028729, 0.006212, 0.002798, 0.025384, 0.064166, 0.022443, 0.007769, 0.019500, 0.009120}, {0.020812, 0.010703, 0.005375, 0.000614, -0.487357, 0.002002, 0.000433, 0.006214, 0.005045, 0.003448, 0.007787, 0.001500, 0.007913, 0.008065, 0.002217, 0.028525, 0.010395, 0.014531, 0.011020, 0.020307}, {0.035023, 0.117008, 0.059502, 0.023775, 0.003809, -1.379785, 0.210830, 0.012722, 0.165524, 0.004391, 0.033516, 0.150135, 0.059565, 0.003852, 0.035978, 0.039660, 0.033070, 0.008316, 0.008777, 0.011613}, {0.096449, 0.026759, 0.057716, 0.376214, 0.001301, 0.333275, -1.236894, 0.034593, 0.034734, 0.007763, 0.009400, 0.157479, 0.019202, 0.004944, 0.041578, 0.042955, 0.050134, 0.009540, 0.011961, 0.035874}, {0.123784, 0.051085, 0.098345, 0.075630, 0.026795, 0.028838, 0.049604, -0.497615, 0.021792, 0.002661, 0.005356, 0.032639, 0.015212, 0.004363, 0.021282, 0.117240, 0.019732, 0.029444, 0.009052, 0.016361}, {0.008127, 0.054799, 0.101443, 0.023863, 0.006384, 0.110105, 0.014616, 0.006395, -0.992342, 0.003543, 0.012807, 0.022832, 0.010363, 0.017420, 0.017851, 0.018979, 0.012136, 0.006733, 0.099319, 0.003035}, {0.009834, 0.009511, 0.028192, 0.002006, 0.008654, 0.005794, 0.006480, 0.001549, 0.007029, -1.233162, 0.161294, 0.016472, 0.216559, 0.053891, 0.005083, 0.016249, 0.074170, 0.010808, 0.021372, 0.397837}, {0.036002, 0.045028, 0.011900, 0.007673, 0.034769, 0.078669, 0.013957, 0.005547, 0.045190, 0.286902, -0.726011, 0.023303, 0.439180, 0.191376, 0.037625, 0.031191, 0.029552, 0.060196, 0.036066, 0.162890}, {0.058998, 0.348377, 0.196082, 0.031239, 0.004820, 0.253558, 0.168246, 0.024319, 0.057967, 0.021081, 0.016767, -1.124580, 0.060821, 0.005783, 0.036254, 0.062960, 0.090292, 0.008952, 0.008675, 0.019884}, {0.018288, 0.013983, 0.004057, 0.002124, 0.007993, 0.031629, 0.006450, 0.003564, 0.008272, 0.087143, 0.099354, 0.019123, -1.322098, 0.024370, 0.003507, 0.010109, 0.031033, 0.010556, 0.008769, 0.042133}, {0.008490, 0.004143, 0.003879, 0.001885, 0.016054, 0.004030, 0.003273, 0.002014, 0.027402, 0.042734, 0.085315, 0.003583, 0.048024, -0.713669, 0.006512, 0.022020, 0.006934, 0.061698, 0.260332, 0.026213}, {0.069092, 0.032635, 0.009370, 0.020364, 0.005255, 0.044829, 0.032773, 0.011698, 0.033438, 0.004799, 0.019973, 0.026747, 0.008229, 0.007754, -0.605590, 0.077484, 0.038202, 0.006695, 0.010376, 0.015124}, {0.245933, 0.089317, 0.289960, 0.078196, 0.102703, 0.075066, 0.051432, 0.097899, 0.054003, 0.023306, 0.025152, 0.070562, 0.036035, 0.039831, 0.117705, -1.392239, 0.319421, 0.038212, 0.057419, 0.016981}, {0.135823, 0.035501, 0.129992, 0.024004, 0.032848, 0.054936, 0.052685, 0.014461, 0.030308, 0.093371, 0.020915, 0.088814, 0.097083, 0.011008, 0.050931, 0.280341, -1.154973, 0.007099, 0.018643, 0.088894}, {0.001708, 0.017573, 0.001086, 0.001959, 0.010826, 0.003257, 0.002364, 0.005088, 0.003964, 0.003208, 0.010045, 0.002076, 0.007786, 0.023095, 0.002105, 0.007908, 0.001674, -0.466694, 0.037525, 0.005516}, {0.008912, 0.014125, 0.040205, 0.012058, 0.020133, 0.008430, 0.007267, 0.003836, 0.143398, 0.015555, 0.014757, 0.004934, 0.015861, 0.238943, 0.007998, 0.029135, 0.010779, 0.092011, -0.726275, 0.011652}, {0.149259, 0.018739, 0.014602, 0.011335, 0.074565, 0.022417, 0.043805, 0.013932, 0.008807, 0.581952, 0.133956, 0.022726, 0.153161, 0.048356, 0.023429, 0.017317, 0.103293, 0.027186, 0.023418, -1.085487}, }; /* Le-Gascuel 2008 model data from Harry Yoo https://github.com/hyoo/FastTree */ double statLG08[MAXCODES] = {0.079066, 0.055941, 0.041977, 0.053052, 0.012937, 0.040767, 0.071586, 0.057337, 0.022355, 0.062157, 0.099081, 0.0646, 0.022951, 0.042302, 0.04404, 0.061197, 0.053287, 0.012066, 0.034155, 0.069147}; double matrixLG08[MAXCODES][MAXCODES] = { {-1.08959879,0.03361031,0.02188683,0.03124237,0.19680136,0.07668542,0.08211337,0.16335306,0.02837339,0.01184642,0.03125763,0.04242021,0.08887270,0.02005907,0.09311189,0.37375830,0.16916131,0.01428853,0.01731216,0.20144931}, {0.02378006,-0.88334349,0.04206069,0.00693409,0.02990323,0.15707674,0.02036079,0.02182767,0.13574610,0.00710398,0.01688563,0.35388551,0.02708281,0.00294931,0.01860218,0.04800569,0.03238902,0.03320688,0.01759004,0.00955956}, {0.01161996,0.03156149,-1.18705869,0.21308090,0.02219603,0.07118238,0.02273938,0.06034785,0.18928374,0.00803870,0.00287235,0.09004368,0.01557359,0.00375798,0.00679131,0.16825837,0.08398226,0.00190474,0.02569090,0.00351296}, {0.02096312,0.00657599,0.26929909,-0.86328733,0.00331871,0.02776660,0.27819699,0.04482489,0.04918511,0.00056712,0.00079981,0.01501150,0.00135537,0.00092395,0.02092662,0.06579888,0.02259266,0.00158572,0.00716768,0.00201422}, {0.03220119,0.00691547,0.00684065,0.00080928,-0.86781864,0.00109716,0.00004527,0.00736456,0.00828668,0.00414794,0.00768465,0.00017162,0.01156150,0.01429859,0.00097521,0.03602269,0.01479316,0.00866942,0.01507844,0.02534728}, {0.03953956,0.11446966,0.06913053,0.02133682,0.00345736,-1.24953177,0.16830979,0.01092385,0.19623161,0.00297003,0.02374496,0.13185209,0.06818543,0.00146170,0.02545052,0.04989165,0.04403378,0.00962910,0.01049079,0.00857458}, {0.07434507,0.02605508,0.03877888,0.37538659,0.00025048,0.29554848,-0.84254259,0.02497249,0.03034386,0.00316875,0.00498760,0.12936820,0.01243696,0.00134660,0.03002373,0.04380857,0.04327684,0.00557310,0.00859294,0.01754095}, {0.11846020,0.02237238,0.08243001,0.04844538,0.03263985,0.01536392,0.02000178,-0.50414422,0.01785951,0.00049912,0.00253779,0.01700817,0.00800067,0.00513658,0.01129312,0.09976552,0.00744439,0.01539442,0.00313512,0.00439779}, {0.00802225,0.05424651,0.10080372,0.02072557,0.01431930,0.10760560,0.00947583,0.00696321,-1.09324335,0.00243405,0.00818899,0.01558729,0.00989143,0.01524917,0.01137533,0.02213166,0.01306114,0.01334710,0.11863394,0.00266053}, {0.00931296,0.00789336,0.01190322,0.00066446,0.01992916,0.00452837,0.00275137,0.00054108,0.00676776,-1.41499789,0.25764421,0.00988722,0.26563382,0.06916358,0.00486570,0.00398456,0.06425393,0.00694043,0.01445289,0.66191466}, {0.03917027,0.02990732,0.00677980,0.00149374,0.05885464,0.05771026,0.00690325,0.00438541,0.03629495,0.41069624,-0.79375308,0.01362360,0.62543296,0.25688578,0.02467704,0.01806113,0.03001512,0.06139358,0.02968934,0.16870919}, {0.03465896,0.40866276,0.13857164,0.01827910,0.00085698,0.20893479,0.11674330,0.01916263,0.04504313,0.01027583,0.00888247,-0.97644156,0.04241650,0.00154510,0.02521473,0.04836478,0.07344114,0.00322392,0.00852278,0.01196402}, {0.02579765,0.01111131,0.00851489,0.00058635,0.02051079,0.03838702,0.00398738,0.00320253,0.01015515,0.09808327,0.14487451,0.01506968,-1.54195698,0.04128536,0.00229163,0.00796306,0.04636929,0.01597787,0.01104642,0.04357735}, {0.01073203,0.00223024,0.00378708,0.00073673,0.04675419,0.00151673,0.00079574,0.00378966,0.02885576,0.04707045,0.10967574,0.00101178,0.07609486,-0.81061579,0.00399600,0.01530562,0.00697985,0.10394083,0.33011973,0.02769432}, {0.05186360,0.01464471,0.00712508,0.01737179,0.00331981,0.02749383,0.01847072,0.00867414,0.02240973,0.00344749,0.01096857,0.01718973,0.00439734,0.00416018,-0.41664685,0.05893117,0.02516738,0.00418956,0.00394655,0.01305787}, {0.28928853,0.05251612,0.24529879,0.07590089,0.17040121,0.07489439,0.03745080,0.10648187,0.06058559,0.00392302,0.01115539,0.04581702,0.02123285,0.02214217,0.08188943,-1.42842431,0.39608294,0.01522956,0.02451220,0.00601987}, {0.11400727,0.03085239,0.10660988,0.02269274,0.06093244,0.05755704,0.03221430,0.00691855,0.03113348,0.05508469,0.01614250,0.06057985,0.10765893,0.00879238,0.03045173,0.34488735,-1.23444419,0.00750412,0.01310009,0.11660005}, {0.00218053,0.00716244,0.00054751,0.00036065,0.00808574,0.00284997,0.00093936,0.00323960,0.00720403,0.00134729,0.00747646,0.00060216,0.00840002,0.02964754,0.00114785,0.00300276,0.00169919,-0.44275283,0.03802969,0.00228662}, {0.00747852,0.01073967,0.02090366,0.00461457,0.03980863,0.00878929,0.00409985,0.00186756,0.18125441,0.00794180,0.01023445,0.00450612,0.01643896,0.26654152,0.00306072,0.01368064,0.00839668,0.10764993,-0.71435091,0.00851526}, {0.17617706,0.01181629,0.00578676,0.00262530,0.13547871,0.01454379,0.01694332,0.00530363,0.00822937,0.73635171,0.11773937,0.01280613,0.13129028,0.04526924,0.02050210,0.00680190,0.15130413,0.01310401,0.01723920,-1.33539639} };
serial_tree_learner.h
#ifndef LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #define LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #include <LightGBM/utils/random.h> #include <LightGBM/utils/array_args.h> #include <LightGBM/tree_learner.h> #include <LightGBM/dataset.h> #include <LightGBM/tree.h> #include "feature_histogram.hpp" #include "split_info.hpp" #include "data_partition.hpp" #include "leaf_splits.hpp" #include <cstdio> #include <vector> #include <random> #include <cmath> #include <memory> #ifdef USE_GPU // Use 4KBytes aligned allocator for ordered gradients and ordered hessians when GPU is enabled. // This is necessary to pin the two arrays in memory and make transferring faster. #include <boost/align/aligned_allocator.hpp> #endif namespace LightGBM { /*! * \brief Used for learning a tree by single machine */ class SerialTreeLearner: public TreeLearner { public: explicit SerialTreeLearner(const TreeConfig* tree_config); ~SerialTreeLearner(); void Init(const Dataset* train_data, bool is_constant_hessian) override; void ResetTrainingData(const Dataset* train_data) override; void ResetConfig(const TreeConfig* tree_config) override; Tree* Train(const score_t* gradients, const score_t *hessians, bool is_constant_hessian) override; Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override; void SetBaggingData(const data_size_t* used_indices, data_size_t num_data) override { data_partition_->SetUsedDataIndices(used_indices, num_data); } void AddPredictionToScore(const Tree* tree, double* out_score) const override { if (tree->num_leaves() <= 1) { return; } CHECK(tree->num_leaves() <= data_partition_->num_leaves()); #pragma omp parallel for schedule(static) for (int i = 0; i < tree->num_leaves(); ++i) { double output = static_cast<double>(tree->LeafOutput(i)); data_size_t cnt_leaf_data = 0; auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); for (data_size_t j = 0; j < cnt_leaf_data; ++j) { out_score[tmp_idx[j]] += output; } } } protected: /*! * \brief Some initial works before training */ virtual void BeforeTrain(); /*! * \brief Some initial works before FindBestSplit */ virtual bool BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf); virtual void FindBestSplits(); virtual void ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); /*! * \brief Partition tree and data according best split. * \param tree Current tree, will be splitted on this function. * \param best_leaf The index of leaf that will be splitted. * \param left_leaf The index of left leaf after splitted. * \param right_leaf The index of right leaf after splitted. */ virtual void Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf); /*! * \brief Get the number of data in a leaf * \param leaf_idx The index of leaf * \return The number of data in the leaf_idx leaf */ inline virtual data_size_t GetGlobalDataCountInLeaf(int leaf_idx) const; /*! \brief number of data */ data_size_t num_data_; /*! \brief number of features */ int num_features_; /*! \brief training data */ const Dataset* train_data_; /*! \brief gradients of current iteration */ const score_t* gradients_; /*! \brief hessians of current iteration */ const score_t* hessians_; /*! \brief training data partition on leaves */ std::unique_ptr<DataPartition> data_partition_; /*! \brief used for generate used features */ Random random_; /*! \brief used for sub feature training, is_feature_used_[i] = false means don't used feature i */ std::vector<int8_t> is_feature_used_; /*! \brief pointer to histograms array of parent of current leaves */ FeatureHistogram* parent_leaf_histogram_array_; /*! \brief pointer to histograms array of smaller leaf */ FeatureHistogram* smaller_leaf_histogram_array_; /*! \brief pointer to histograms array of larger leaf */ FeatureHistogram* larger_leaf_histogram_array_; /*! \brief store best split points for all leaves */ std::vector<SplitInfo> best_split_per_leaf_; /*! \brief stores best thresholds for all feature for smaller leaf */ std::unique_ptr<LeafSplits> smaller_leaf_splits_; /*! \brief stores best thresholds for all feature for larger leaf */ std::unique_ptr<LeafSplits> larger_leaf_splits_; #ifdef USE_GPU /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_; #else /*! \brief gradients of current iteration, ordered for cache optimized */ std::vector<score_t> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized */ std::vector<score_t> ordered_hessians_; #endif /*! \brief Store ordered bin */ std::vector<std::unique_ptr<OrderedBin>> ordered_bins_; /*! \brief True if has ordered bin */ bool has_ordered_bin_ = false; /*! \brief is_data_in_leaf_[i] != 0 means i-th data is marked */ std::vector<char> is_data_in_leaf_; /*! \brief used to cache historical histogram to speed up*/ HistogramPool histogram_pool_; /*! \brief config of tree learner*/ const TreeConfig* tree_config_; int num_threads_; std::vector<int> ordered_bin_indices_; bool is_constant_hessian_; }; inline data_size_t SerialTreeLearner::GetGlobalDataCountInLeaf(int leafIdx) const { if (leafIdx >= 0) { return data_partition_->leaf_count(leafIdx); } else { return 0; } } } // namespace LightGBM #endif // LightGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/APINotes/APINotesManager.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <functional> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; /// A key method to reduce duplicate debug info from Sema. virtual void anchor(); ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 29; static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; api_notes::APINotesManager APINotes; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } /// \brief Callback to the parser to parse a type expressed as a string. std::function<TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback; class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal swift_name /// attribute for the decl \p D. Raise a diagnostic if the name is invalid /// for the given declaration. /// /// For a function, this will validate a compound Swift name, /// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, /// and the function will output the number of parameter names, and whether /// this is a single-arg initializer. /// /// For a type, enum constant, property, or variable declaration, this will /// validate either a simple identifier, or a qualified /// <code>context.identifier</code> name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation ArgLoc, const IdentifierInfo *AttrName); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range); bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); QualType adjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name, bool Override); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Map any API notes provided for this declaration to attributes on the /// declaration. /// /// Triggered by declaration-attribute processing. void ProcessAPINotes(Decl *D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Check whether a nullability type specifier can be added to the given /// type through some means not written in source (e.g. API notes). /// /// \param type The type to which the nullability specifier will be /// added. On success, this type will be updated appropriately. /// /// \param nullability The nullability specifier to add. /// /// \param diagLoc The location to use for diagnostics. /// /// \param allowArrayTypes Whether to accept nullability specifiers on an /// array type (e.g., because it will decay to a pointer). /// /// \param overrideExisting Whether to override an existing, locally-specified /// nullability specifier rather than complaining about the conflict. /// /// \returns true if nullability cannot be applied, false otherwise. bool checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting); /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildUniqueStableName(SourceLocation Loc, TypeSourceInfo *Operand); ExprResult BuildUniqueStableName(SourceLocation Loc, Expr *E); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType Ty); ExprResult ActOnUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied because it was ill-formed. void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation, StringRef Diagnostic); void DiagnoseRedeclarationConstraintMismatch(SourceLocation Old, SourceLocation New); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. ResultTypeCompatibilityKind checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method, const ObjCInterfaceDecl *CurrentClass); void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = std::string(Ext); } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. SmallVector<SourceLocation, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. FunctionDecl * ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(Scope *S, Declarator &D); /// Register \p FD as specialization of \p BaseFD in the current `omp /// begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( FunctionDecl *FD, FunctionDecl *BaseFD); public: /// Can we exit a scope at the moment. bool isInOpenMPDeclareVariantScope() { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); /// Check if the expression is allowed to be used in expressions for the /// offloading devices. void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; DeviceDiagBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
convolution_3x3_pack1ton_fp16s.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void conv3x3s1_pack1ton_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); vfloat16m1_t _bias0 = bias ? vle16_v_f16m1(bias + p * packn, vl) : vfmv_v_f_f16m1(0.f, vl); out0.fill(_bias0); const __fp16* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { __fp16* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); vfloat16m1_t _k00 = vle16_v_f16m1(k0, vl); vfloat16m1_t _k01 = vle16_v_f16m1(k0 + packn, vl); vfloat16m1_t _k02 = vle16_v_f16m1(k0 + packn * 2, vl); vfloat16m1_t _k10 = vle16_v_f16m1(k0 + packn * 3, vl); vfloat16m1_t _k11 = vle16_v_f16m1(k0 + packn * 4, vl); vfloat16m1_t _k12 = vle16_v_f16m1(k0 + packn * 5, vl); vfloat16m1_t _k20 = vle16_v_f16m1(k0 + packn * 6, vl); vfloat16m1_t _k21 = vle16_v_f16m1(k0 + packn * 7, vl); vfloat16m1_t _k22 = vle16_v_f16m1(k0 + packn * 8, vl); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); vfloat16m1_t _sum2 = vle16_v_f16m1(outptr0 + packn * 2, vl); vfloat16m1_t _sum3 = vle16_v_f16m1(outptr0 + packn * 3, vl); vfloat16m1_t _sum4 = vle16_v_f16m1(outptr0 + packn * 4, vl); vfloat16m1_t _sum5 = vle16_v_f16m1(outptr0 + packn * 5, vl); vfloat16m1_t _sum6 = vle16_v_f16m1(outptr0 + packn * 6, vl); vfloat16m1_t _sum7 = vle16_v_f16m1(outptr0 + packn * 7, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[1], _k00, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[2], _k00, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[3], _k00, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[4], _k00, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[5], _k00, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[6], _k00, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[7], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k01, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[3], _k01, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[4], _k01, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[5], _k01, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[6], _k01, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[7], _k01, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[8], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k02, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[4], _k02, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[5], _k02, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[6], _k02, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[7], _k02, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[8], _k02, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[9], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[1], _k10, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[2], _k10, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[3], _k10, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[4], _k10, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[5], _k10, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[6], _k10, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[7], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k11, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[3], _k11, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[4], _k11, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[5], _k11, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[6], _k11, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[7], _k11, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[8], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k12, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[4], _k12, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[5], _k12, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[6], _k12, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[7], _k12, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[8], _k12, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[9], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[1], _k20, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[2], _k20, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[3], _k20, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[4], _k20, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[5], _k20, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[6], _k20, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[7], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k21, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[3], _k21, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[4], _k21, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[5], _k21, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[6], _k21, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[7], _k21, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[8], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k22, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[4], _k22, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[5], _k22, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[6], _k22, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[7], _k22, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[8], _k22, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[9], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl); vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl); vse16_v_f16m1(outptr0 + packn * 4, _sum4, vl); vse16_v_f16m1(outptr0 + packn * 5, _sum5, vl); vse16_v_f16m1(outptr0 + packn * 6, _sum6, vl); vse16_v_f16m1(outptr0 + packn * 7, _sum7, vl); outptr0 += packn * 8; r0 += 8; r1 += 8; r2 += 8; } for (; j + 3 < outw; j += 4) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); vfloat16m1_t _sum2 = vle16_v_f16m1(outptr0 + packn * 2, vl); vfloat16m1_t _sum3 = vle16_v_f16m1(outptr0 + packn * 3, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[1], _k00, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[2], _k00, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[3], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k01, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[3], _k01, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[4], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k02, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[4], _k02, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[5], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[1], _k10, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[2], _k10, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[3], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k11, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[3], _k11, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[4], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k12, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[4], _k12, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[5], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[1], _k20, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[2], _k20, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[3], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k21, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[3], _k21, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[4], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k22, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[4], _k22, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[5], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl); vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl); outptr0 += packn * 4; r0 += 4; r1 += 4; r2 += 4; } for (; j + 1 < outw; j += 2) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[1], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[1], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[1], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); outptr0 += packn * 2; r0 += 2; r1 += 2; r2 += 2; } for (; j < outw; j++) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); outptr0 += packn; r0 += 1; r1 += 1; r2 += 1; } r0 += 2; r1 += 2; r2 += 2; } k0 += 9 * packn; } } } static void conv3x3s2_pack1ton_fp16sa_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 2; const word_type vl = vsetvl_e16m1(packn); int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const __fp16* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); vfloat16m1_t _bias0 = bias ? vle16_v_f16m1(bias + p * packn, vl) : vfmv_v_f_f16m1(0.f, vl); out0.fill(_bias0); const __fp16* k0 = kernel.channel(p); int q = 0; for (; q < inch; q++) { __fp16* outptr0 = out0; const Mat img0 = bottom_blob.channel(q); const __fp16* r0 = img0.row<const __fp16>(0); const __fp16* r1 = img0.row<const __fp16>(1); const __fp16* r2 = img0.row<const __fp16>(2); vfloat16m1_t _k00 = vle16_v_f16m1(k0, vl); vfloat16m1_t _k01 = vle16_v_f16m1(k0 + packn, vl); vfloat16m1_t _k02 = vle16_v_f16m1(k0 + packn * 2, vl); vfloat16m1_t _k10 = vle16_v_f16m1(k0 + packn * 3, vl); vfloat16m1_t _k11 = vle16_v_f16m1(k0 + packn * 4, vl); vfloat16m1_t _k12 = vle16_v_f16m1(k0 + packn * 5, vl); vfloat16m1_t _k20 = vle16_v_f16m1(k0 + packn * 6, vl); vfloat16m1_t _k21 = vle16_v_f16m1(k0 + packn * 7, vl); vfloat16m1_t _k22 = vle16_v_f16m1(k0 + packn * 8, vl); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 7 < outw; j += 8) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); vfloat16m1_t _sum2 = vle16_v_f16m1(outptr0 + packn * 2, vl); vfloat16m1_t _sum3 = vle16_v_f16m1(outptr0 + packn * 3, vl); vfloat16m1_t _sum4 = vle16_v_f16m1(outptr0 + packn * 4, vl); vfloat16m1_t _sum5 = vle16_v_f16m1(outptr0 + packn * 5, vl); vfloat16m1_t _sum6 = vle16_v_f16m1(outptr0 + packn * 6, vl); vfloat16m1_t _sum7 = vle16_v_f16m1(outptr0 + packn * 7, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k00, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[4], _k00, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[6], _k00, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[8], _k00, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[10], _k00, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[12], _k00, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[14], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k01, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[5], _k01, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[7], _k01, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[9], _k01, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[11], _k01, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[13], _k01, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[15], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[4], _k02, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[6], _k02, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[8], _k02, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r0[10], _k02, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r0[12], _k02, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r0[14], _k02, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r0[16], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k10, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[4], _k10, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[6], _k10, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[8], _k10, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[10], _k10, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[12], _k10, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[14], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k11, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[5], _k11, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[7], _k11, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[9], _k11, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[11], _k11, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[13], _k11, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[15], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[4], _k12, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[6], _k12, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[8], _k12, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r1[10], _k12, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r1[12], _k12, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r1[14], _k12, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r1[16], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k20, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[4], _k20, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[6], _k20, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[8], _k20, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[10], _k20, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[12], _k20, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[14], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k21, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[5], _k21, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[7], _k21, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[9], _k21, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[11], _k21, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[13], _k21, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[15], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[4], _k22, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[6], _k22, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[8], _k22, vl); _sum4 = vfmacc_vf_f16m1(_sum4, r2[10], _k22, vl); _sum5 = vfmacc_vf_f16m1(_sum5, r2[12], _k22, vl); _sum6 = vfmacc_vf_f16m1(_sum6, r2[14], _k22, vl); _sum7 = vfmacc_vf_f16m1(_sum7, r2[16], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl); vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl); vse16_v_f16m1(outptr0 + packn * 4, _sum4, vl); vse16_v_f16m1(outptr0 + packn * 5, _sum5, vl); vse16_v_f16m1(outptr0 + packn * 6, _sum6, vl); vse16_v_f16m1(outptr0 + packn * 7, _sum7, vl); outptr0 += packn * 8; r0 += 16; r1 += 16; r2 += 16; } for (; j + 3 < outw; j += 4) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); vfloat16m1_t _sum2 = vle16_v_f16m1(outptr0 + packn * 2, vl); vfloat16m1_t _sum3 = vle16_v_f16m1(outptr0 + packn * 3, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k00, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[4], _k00, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[6], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k01, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[5], _k01, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[7], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[4], _k02, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r0[6], _k02, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r0[8], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k10, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[4], _k10, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[6], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k11, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[5], _k11, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[7], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[4], _k12, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r1[6], _k12, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r1[8], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k20, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[4], _k20, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[6], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k21, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[5], _k21, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[7], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[4], _k22, vl); _sum2 = vfmacc_vf_f16m1(_sum2, r2[6], _k22, vl); _sum3 = vfmacc_vf_f16m1(_sum3, r2[8], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); vse16_v_f16m1(outptr0 + packn * 2, _sum2, vl); vse16_v_f16m1(outptr0 + packn * 3, _sum3, vl); outptr0 += packn * 4; r0 += 8; r1 += 8; r2 += 8; } for (; j + 1 < outw; j += 2) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); vfloat16m1_t _sum1 = vle16_v_f16m1(outptr0 + packn, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[2], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[3], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r0[4], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[2], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[3], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r1[4], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[2], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[3], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); _sum1 = vfmacc_vf_f16m1(_sum1, r2[4], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); vse16_v_f16m1(outptr0 + packn, _sum1, vl); outptr0 += packn * 2; r0 += 4; r1 += 4; r2 += 4; } for (; j < outw; j++) { vfloat16m1_t _sum0 = vle16_v_f16m1(outptr0, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[0], _k00, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[1], _k01, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r0[2], _k02, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[0], _k10, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[1], _k11, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r1[2], _k12, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[0], _k20, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[1], _k21, vl); _sum0 = vfmacc_vf_f16m1(_sum0, r2[2], _k22, vl); vse16_v_f16m1(outptr0, _sum0, vl); outptr0 += packn; r0 += 2; r1 += 2; r2 += 2; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } k0 += 9 * packn; } } }
rose_v1_outer_only.c
/* Only the outmost loop can be parallelized */ #include <omp.h> void foo() { int n = 100; int m = 100; double b[n][m]; int i; int j; #pragma omp parallel for private (i,j) firstprivate (n,m) for (i = 0; i <= n - 1; i += 1) { for (j = 1; j <= m - 1; j += 1) { b[i][j] = b[i][j - 1]; } } } /* Unparallelizable loop at line:9 due to the following dependencies: 1*1 TRUE_DEP DATA_DEP; commonlevel = 1 CarryLevel = 0 Is precise SgPntrArrRefExp:(b[i])[j]@10:14->SgPntrArrRefExp:((b[i])[j - 1])@10:19 == -1;||:: */
refinePoses.h
#ifndef SP_SEGMENTER_REFINE_POSES #define SP_SEGMENTER_REFINE_POSES std::vector<poseT> RefinePoses(const pcl::PointCloud<myPointXYZ>::Ptr scene, const std::vector<ModelT> &mesh_set, const std::vector<poseT> &all_poses) { int pose_num = all_poses.size(); std::vector<ModelT> est_models(pose_num); pcl::PointCloud<myPointXYZ>::Ptr down_scene(new pcl::PointCloud<myPointXYZ>()); pcl::VoxelGrid<myPointXYZ> sor; sor.setInputCloud(scene); sor.setLeafSize(0.005, 0.005, 0.005); sor.filter(*down_scene); #pragma omp parallel for schedule(dynamic, 1) for(int i = 0 ; i < pose_num ; i++ ){ for( std::size_t j = 0 ; j < mesh_set.size() ; j++ ){ if( mesh_set[j].model_label == all_poses[i].model_name ) { est_models[i].model_label = all_poses[i].model_name; est_models[i].model_cloud = pcl::PointCloud<myPointXYZ>::Ptr (new pcl::PointCloud<myPointXYZ>()); pcl::transformPointCloud(*mesh_set[j].model_cloud, *est_models[i].model_cloud, all_poses[i].shift, all_poses[i].rotation); break; } } } std::vector< pcl::search::KdTree<myPointXYZ>::Ptr > tree_set(est_models.size()); #pragma omp parallel for schedule(dynamic, 1) for( int i = 0 ; i < pose_num ; i++ ) { tree_set[i] = pcl::search::KdTree<myPointXYZ>::Ptr (new pcl::search::KdTree<myPointXYZ>()); tree_set[i]->setInputCloud(est_models[i].model_cloud); } std::vector<int> votes(pose_num, 0); std::vector< std::vector<int> > adj_graph(pose_num); for( int i = 0 ; i < pose_num ; i++ ) adj_graph[i].resize(pose_num, 0); float sqrT = 0.01*0.01; int down_num = down_scene->size(); std::vector< std::vector<int> > bin_vec(down_num); #pragma omp parallel for for(int i = 0 ; i < pose_num ; i++ ) { int count = 0; for( pcl::PointCloud<myPointXYZ>::const_iterator it = down_scene->begin() ; it < down_scene->end() ; it++, count++ ) { std::vector<int> idx (1); std::vector<float> sqrDist (1); int nres = tree_set[i]->nearestKSearch(*it, 1, idx, sqrDist); if ( nres >= 1 && sqrDist[0] <= sqrT ) { #pragma omp critical { bin_vec[count].push_back(i); } votes[i]++; } } } for( int it = 0 ; it < down_num ; it++ ) for( std::vector<int>::iterator ii = bin_vec[it].begin() ; ii < bin_vec[it].end() ; ii++ ) for( std::vector<int>::iterator jj = ii+1 ; jj < bin_vec[it].end() ; jj++ ) { adj_graph[*ii][*jj]++; adj_graph[*jj][*ii]++; } std::vector<bool> dead_flag(pose_num, 0); for( int i = 0 ; i < pose_num ; i++ ){ if( dead_flag[i] == true ) continue; for( int j = i+1 ; j < pose_num ; j++ ) { if( dead_flag[j] == true ) continue; int min_tmp = std::min(votes[i], votes[j]); if( (adj_graph[i][j]+0.0) / min_tmp >= 0.3 ) { std::cerr << votes[i] << " " << i << std::endl; std::cerr << votes[j] << " " << j << std::endl; if( votes[i] > votes[j] ) dead_flag[j] = true; else { dead_flag[i] = true; break; } } } } std::vector<poseT> refined_poses; for( int i = 0 ; i < pose_num ; i++ ) if( dead_flag[i] == false ) refined_poses.push_back(all_poses[i]); return refined_poses; } #endif
XSHA_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2008,2011 by Solar Designer * * Intrinsics support added by magnum 2011. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_XSHA; #elif FMT_REGISTERS_H john_register_one(&fmt_XSHA); #else #include <string.h> #include "arch.h" #ifdef MMX_COEF #define NBKEYS (MMX_COEF * SHA1_SSE_PARA) #ifdef _OPENMP static unsigned int omp_t = 1; #include <omp.h> #define OMP_SCALE 128 #endif #endif #include "sse-intrinsics.h" #include "params.h" #include "common.h" #include "formats.h" #include "sha.h" #include "johnswap.h" #include "memdbg.h" #define FORMAT_LABEL "xsha" #define FORMAT_NAME "Mac OS X 10.4 - 10.6" #define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 51 #define CIPHERTEXT_LENGTH 48 #define BINARY_SIZE 20 #define BINARY_ALIGN 4 #define SALT_SIZE 4 #define SALT_ALIGN 4 #ifdef MMX_COEF #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define GETPOS(i, index) ( (index&(MMX_COEF-1))*4 + ((i)&(0xffffffff-3))*MMX_COEF + (3-((i)&3)) + (index>>(MMX_COEF>>1))*SHA_BUF_SIZ*MMX_COEF*4 ) //for endianity conversion #else #define MIN_KEYS_PER_CRYPT 1 #ifdef _OPENMP #define MAX_KEYS_PER_CRYPT (0x200 * 3) #else #define MAX_KEYS_PER_CRYPT 0x100 #endif #endif static struct fmt_tests tests[] = { {"12345678F9083C7F66F46A0A102E4CC17EC08C8AF120571B", "abc"}, {"12345678EB8844BFAF2A8CBDD587A37EF8D4A290680D5818", "azertyuiop1"}, {"3234C32AAA335FD20E3F95870E5851BDBE942B79CE4FDD92", "azertyuiop2"}, {"01295B67659E95F32931CEDB3BA50289E2826AF3D5A1422F", "apple"}, {"0E6A48F765D0FFFFF6247FA80D748E615F91DD0C7431E4D9", "macintosh"}, {"A320163F1E6DB42C3949F7E232888ACC7DB7A0A17E493DBA", "test"}, {NULL} }; #ifdef MMX_COEF static ARCH_WORD_32 (*saved_key); static ARCH_WORD_32 (*crypt_key); static ARCH_WORD_32 cur_salt; #else static char saved_key[MAX_KEYS_PER_CRYPT][PLAINTEXT_LENGTH + 1]; static int saved_key_length[MAX_KEYS_PER_CRYPT]; static SHA_CTX ctx_salt; static ARCH_WORD_32 crypt_out[MAX_KEYS_PER_CRYPT][5]; #endif static void init(struct fmt_main *self) { #ifdef MMX_COEF #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt = omp_t * NBKEYS; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt = omp_t * NBKEYS; #endif saved_key = mem_calloc_tiny(SHA_BUF_SIZ*4 * self->params.max_keys_per_crypt, MEM_ALIGN_SIMD); crypt_key = mem_calloc_tiny(BINARY_SIZE * self->params.max_keys_per_crypt, MEM_ALIGN_SIMD); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *pos; /* Require uppercase hex digits (assume ASCII) */ pos = ciphertext; while (atoi16[ARCH_INDEX(*pos)] != 0x7F && *pos < 'a') pos++; return !*pos && pos - ciphertext == CIPHERTEXT_LENGTH; } static void *get_binary(char *ciphertext) { static unsigned char *out; char *p; int i; if (!out) out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD); p = ciphertext + 8; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef MMX_COEF alter_endianity(out, BINARY_SIZE); #endif return out; } static void *salt(char *ciphertext) { static unsigned int outbuf[SALT_SIZE / sizeof(int)]; unsigned char *out = (unsigned char*)outbuf; char *p; int i; p = ciphertext; for (i = 0; i < SALT_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef MMX_COEF alter_endianity(out, SALT_SIZE); #endif return out; } #ifdef MMX_COEF static int get_hash_0(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xf; } static int get_hash_1(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xff; } static int get_hash_2(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xfff; } static int get_hash_3(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xffff; } static int get_hash_4(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xfffff; } static int get_hash_5(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0xffffff; } static int get_hash_6(int index) { unsigned int x,y; x = index&3; y = index/4; return ((ARCH_WORD_32*)crypt_key)[x+y*MMX_COEF*5] & 0x7ffffff; } #else static int get_hash_0(int index) { return crypt_out[index][0] & 0xF; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xFF; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xFFF; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xFFFF; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xFFFFF; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xFFFFFF; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7FFFFFF; } #endif static int salt_hash(void *salt) { return *(ARCH_WORD_32 *)salt & (SALT_HASH_SIZE - 1); } static void set_salt(void *salt) { #ifdef MMX_COEF cur_salt = *(ARCH_WORD_32*)salt; #else SHA1_Init(&ctx_salt); SHA1_Update(&ctx_salt, salt, SALT_SIZE); #endif } static void set_key(char *key, int index) { #ifdef MMX_COEF const ARCH_WORD_32 *wkey = (ARCH_WORD_32*)key; ARCH_WORD_32 *keybuffer = &saved_key[(index&(MMX_COEF-1)) + (index>>(MMX_COEF>>1))*SHA_BUF_SIZ*MMX_COEF + MMX_COEF]; ARCH_WORD_32 *keybuf_word = keybuffer; unsigned int len; ARCH_WORD_32 temp; len = 4; while((temp = *wkey++) & 0xff) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP(temp | (0x80 << 24)); len+=3; goto key_cleaning; } *keybuf_word = JOHNSWAP(temp); len += 4; keybuf_word += MMX_COEF; } *keybuf_word = 0x80000000; key_cleaning: keybuf_word += MMX_COEF; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += MMX_COEF; } keybuffer[14*MMX_COEF] = len << 3; #else int length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; saved_key_length[index] = length; memcpy(saved_key[index], key, length); #endif } static char *get_key(int index) { #ifdef MMX_COEF unsigned int i,s; static char out[PLAINTEXT_LENGTH + 1]; s = ((unsigned int *)saved_key)[15*MMX_COEF + (index&3) + (index>>2)*SHA_BUF_SIZ*MMX_COEF] >> 3; for(i = 0; i < (s - SALT_SIZE); i++) out[i] = ((char*)saved_key)[ GETPOS((i + SALT_SIZE), index) ]; out[i] = 0; return (char *) out; #else saved_key[index][saved_key_length[index]] = 0; return saved_key[index]; #endif } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; #ifdef MMX_COEF int i = 0; #if defined(_OPENMP) #pragma omp parallel for for (i=0; i < omp_t; i++) { #endif unsigned int *in = &saved_key[i*NBKEYS*SHA_BUF_SIZ]; unsigned int *out = &crypt_key[i*NBKEYS*BINARY_SIZE/4]; unsigned int j; for (j=0; j < NBKEYS; j++) in[(j&(MMX_COEF-1)) + (j>>(MMX_COEF>>1))*SHA_BUF_SIZ*MMX_COEF] = cur_salt; SSESHA1body(in, out, NULL, SSEi_MIXED_IN); #if defined(_OPENMP) } #endif #else int i; #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(ctx_salt, count, saved_key, saved_key_length, crypt_out) #endif for (i = 0; i < count; i++) { SHA_CTX ctx; memcpy(&ctx, &ctx_salt, sizeof(ctx)); SHA1_Update(&ctx, saved_key[i], saved_key_length[i]); SHA1_Final((unsigned char *)(crypt_out[i]), &ctx); } #endif return count; } static int cmp_all(void *binary, int count) { #ifdef MMX_COEF unsigned int x,y=0; #ifdef _OPENMP for(;y<SHA1_SSE_PARA*omp_t;y++) #else for(;y<SHA1_SSE_PARA;y++) #endif for(x=0;x<MMX_COEF;x++) { if( ((ARCH_WORD_32 *)binary)[0] == ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5] ) return 1; } return 0; #else ARCH_WORD_32 b0 = *(ARCH_WORD_32 *)binary; int i; for (i = 0; i < count; i++) { if (b0 != crypt_out[i][0]) continue; if (!memcmp(binary, crypt_out[i], BINARY_SIZE)) return 1; } return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef MMX_COEF unsigned int x,y; x = index&3; y = index/4; if( ((ARCH_WORD_32 *)binary)[0] != ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5] ) return 0; if( ((ARCH_WORD_32 *)binary)[1] != ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5+MMX_COEF] ) return 0; if( ((ARCH_WORD_32 *)binary)[2] != ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5+2*MMX_COEF] ) return 0; if( ((ARCH_WORD_32 *)binary)[3] != ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5+3*MMX_COEF] ) return 0; if( ((ARCH_WORD_32 *)binary)[4] != ((ARCH_WORD_32 *)crypt_key)[x+y*MMX_COEF*5+4*MMX_COEF] ) return 0; return 1; #else return !memcmp(binary, crypt_out[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_XSHA = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_OMP | FMT_CASE | FMT_8_BIT, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
rose_v1_scalar_output.c
/* * Scalar-to-scalar output dependencies * */ #include <omp.h> int a[100]; // A private case void foo2() { int i; int tmp; #pragma omp parallel for private (tmp,i) for (i = 0; i <= 99; i += 1) { tmp = a[i] + i; } } // A lastprivate case void foo() { int i; int tmp; #pragma omp parallel for private (i) lastprivate (tmp) for (i = 0; i <= 99; i += 1) { tmp = a[i] + i; } i = tmp; }
mult_impl_gsl.h
#ifndef _MULT_IMPL_GSL_H #define _MULT_IMPL_GSL_H CPS_END_NAMESPACE #include<alg/a2a/gsl_wrapper.h> CPS_START_NAMESPACE //Implementations for meson field contractions template<typename mf_Policies, template <typename> class lA2AfieldL, template <typename> class lA2AfieldR, template <typename> class rA2AfieldL, template <typename> class rA2AfieldR > class _mult_impl{ //necessary to avoid an annoying ambigous overload when mesonfield friends mult public: typedef gsl_wrapper<typename mf_Policies::ScalarComplexType::value_type> gw; //Matrix product of meson field pairs //out(t1,t4) = l(t1,t2) * r(t3,t4) (The stored timeslices are only used to unpack TimePackedIndex so it doesn't matter if t2 and t3 are thrown away; their indices are contracted over hence the times are not needed) inline static int nearest_divisor(const int of, const int base_divisor){ //printf("nearest_divisor of %d, base_divisor %d\n", of, base_divisor); fflush(stdout); assert(base_divisor > 0); if(of % base_divisor == 0) return base_divisor; int nearest_below = base_divisor; bool no_nearest_below = false; while(of % nearest_below != 0){ --nearest_below; if(nearest_below == 0){ no_nearest_below = true; break; } } int nearest_above = base_divisor; bool no_nearest_above = false; while(of % nearest_above !=0){ ++nearest_above; if(nearest_above == of){ no_nearest_above = true; break; } } if(no_nearest_above && no_nearest_below) return of; if(no_nearest_below) return nearest_above; if(no_nearest_above) return nearest_below; int sep_above = nearest_above - base_divisor; int sep_below = base_divisor - nearest_below; return sep_above < sep_below ? nearest_above : nearest_below; } static void mult(A2AmesonField<mf_Policies,lA2AfieldL,rA2AfieldR> &out, const A2AmesonField<mf_Policies,lA2AfieldL,lA2AfieldR> &l, const A2AmesonField<mf_Policies,rA2AfieldL,rA2AfieldR> &r, const bool node_local){ typedef typename mf_Policies::ScalarComplexType ScalarComplexType; typedef typename ScalarComplexType::value_type mf_Float; assert( (void*)&out != (void*)&l || (void*)&out != (void*)&r ); if(! l.getColParams().paramsEqual( r.getRowParams() ) ){ if(!UniqueID()){ printf("mult(): Illegal matrix product: underlying vector parameters must match\n"); fflush(stdout); std::cout << "left-column: " << l.getColParams().print() << "\n"; std::cout << "right-row: " << r.getRowParams().print() << "\n"; std::cout.flush(); } exit(-1); } out.setup(l.getRowParams(),r.getColParams(), l.tl, r.tr ); //zeroes output, so safe to re-use int ni = l.getNrows(); int nk = r.getNcols(); typedef typename A2AmesonField<mf_Policies,lA2AfieldL,lA2AfieldR>::RightDilutionType LeftDilutionType; typedef typename A2AmesonField<mf_Policies,rA2AfieldL,rA2AfieldR>::LeftDilutionType RightDilutionType; ModeContractionIndices<LeftDilutionType,RightDilutionType> j_ind2(l.getColParams()); //these maps could be cached somewhere modeIndexSet lmodeparams; lmodeparams.time = l.tr; modeIndexSet rmodeparams; rmodeparams.time = r.tl; int nj = j_ind2.getNindices(lmodeparams,rmodeparams); int jlmap[nj], jrmap[nj]; for(int j = 0; j < nj; j++) j_ind2.getBothIndices(jlmap[j],jrmap[j],j,lmodeparams,rmodeparams); //Try a blocked matrix multiply //Because ni, nj are different and not necessarily multiples of a common blocking we need to dynamically choose the block size int nodes = 1; for(int i=0;i<5;i++) nodes *= GJP.Nodes(i); int compute_elements = omp_get_max_threads() * ( node_local ? 1 : nodes ); //Want the total number of blocks to be close to the number of compute elements = (number of nodes)*(number of threads) //We shouldn't just take the cubed-root though because quite often the number of indices differs substantially //We want ni0 * nj0 * nk0 = nodes //and the ratios to be approximately the same between the number of blocks and the number of indices //Take ratios wrt smallest so these are always >=1 int smallest = ni; if(nj < smallest) smallest = nj; if(nk < smallest) smallest = nk; int ratios[3] = {ni/smallest, nj/smallest, nk/smallest}; int base = (int)pow( compute_elements/ratios[0]/ratios[1]/ratios[2], 1/3.); //compute_element if(!base) ++base; int ni0 = nearest_divisor(ni, ratios[0]*base); int nj0 = nearest_divisor(nj, ratios[1]*base); int nk0 = nearest_divisor(nk, ratios[2]*base); assert(ni % ni0 == 0); assert(nj % nj0 == 0); assert(nk % nk0 == 0); int bi = ni/ni0; int bj = nj/nj0; int bk = nk/nk0; //parallelize ijk int work = ni0 * nj0 * nk0; int node_work, node_off; bool do_work; getNodeWork(work,node_work,node_off,do_work,node_local); //if(!UniqueID()) printf("mult sizes %d %d %d block sizes %d %d %d, num blocks %d %d %d. Work %d, node_work %d\n",ni,nj,nk,bi,bj,bk,ni0,nj0,nk0,work,node_work); if(do_work){ Float t1 = dclock(); //complex mult re = re*re - im*im, im = re*im + im*re //6 flops //complex add 2 flops Float flops_total = Float(ni)*Float(nk)*Float(nj)*8.; A2AmesonField<mf_Policies,lA2AfieldL,lA2AfieldR> lreord; A2AmesonField<mf_Policies,rA2AfieldL,rA2AfieldR> rreord; #ifndef MEMTEST_MODE r.rowReorder(rreord,jrmap,nj); l.colReorder(lreord,jlmap,nj); #endif typename gw::matrix_complex *lreord_gsl = gw::matrix_complex_alloc(ni,nj); typename gw::matrix_complex *rreord_gsl = gw::matrix_complex_alloc(nj,nk); #ifndef MEMTEST_MODE #pragma omp parallel for for(int i=0;i<ni;i++) for(int j=0;j<nj;j++){ const ScalarComplexType & el = lreord(i, j); mf_Float *el_gsl = (mf_Float*)gw::matrix_complex_ptr(lreord_gsl,i,j); *(el_gsl++) = std::real(el); *(el_gsl) = std::imag(el); } #pragma omp parallel for for(int j=0;j<nj;j++) for(int k=0;k<nk;k++){ const ScalarComplexType & el = rreord(j, k); mf_Float *el_gsl = (mf_Float*)gw::matrix_complex_ptr(rreord_gsl,j,k); *(el_gsl++) = std::real(el); *(el_gsl) = std::imag(el); } #endif static const int lcol_stride = 1; int rrow_stride = rreord.getNcols(); #pragma omp parallel for for(int i0j0k0 = node_off; i0j0k0 < node_off + node_work; ++i0j0k0){ int rem = i0j0k0; int k0 = rem % nk0; rem /= nk0; int j0 = rem % nj0; rem /= nj0; int i0 = rem; i0 *= bi; j0 *= bj; k0 *= bk; typename gw::complex tmp; typename gw::matrix_complex *tmp_out = gw::matrix_complex_alloc(bi,bk); typename gw::matrix_complex_const_view ijblock_view = gw::matrix_complex_const_submatrix(lreord_gsl,i0,j0,bi,bj); typename gw::matrix_complex_const_view jkblock_view = gw::matrix_complex_const_submatrix(rreord_gsl,j0,k0,bj,bk); const typename gw::matrix_complex *const ijblock = &ijblock_view.matrix; //gw::matrix_complex_alloc(bi,bj); const typename gw::matrix_complex *const jkblock = &jkblock_view.matrix; //gw::matrix_complex_alloc(bj,bk); typename gw::complex one; GSL_SET_COMPLEX(&one,1.0,0.0); typename gw::complex zero; GSL_SET_COMPLEX(&zero,0.0,0.0); #ifndef MEMTEST_MODE gw::matrix_complex_set_zero(tmp_out); gw::blas_gemm(CblasNoTrans, CblasNoTrans, one, ijblock, jkblock, zero, tmp_out); for(int i=0;i<bi;i++) for(int k=0;k<bk;k++){ mf_Float const* el = (mf_Float const*)gw::matrix_complex_ptr(tmp_out,i,k); mf_Float(&out_el)[2] = reinterpret_cast<mf_Float(&)[2]>(out(i0+i,k0+k)); #pragma omp atomic out_el[0] += *(el++); #pragma omp atomic out_el[1] += *(el); } #endif gw::matrix_complex_free(tmp_out); } Float t2 = dclock(); Float flops_per_sec = flops_total/(t2-t1); //if(!UniqueID()) printf("node mult flops/s %g (time %f total flops %g)\n",flops_per_sec,t2-t1,flops_total); gw::matrix_complex_free(lreord_gsl); gw::matrix_complex_free(rreord_gsl); } Float time = -dclock(); if(!node_local) out.nodeSum(); time += dclock(); //if(!UniqueID()) printf("mult comms time %g s\n",time); } }; #endif
GB_subref_phase0.c
//------------------------------------------------------------------------------ // GB_subref_phase0: find vectors of C = A(I,J) and determine I,J properties //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ #include "GB_subref.h" #define GB_Ai(p) GB_UNFLIP (Ai [p]) //------------------------------------------------------------------------------ // GB_find_Ap_start_end //------------------------------------------------------------------------------ // Find pA and pA_end so that Ai,Ax [pA:pA_end-1] contains the vector // A(imin:imax,kA). If A(:,kA) is dense, [pA:pA_end-1] is the entire dense // vector (it is not trimmed). Otherwise, if A(imin:imax,kA) is empty, then // pA and pA_end are set to -1 to denote an empty list. The resulting pointers // are then returned in Ap_start [kC] and Ap_end [kC]. static inline void GB_find_Ap_start_end ( // input, not modified const int64_t kA, const int64_t *GB_RESTRICT Ap, const int64_t *GB_RESTRICT Ai, const int64_t avlen, const int64_t imin, const int64_t imax, const int64_t kC, const int64_t nzombies, // output: Ap_start [kC] and Ap_end [kC]: int64_t *GB_RESTRICT Ap_start, int64_t *GB_RESTRICT Ap_end ) { //-------------------------------------------------------------------------- // get A(:,kA) //-------------------------------------------------------------------------- int64_t pA = Ap [kA] ; int64_t pA_end = Ap [kA+1] ; int64_t ajnz = pA_end - pA ; //-------------------------------------------------------------------------- // trim it to A(imin:imax,kA) //-------------------------------------------------------------------------- if (ajnz == avlen) { //---------------------------------------------------------------------- // A (:,kA) is dense; use pA and pA_end as-is //---------------------------------------------------------------------- ; } else if (ajnz == 0 || GB_Ai (pA) > imax || GB_Ai (pA_end-1) < imin) { //---------------------------------------------------------------------- // intersection of A(:,kA) and imin:imax is empty //---------------------------------------------------------------------- pA = -1 ; pA_end = -1 ; } else { //---------------------------------------------------------------------- // A (:,kA) is sparse, with at least one entry //---------------------------------------------------------------------- // trim the leading part of A(:,kA) if (GB_Ai (pA) < imin) { bool found, is_zombie ; int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH_ZOMBIE (imin, Ai, pA, pright, found, nzombies, is_zombie) ; } // trim the trailing part of A (:,kA) if (imin == imax) { if (GB_Ai (pA) == imin) { // found the the single entry A (i,kA) pA_end = pA + 1 ; } else { // A (i,kA) has not been found pA = -1 ; pA_end = -1 ; } } else if (imax < GB_Ai (pA_end-1)) { bool found, is_zombie ; int64_t pleft = pA ; int64_t pright = pA_end - 1 ; GB_SPLIT_BINARY_SEARCH_ZOMBIE (imax, Ai, pleft, pright, found, nzombies, is_zombie) ; pA_end = (found) ? (pleft + 1) : pleft ; } #ifdef GB_DEBUG ajnz = pA_end - pA ; if (ajnz > 0) { // A(imin:imax,kA) is now in Ai [pA:pA_end-1] ASSERT (GB_IMPLIES (Ap [kA] < pA, GB_Ai (pA-1) < imin)) ; ASSERT (GB_IMPLIES (pA_end < Ap [kA+1], imax < GB_Ai (pA_end))) ; ASSERT (imin <= GB_Ai (pA)) ; ASSERT (GB_Ai (pA_end-1) <= imax) ; } #endif } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- // The result [pA:pA_end-1] defines the range of entries that need to be // accessed for constructing C(:,kC). Ap_start [kC] = pA ; Ap_end [kC] = pA_end ; } //------------------------------------------------------------------------------ // GB_subref_phase0 //------------------------------------------------------------------------------ #define GB_FREE_WORK \ GB_FREE_MEMORY (Count, max_ntasks+1, sizeof (int64_t)) ; GrB_Info GB_subref_phase0 ( // output int64_t *GB_RESTRICT *p_Ch, // Ch = C->h hyperlist, or NULL standard int64_t *GB_RESTRICT *p_Ap_start, // A(:,kA) starts at Ap_start [kC] int64_t *GB_RESTRICT *p_Ap_end, // ... and ends at Ap_end [kC] - 1 int64_t *p_Cnvec, // # of vectors in C bool *p_need_qsort, // true if C must be sorted int *p_Ikind, // kind of I int64_t *p_nI, // length of I int64_t Icolon [3], // for GB_RANGE, GB_STRIDE int64_t *p_nJ, // length of J // input, not modified const GrB_Matrix A, const GrB_Index *I, // index list for C = A(I,J), or GrB_ALL, etc. const int64_t ni, // length of I, or special const GrB_Index *J, // index list for C = A(I,J), or GrB_ALL, etc. const int64_t nj, // length of J, or special const bool must_sort, // true if C must be returned sorted GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (p_Ch != NULL) ; ASSERT (p_Ap_start != NULL) ; ASSERT (p_Ap_end != NULL) ; ASSERT (p_Cnvec != NULL) ; ASSERT (p_nJ != NULL) ; ASSERT (p_Ikind != NULL) ; ASSERT (p_nI != NULL) ; ASSERT (Icolon != NULL) ; ASSERT_MATRIX_OK (A, "A for subref phase 0", GB0) ; ASSERT (I != NULL) ; ASSERT (J != NULL) ; GrB_Info info ; (*p_Ch ) = NULL ; (*p_Ap_start ) = NULL ; (*p_Ap_end ) = NULL ; (*p_Cnvec ) = 0 ; (*p_need_qsort) = false ; (*p_Ikind ) = 0 ; (*p_nI ) = 0 ; (*p_nJ ) = 0 ; //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- int64_t *GB_RESTRICT Ap = A->p ; // Ap (but not A->p) may be trimmed int64_t *GB_RESTRICT Ah = A->h ; // Ah (but not A->h) may be trimmed int64_t *GB_RESTRICT Ai = A->i ; int64_t anvec = A->nvec ; // may be trimmed int64_t avlen = A->vlen ; int64_t avdim = A->vdim ; int64_t nzombies = A->nzombies ; //-------------------------------------------------------------------------- // check the properties of I and J //-------------------------------------------------------------------------- // C = A(I,J) so I is in range 0:avlen-1 and J is in range 0:avdim-1 int64_t nI, nJ, Jcolon [3] ; int Ikind, Jkind ; GB_ijlength (I, ni, avlen, &nI, &Ikind, Icolon) ; GB_ijlength (J, nj, avdim, &nJ, &Jkind, Jcolon) ; bool I_unsorted, I_has_dupl, I_contig, J_unsorted, J_has_dupl, J_contig ; int64_t imin, imax, jmin, jmax ; info = GB_ijproperties (I, ni, nI, avlen, &Ikind, Icolon, &I_unsorted, &I_has_dupl, &I_contig, &imin, &imax, Context) ; if (info != GrB_SUCCESS) { // I invalid return (info) ; } info = GB_ijproperties (J, nj, nJ, avdim, &Jkind, Jcolon, &J_unsorted, &J_has_dupl, &J_contig, &jmin, &jmax, Context) ; if (info != GrB_SUCCESS) { // J invalid return (info) ; } bool need_qsort = I_unsorted ; // For the symbolic case, GB_subref must always return C sorted. For the // numeric case, GB_subref may return C with jumbled indices in each // vector, if C will be transposed later by GB_accum_mask. if (must_sort == false) { // The caller does not need C to be returned with sorted vectors. need_qsort = false ; } //-------------------------------------------------------------------------- // determine if C is empty //-------------------------------------------------------------------------- bool C_empty = (nI == 0 || nJ == 0) ; //-------------------------------------------------------------------------- // trim the hyperlist of A //-------------------------------------------------------------------------- // Ah, Ap, and anvec are modified to include just the vectors in range // jmin:jmax, inclusive. A itself is not modified, just the Ah and Ap // pointers, and the scalar anvec. If J is ":", then jmin is zero and // jmax is avdim-1, so there is nothing to trim from Ah. If C is empty, // then Ah and Ap will not be accessed at all, so this can be skipped. bool A_is_hyper = A->is_hyper ; if (A_is_hyper && !C_empty) { //---------------------------------------------------------------------- // trim the leading end of Ah so that it starts with jmin:... //---------------------------------------------------------------------- if (jmin > 0) { bool found ; int64_t kleft = 0 ; int64_t kright = anvec-1 ; GB_SPLIT_BINARY_SEARCH (jmin, Ah, kleft, kright, found) ; Ah += kleft ; Ap += kleft ; anvec -= kleft ; } //---------------------------------------------------------------------- // trim the trailing end of Ah so that it ends with ..:jmax //---------------------------------------------------------------------- if (jmax < avdim-1) { bool found ; int64_t kleft = 0 ; int64_t kright = anvec-1 ; GB_SPLIT_BINARY_SEARCH (jmax, Ah, kleft, kright, found) ; anvec = (found) ? (kleft + 1) : kleft ; } // Ah has been trimmed ASSERT (GB_IMPLIES (anvec > 0, jmin <= Ah [0] && Ah [anvec-1] <= jmax)); } // Ah may now be empty, after being trimmed C_empty = C_empty || (anvec == 0) ; //-------------------------------------------------------------------------- // determine # of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = 1, ntasks = 1 ; int max_ntasks = nthreads_max * 8 ; int64_t *GB_RESTRICT Count = NULL ; // size max_ntasks+1 #define GB_GET_NTHREADS_AND_NTASKS(work) \ { \ nthreads = GB_nthreads (work, chunk, nthreads_max) ; \ ntasks = (nthreads == 1) ? 1 : (8 * nthreads) ; \ ntasks = GB_IMIN (ntasks, work) ; \ ntasks = GB_IMAX (ntasks, 1) ; \ } //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- GB_CALLOC_MEMORY (Count, max_ntasks+1, sizeof (int64_t)) ; if (Count == NULL) { // out of memory return (GB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // compute Cnvec and determine the format of Ch //-------------------------------------------------------------------------- // Ch is an explicit or implicit array of size Cnvec <= nJ. jC = Ch [kC] // if C(:,jC) is the (kC)th vector of C. If NULL, then C is standard, and // jC == kC. jC is in the range 0 to nJ-1. int64_t *GB_RESTRICT Ch = NULL ; int64_t *GB_RESTRICT Ap_start = NULL ; int64_t *GB_RESTRICT Ap_end = NULL ; int64_t Cnvec = 0 ; int64_t jbegin = Jcolon [GxB_BEGIN] ; int64_t jinc = Jcolon [GxB_INC ] ; if (C_empty) { //---------------------------------------------------------------------- // C is an empty hypersparse matrix //---------------------------------------------------------------------- ; } else if (!A_is_hyper) { //---------------------------------------------------------------------- // both C and A are standard matrices //---------------------------------------------------------------------- Cnvec = nJ ; GB_GET_NTHREADS_AND_NTASKS (nJ) ; } else if (Jkind == GB_ALL || Jkind == GB_RANGE) { //---------------------------------------------------------------------- // J is ":" or jbegin:jend //---------------------------------------------------------------------- // Ch is a shifted copy of the trimmed Ah, of length Cnvec = anvec. // so kA = kC, and jC = Ch [kC] = jA - jmin. Ap has also been trimmed. Cnvec = anvec ; ASSERT (Cnvec <= nJ) ; GB_GET_NTHREADS_AND_NTASKS (anvec) ; } else if (Jkind == GB_STRIDE && anvec < nJ * 64) { //---------------------------------------------------------------------- // J is jbegin:jinc:jend, but J is large //---------------------------------------------------------------------- // The case for Jkind == GB_STRIDE can be done by either this method, // or the one below. This takes O(anvec) time, and the one below // takes O(nj*log2(anvec)), so use this method if anvec < nj * 64. // Ch is a list of length Cnvec, where Cnvec is the length of // the intersection of Ah and jbegin:jinc:jend. // count the length of Ch Cnvec = 0 ; GB_GET_NTHREADS_AND_NTASKS (anvec) ; // scan all of Ah and check each entry if it appears in J int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t kA_start, kA_end, my_Cnvec = 0 ; GB_PARTITION (kA_start, kA_end, anvec, (jinc > 0) ? tid : (ntasks-tid-1), ntasks) ; for (int64_t kA = kA_start ; kA < kA_end ; kA++) { int64_t jA = Ah [kA] ; if (GB_ij_is_in_list (J, nJ, jA, GB_STRIDE, Jcolon)) { my_Cnvec++ ; } } Count [tid] = my_Cnvec ; } GB_cumsum (Count, ntasks, NULL, 1) ; Cnvec = Count [ntasks] ; } else // Jkind == GB_LIST or GB_STRIDE { //---------------------------------------------------------------------- // J is an explicit list, or jbegin:jinc:end //---------------------------------------------------------------------- // Ch is an explicit list: the intersection of Ah and J // count the length of Ch Cnvec = 0 ; GB_GET_NTHREADS_AND_NTASKS (nJ) ; // scan all of J and check each entry if it appears in Ah int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t jC_start, jC_end, my_Cnvec = 0 ; GB_PARTITION (jC_start, jC_end, nJ, tid, ntasks) ; for (int64_t jC = jC_start ; jC < jC_end ; jC++) { int64_t jA = GB_ijlist (J, jC, Jkind, Jcolon) ; bool found ; int64_t kA = 0 ; int64_t kright = anvec-1 ; GB_BINARY_SEARCH (jA, Ah, kA, kright, found) ; if (found) my_Cnvec++ ; } Count [tid] = my_Cnvec ; } GB_cumsum (Count, ntasks, NULL, 1) ; Cnvec = Count [ntasks] ; } //-------------------------------------------------------------------------- // allocate Ch, Ap_start, and Ap_end //-------------------------------------------------------------------------- C_empty = C_empty || (Cnvec == 0) ; // C is hypersparse if A is hypersparse, or if C is empty bool C_is_hyper = A_is_hyper || C_empty ; if (C_is_hyper) { GB_MALLOC_MEMORY (Ch, Cnvec, sizeof (int64_t)) ; if (Ch == NULL) { GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } if (Cnvec > 0) { GB_MALLOC_MEMORY (Ap_start, Cnvec, sizeof (int64_t)) ; GB_MALLOC_MEMORY (Ap_end, Cnvec, sizeof (int64_t)) ; if (Ap_start == NULL || Ap_end == NULL) { // out of memory GB_FREE_WORK ; GB_FREE_MEMORY (Ch, Cnvec, sizeof (int64_t)) ; GB_FREE_MEMORY (Ap_start, Cnvec, sizeof (int64_t)) ; GB_FREE_MEMORY (Ap_end, Cnvec, sizeof (int64_t)) ; return (GB_OUT_OF_MEMORY) ; } } //-------------------------------------------------------------------------- // create Ch, Ap_start, and Ap_end //-------------------------------------------------------------------------- // For the (kC)th vector of C, which corresponds to the (kA)th vector of A, // pA = Ap_start [kC] and pA_end = Ap_end [kC] are pointers to the range // of entries in A(imin:imax,kA). if (C_empty) { //---------------------------------------------------------------------- // C is an empty hypersparse matrix //---------------------------------------------------------------------- ; } else if (!A_is_hyper) { //---------------------------------------------------------------------- // both C and A are standard matrices //---------------------------------------------------------------------- int64_t jC ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (jC = 0 ; jC < nJ ; jC++) { int64_t jA = GB_ijlist (J, jC, Jkind, Jcolon) ; GB_find_Ap_start_end (jA, Ap, Ai, avlen, imin, imax, jC, nzombies, Ap_start, Ap_end) ; } } else if (Jkind == GB_ALL || Jkind == GB_RANGE) { //---------------------------------------------------------------------- // J is ":" or jbegin:jend //---------------------------------------------------------------------- // C and A are both hypersparse. Ch is a shifted copy of the trimmed // Ah, of length Cnvec = anvec. so kA = kC. Ap has also been trimmed. int64_t kC ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (kC = 0 ; kC < Cnvec ; kC++) { int64_t kA = kC ; int64_t jA = Ah [kA] ; int64_t jC = jA - jmin ; Ch [kC] = jC ; GB_find_Ap_start_end (kA, Ap, Ai, avlen, imin, imax, kC, nzombies, Ap_start, Ap_end) ; } } else if (Jkind == GB_STRIDE && anvec < nJ * 64) { //---------------------------------------------------------------------- // J is jbegin:jinc:jend where jinc may be positive or negative //---------------------------------------------------------------------- // C and A are both hypersparse. Ch is constructed by scanning all // vectors in Ah [0..anvec-1] and checking if they appear in the // jbegin:jinc:jend sequence. if (jinc > 0) { int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t kA_start, kA_end ; GB_PARTITION (kA_start, kA_end, anvec, tid, ntasks) ; int64_t kC = Count [tid] ; for (int64_t kA = kA_start ; kA < kA_end ; kA++) { int64_t jA = Ah [kA] ; if (GB_ij_is_in_list (J, nJ, jA, GB_STRIDE, Jcolon)) { int64_t jC = (jA - jbegin) / jinc ; Ch [kC] = jC ; GB_find_Ap_start_end (kA, Ap, Ai, avlen, imin, imax, kC, nzombies, Ap_start, Ap_end) ; kC++ ; } } } } else { int tid; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t kA_start, kA_end ; GB_PARTITION (kA_start, kA_end, anvec, ntasks-tid-1, ntasks) ; int64_t kC = Count [tid] ; for (int64_t kA = kA_end-1 ; kA >= kA_start ; kA--) { int64_t jA = Ah [kA] ; if (GB_ij_is_in_list (J, nJ, jA, GB_STRIDE, Jcolon)) { int64_t jC = (jA - jbegin) / jinc ; Ch [kC] = jC ; GB_find_Ap_start_end (kA, Ap, Ai, avlen, imin, imax, kC, nzombies, Ap_start, Ap_end) ; kC++ ; } } } } } else // Jkind == GB_LIST or GB_STRIDE { //---------------------------------------------------------------------- // J is an explicit list, or jbegin:jinc:jend //---------------------------------------------------------------------- // C and A are both hypersparse. Ch is constructed by scanning the // list J, or the entire jbegin:jinc:jend sequence. Each vector is // then found in Ah, via binary search. int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t jC_start, jC_end ; GB_PARTITION (jC_start, jC_end, nJ, tid, ntasks) ; int64_t kC = Count [tid] ; for (int64_t jC = jC_start ; jC < jC_end ; jC++) { int64_t jA = GB_ijlist (J, jC, Jkind, Jcolon) ; bool found ; int64_t kA = 0 ; int64_t kright = anvec-1 ; GB_BINARY_SEARCH (jA, Ah, kA, kright, found) ; if (found) { ASSERT (jA == Ah [kA]) ; Ch [kC] = jC ; GB_find_Ap_start_end (kA, Ap, Ai, avlen, imin, imax, kC, nzombies, Ap_start, Ap_end) ; kC++ ; } } } } //-------------------------------------------------------------------------- // check result //-------------------------------------------------------------------------- #ifdef GB_DEBUG for (int64_t kC = 0 ; kC < Cnvec ; kC++) { // jC is the (kC)th vector of C = A(I,J) int64_t jC = (Ch == NULL) ? kC : Ch [kC] ; int64_t jA = GB_ijlist (J, jC, Jkind, Jcolon) ; // jA is the corresponding (kA)th vector of A. int64_t kA = 0 ; int64_t pright = A->nvec - 1 ; int64_t pA_start_all, pA_end_all ; bool found = GB_lookup (A->is_hyper, A->h, A->p, &kA, pright, jA, &pA_start_all, &pA_end_all) ; if (found && A->is_hyper) { ASSERT (jA == A->h [kA]) ; } int64_t pA = Ap_start [kC] ; int64_t pA_end = Ap_end [kC] ; int64_t ajnz = pA_end - pA ; if (ajnz == avlen) { // A(:,kA) is dense; Ai [pA:pA_end-1] is the entire vector. // C(:,kC) will have exactly nI entries. ASSERT (pA == pA_start_all) ; ASSERT (pA_end == pA_end_all ) ; ; } else if (ajnz > 0) { // A(imin:imax,kA) has at least one entry, in Ai [pA:pA_end-1] ASSERT (imin <= GB_Ai (pA)) ; ASSERT (GB_Ai (pA_end-1) <= imax) ; ASSERT (pA_start_all <= pA && pA < pA_end && pA_end <= pA_end_all) ; } else { // A(imin:imax,kA) and C(:,kC) are empty ; } } #endif //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK ; (*p_Ch ) = Ch ; (*p_Ap_start ) = Ap_start ; (*p_Ap_end ) = Ap_end ; (*p_Cnvec ) = Cnvec ; (*p_need_qsort) = need_qsort ; (*p_Ikind ) = Ikind ; (*p_nI ) = nI ; (*p_nJ ) = nJ ; return (GrB_SUCCESS) ; }
GB_binop__band_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint64) // A*D function (colscale): GB (_AxD__band_uint64) // D*A function (rowscale): GB (_DxB__band_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__band_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__band_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint64) // C=scalar+B GB (_bind1st__band_uint64) // C=scalar+B' GB (_bind1st_tran__band_uint64) // C=A+scalar GB (_bind2nd__band_uint64) // C=A'+scalar GB (_bind2nd_tran__band_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x) & (y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BAND || GxB_NO_UINT64 || GxB_NO_BAND_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__band_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__band_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__band_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__band_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__band_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__band_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__band_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__band_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij) & (y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mandelbrot.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <complex.h> #include "types.h" static double in_mandelbrot_set(double complex c, long iterations, long escape_radius) { long i; double complex z = 0; for (i = 0; i < iterations; i++) { double r = cabs(z); if (r > escape_radius) { return (double) i + 1 - log10(log10(r)) / log10(2); } z = z*z+c; } return 0; } static struct rgb color(double i) { struct rgb r; i = fmod(i, 100.0); if (i < 30) { double norm = i / 30.0; norm *= norm; r.r = norm * 0x00; r.g = norm * 0x00; r.b = norm * 0x55; } else if (i < 70) { i -= 30.0; double norm = i / 40.0; r.r = norm * 0xaa; r.g = norm * 0xaa; r.b = norm * 0xaa + 0x55; } else { i -= 70.0; double norm = i / 30.0; r.r = (1.0-norm) * 0xaa; r.g = (1.0-norm) * 0xaa; r.b = (1.0-norm) * 0xff; } return r; } void generate(FILE *output_file, int image_width, int image_height, double xmin, double xmax, double ymin, double ymax, long escape_radius, long iterations) { struct rgb *line = malloc(image_width * sizeof(struct rgb)); for (int y = 0; y < image_height; y++) { #pragma omp parallel for for (int x = 0; x < image_width; x++) { /* map pixels to complex numbers according to given ranges then test if they're in the set */ double real = (double)x/(double)image_width * (xmax-xmin) + xmin; double imag = (1-(double)y/(double)image_height) * (ymax-ymin) + ymin; double i = in_mandelbrot_set(real + I*imag, iterations, escape_radius); line[x] = color(i); } fwrite(line, 3, image_width, output_file); } free(line); }
brilliantrussian.c
/******************************************************************* * * M4RI: Linear Algebra over GF(2) * * Copyright (C) 2007, 2008 Gregory Bard <[email protected]> * Copyright (C) 2008-2010 Martin Albrecht <[email protected]> * * Distributed under the terms of the GNU General Public License (GPL) * version 2 or higher. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * The full text of the GPL is available at: * * http://www.gnu.org/licenses/ * ********************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "brilliantrussian.h" #include "xor.h" #include "graycode.h" #include "echelonform.h" #include "ple_russian.h" /** * \brief Perform Gaussian reduction to reduced row echelon form on a * submatrix. * * The submatrix has dimension at most k starting at r x c of A. Checks * for pivot rows up to row endrow (exclusive). Terminates as soon as * finding a pivot column fails. * * \param A Matrix. * \param r First row. * \param c First column. * \param k Maximal dimension of identity matrix to produce. * \param end_row Maximal row index (exclusive) for rows to consider * for inclusion. */ static inline int _mzd_gauss_submatrix_full(mzd_t *A, rci_t r, rci_t c, rci_t end_row, int k) { assert(k <= m4ri_radix); rci_t start_row = r; rci_t j; for (j = c; j < c + k; ++j) { int found = 0; for (rci_t i = start_row; i < end_row; ++i) { /* first we need to clear the first columns */ word const tmp = mzd_read_bits(A, i, c, j - c + 1); if(tmp) { for (int l = 0; l < j - c; ++l) if (__M4RI_GET_BIT(tmp, l)) mzd_row_add_offset(A, i, r+l, c+l); /* pivot? */ if (mzd_read_bit(A, i, j)) { mzd_row_swap(A, i, start_row); /* clear above */ for (rci_t l = r; l < start_row; ++l) { if (mzd_read_bit(A, l, j)) { mzd_row_add_offset(A, l, start_row, j); } } ++start_row; found = 1; break; } } } if (found == 0) { break; } } __M4RI_DD_MZD(A); __M4RI_DD_INT(j - c); return j - c; } /** * \brief Perform Gaussian reduction to upper triangular matrix on a * submatrix. * * The submatrix has dimension at most k starting at r x c of A. Checks * for pivot rows up to row end_row (exclusive). Terminates as soon as * finding a pivot column fails. * * \param A Matrix. * \param r First row. * \param c First column. * \param k Maximal dimension of identity matrix to produce. * \param end_row Maximal row index (exclusive) for rows to consider * for inclusion. */ static inline int _mzd_gauss_submatrix(mzd_t *A, rci_t r, rci_t c, rci_t end_row, int k) { rci_t start_row = r; int found; rci_t j; for (j = c; j < c+k; ++j) { found = 0; for (rci_t i = start_row; i < end_row; ++i) { /* first we need to clear the first columns */ for (int l = 0; l < j - c; ++l) if (mzd_read_bit(A, i, c+l)) mzd_row_add_offset(A, i, r+l, c+l); /* pivot? */ if (mzd_read_bit(A, i, j)) { mzd_row_swap(A, i, start_row); start_row++; found = 1; break; } } if (found == 0) { break; } } __M4RI_DD_MZD(A); __M4RI_DD_INT(j - c); return j - c; } /** * \brief Given a submatrix in upper triangular form compute the * reduced row echelon form. * * The submatrix has dimension at most k starting at r x c of A. Checks * for pivot rows up to row end_row (exclusive). Terminates as soon as * finding a pivot column fails. * * \param A Matrix. * \param r First row. * \param c First column. * \param k Maximal dimension of identity matrix to produce. * \param end_row Maximal row index (exclusive) for rows to consider * for inclusion. */ static inline int _mzd_gauss_submatrix_top(mzd_t *A, rci_t r, rci_t c, int k) { rci_t start_row = r; for (rci_t j = c; j < c + k; ++j) { for (rci_t l = r; l < start_row; ++l) { if (mzd_read_bit(A, l, j)) { mzd_row_add_offset(A, l, start_row, j); } } ++start_row; } __M4RI_DD_MZD(A); __M4RI_DD_INT(k); return k; } static inline void _mzd_copy_back_rows(mzd_t *A, mzd_t const *U, rci_t r, rci_t c, int k) { wi_t const startblock = c / m4ri_radix; wi_t const width = A->width - startblock; for (int i = 0; i < k; ++i) { word const *const src = U->rows[i] + startblock; word *const dst = A->rows[r+i] + startblock; for (wi_t j = 0; j < width; ++j) { dst[j] = src[j]; } } __M4RI_DD_MZD(A); } void mzd_make_table(mzd_t const *M, rci_t r, rci_t c, int k, mzd_t *T, rci_t *L) { wi_t const homeblock = c / m4ri_radix; word const mask_end = __M4RI_LEFT_BITMASK(M->ncols % m4ri_radix); word const pure_mask_begin = __M4RI_RIGHT_BITMASK(m4ri_radix - (c % m4ri_radix)); word const mask_begin = (M->width - homeblock != 1) ? pure_mask_begin : pure_mask_begin & mask_end; wi_t const wide = M->width - homeblock; int const twokay = __M4RI_TWOPOW(k); L[0] = 0; for (rci_t i = 1; i < twokay; ++i) { word *ti = T->rows[i] + homeblock; word *ti1 = T->rows[i-1] + homeblock; rci_t const rowneeded = r + m4ri_codebook[k]->inc[i - 1]; int const id = m4ri_codebook[k]->ord[i]; L[id] = i; if (rowneeded >= M->nrows) continue; word *m = M->rows[rowneeded] + homeblock; *ti++ = (*m++ ^ *ti1++) & mask_begin; wi_t j; for(j = 1; j + 8 <= wide - 1; j += 8) { *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; *ti++ = *m++ ^ *ti1++; } switch(wide - j) { case 8: *ti++ = *m++ ^ *ti1++; case 7: *ti++ = *m++ ^ *ti1++; case 6: *ti++ = *m++ ^ *ti1++; case 5: *ti++ = *m++ ^ *ti1++; case 4: *ti++ = *m++ ^ *ti1++; case 3: *ti++ = *m++ ^ *ti1++; case 2: *ti++ = *m++ ^ *ti1++; case 1: *ti++ = (*m++ ^ *ti1++) & mask_end; } } __M4RI_DD_MZD(T); __M4RI_DD_RCI_ARRAY(L, twokay); } void mzd_process_rows(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T, rci_t const *L) { wi_t const block = startcol / m4ri_radix; wi_t const wide = M->width - block; wi_t const count = (wide + 7) / 8; /* Unrolled loop count */ int const entry_point = wide % 8; /* Unrolled loop entry point */ if(k == 1) { word const bm = m4ri_one << (startcol % m4ri_radix); rci_t r; for (r = startrow; r + 2 <= stoprow; r += 2) { word const b0 = M->rows[r+0][block] & bm; word const b1 = M->rows[r+1][block] & bm; word *m0 = M->rows[r+0] + block; word *m1 = M->rows[r+1] + block; word *t = T->rows[1] + block; wi_t n = count; if((b0 & b1)) { switch (entry_point) { case 0: do { *m0++ ^= *t; *m1++ ^= *t++; case 7: *m0++ ^= *t; *m1++ ^= *t++; case 6: *m0++ ^= *t; *m1++ ^= *t++; case 5: *m0++ ^= *t; *m1++ ^= *t++; case 4: *m0++ ^= *t; *m1++ ^= *t++; case 3: *m0++ ^= *t; *m1++ ^= *t++; case 2: *m0++ ^= *t; *m1++ ^= *t++; case 1: *m0++ ^= *t; *m1++ ^= *t++; } while (--n > 0); } } else if(b0) { switch (entry_point) { case 0: do { *m0++ ^= *t++; case 7: *m0++ ^= *t++; case 6: *m0++ ^= *t++; case 5: *m0++ ^= *t++; case 4: *m0++ ^= *t++; case 3: *m0++ ^= *t++; case 2: *m0++ ^= *t++; case 1: *m0++ ^= *t++; } while (--n > 0); } } else if(b1) { switch (entry_point) { case 0: do { *m1++ ^= *t++; case 7: *m1++ ^= *t++; case 6: *m1++ ^= *t++; case 5: *m1++ ^= *t++; case 4: *m1++ ^= *t++; case 3: *m1++ ^= *t++; case 2: *m1++ ^= *t++; case 1: *m1++ ^= *t++; } while (--n > 0); } } } /* TODO: this code is a bit silly/overkill, it just takes care of the last row */ for( ; r < stoprow; ++r) { rci_t const x0 = L[ mzd_read_bits_int(M, r, startcol, k) ]; word *m0 = M->rows[r] + block; word *t0 = T->rows[x0] + block; wi_t n = count; switch (entry_point) { case 0: do { *m0++ ^= *t0++; case 7: *m0++ ^= *t0++; case 6: *m0++ ^= *t0++; case 5: *m0++ ^= *t0++; case 4: *m0++ ^= *t0++; case 3: *m0++ ^= *t0++; case 2: *m0++ ^= *t0++; case 1: *m0++ ^= *t0++; } while (--n > 0); } } __M4RI_DD_MZD(M); return; } rci_t r; for (r = startrow; r + 2 <= stoprow; r += 2) { rci_t const x0 = L[ mzd_read_bits_int(M, r+0, startcol, k) ]; rci_t const x1 = L[ mzd_read_bits_int(M, r+1, startcol, k) ]; word *m0 = M->rows[r+0] + block; word *t0 = T->rows[x0] + block; word *m1 = M->rows[r+1] + block; word *t1 = T->rows[x1] + block; wi_t n = count; switch (entry_point) { case 0: do { *m0++ ^= *t0++; *m1++ ^= *t1++; case 7: *m0++ ^= *t0++; *m1++ ^= *t1++; case 6: *m0++ ^= *t0++; *m1++ ^= *t1++; case 5: *m0++ ^= *t0++; *m1++ ^= *t1++; case 4: *m0++ ^= *t0++; *m1++ ^= *t1++; case 3: *m0++ ^= *t0++; *m1++ ^= *t1++; case 2: *m0++ ^= *t0++; *m1++ ^= *t1++; case 1: *m0++ ^= *t0++; *m1++ ^= *t1++; } while (--n > 0); } } for( ; r < stoprow; ++r) { rci_t const x0 = L[ mzd_read_bits_int(M, r, startcol, k) ]; word *m0 = M->rows[r] + block; word *t0 = T->rows[x0] + block; wi_t n = count; switch (entry_point) { case 0: do { *m0++ ^= *t0++; case 7: *m0++ ^= *t0++; case 6: *m0++ ^= *t0++; case 5: *m0++ ^= *t0++; case 4: *m0++ ^= *t0++; case 3: *m0++ ^= *t0++; case 2: *m0++ ^= *t0++; case 1: *m0++ ^= *t0++; } while (--n > 0); } } __M4RI_DD_MZD(M); } void mzd_process_rows2(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T0, rci_t const *L0, mzd_t const *T1, rci_t const *L1) { assert(k <= m4ri_radix); wi_t const blocknum = startcol / m4ri_radix; wi_t const wide = M->width - blocknum; int const ka = k / 2; int const kb = k - k / 2; rci_t r; word const ka_bm = __M4RI_LEFT_BITMASK(ka); word const kb_bm = __M4RI_LEFT_BITMASK(kb); #if __M4RI_HAVE_OPENMP #pragma omp parallel for private(r) shared(startrow, stoprow) schedule(static,512) // MAX((__M4RI_CPU_L1_CACHE >> 3) / wide, #endif for(r = startrow; r < stoprow; ++r) { word bits = mzd_read_bits(M, r, startcol, k); rci_t const x0 = L0[ bits & ka_bm ]; bits>>=ka; rci_t const x1 = L1[ bits & kb_bm ]; if((x0 | x1) == 0) // x0 == 0 && x1 == 0 continue; word *m0 = M->rows[r] + blocknum; word const *t[2]; t[0] = T0->rows[x0] + blocknum; t[1] = T1->rows[x1] + blocknum; _mzd_combine_2( m0, t, wide); } __M4RI_DD_MZD(M); } void mzd_process_rows3(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T0, rci_t const *L0, mzd_t const *T1, rci_t const *L1, mzd_t const *T2, rci_t const *L2) { assert(k <= m4ri_radix); wi_t const blocknum = startcol / m4ri_radix; wi_t const wide = M->width - blocknum; int rem = k % 3; int const ka = k / 3 + ((rem >= 2) ? 1 : 0); int const kb = k / 3 + ((rem >= 1) ? 1 : 0); int const kc = k / 3; rci_t r; word const ka_bm = __M4RI_LEFT_BITMASK(ka); word const kb_bm = __M4RI_LEFT_BITMASK(kb); word const kc_bm = __M4RI_LEFT_BITMASK(kc); #if __M4RI_HAVE_OPENMP #pragma omp parallel for private(r) shared(startrow, stoprow) schedule(static,512) //if(stoprow-startrow > 128) #endif for(r= startrow; r < stoprow; ++r) { word bits = mzd_read_bits(M, r, startcol, k); rci_t const x0 = L0[ bits & ka_bm ]; bits>>=ka; rci_t const x1 = L1[ bits & kb_bm ]; bits>>=kb; rci_t const x2 = L2[ bits & kc_bm ]; if((x0 | x1 | x2) == 0) // x0 == 0 && x1 == 0 && x2 == 0 continue; word *m0 = M->rows[r] + blocknum; word const *t[3]; t[0] = T0->rows[x0] + blocknum; t[1] = T1->rows[x1] + blocknum; t[2] = T2->rows[x2] + blocknum; _mzd_combine_3( m0, t, wide); } __M4RI_DD_MZD(M); } void mzd_process_rows4(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T0, rci_t const *L0, mzd_t const *T1, rci_t const *L1, mzd_t const *T2, rci_t const *L2, mzd_t const *T3, rci_t const *L3) { assert(k <= m4ri_radix); wi_t const blocknum = startcol / m4ri_radix; wi_t const wide = M->width - blocknum; int const rem = k % 4; int const ka = k / 4 + ((rem >= 3) ? 1 : 0); int const kb = k / 4 + ((rem >= 2) ? 1 : 0); int const kc = k / 4 + ((rem >= 1) ? 1 : 0); int const kd = k / 4; rci_t r; word const ka_bm = __M4RI_LEFT_BITMASK(ka); word const kb_bm = __M4RI_LEFT_BITMASK(kb); word const kc_bm = __M4RI_LEFT_BITMASK(kc); word const kd_bm = __M4RI_LEFT_BITMASK(kd); #if __M4RI_HAVE_OPENMP #pragma omp parallel for private(r) shared(startrow, stoprow) schedule(static,512) //if(stoprow-startrow > 128) #endif for(r = startrow; r < stoprow; ++r) { word bits = mzd_read_bits(M, r, startcol, k); rci_t const x0 = L0[ bits & ka_bm ]; bits>>=ka; rci_t const x1 = L1[ bits & kb_bm ]; bits>>=kb; rci_t const x2 = L2[ bits & kc_bm ]; bits>>=kc; rci_t const x3 = L3[ bits & kd_bm ]; if(((x0 | x1) | (x2 | x3)) == 0) // x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 continue; word *m0 = M->rows[r] + blocknum; word const *t[4]; t[0] = T0->rows[x0] + blocknum; t[1] = T1->rows[x1] + blocknum; t[2] = T2->rows[x2] + blocknum; t[3] = T3->rows[x3] + blocknum; _mzd_combine_4( m0, t, wide); } __M4RI_DD_MZD(M); } void mzd_process_rows5(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T0, rci_t const *L0, mzd_t const *T1, rci_t const *L1, mzd_t const *T2, rci_t const *L2, mzd_t const *T3, rci_t const *L3, mzd_t const *T4, rci_t const *L4) { assert(k <= m4ri_radix); wi_t const blocknum = startcol / m4ri_radix; wi_t const wide = M->width - blocknum; int rem = k % 5; int const ka = k / 5 + ((rem >= 4) ? 1 : 0); int const kb = k / 5 + ((rem >= 3) ? 1 : 0); int const kc = k / 5 + ((rem >= 2) ? 1 : 0); int const kd = k / 5 + ((rem >= 1) ? 1 : 0); int const ke = k / 5; rci_t r; word const ka_bm = __M4RI_LEFT_BITMASK(ka); word const kb_bm = __M4RI_LEFT_BITMASK(kb); word const kc_bm = __M4RI_LEFT_BITMASK(kc); word const kd_bm = __M4RI_LEFT_BITMASK(kd); word const ke_bm = __M4RI_LEFT_BITMASK(ke); #if __M4RI_HAVE_OPENMP #pragma omp parallel for private(r) shared(startrow, stoprow) schedule(static,512) //if(stoprow-startrow > 128) #endif for(r = startrow; r < stoprow; ++r) { word bits = mzd_read_bits(M, r, startcol, k); rci_t const x0 = L0[ bits & ka_bm ]; bits>>=ka; rci_t const x1 = L1[ bits & kb_bm ]; bits>>=kb; rci_t const x2 = L2[ bits & kc_bm ]; bits>>=kc; rci_t const x3 = L3[ bits & kd_bm ]; bits>>=kd; rci_t const x4 = L4[ bits & ke_bm ]; if(((x0 | x1 | x2) | (x3 | x4)) == 0) // x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 && x4 == 0 continue; word *m0 = M->rows[r] + blocknum; word const *t[5]; t[0] = T0->rows[x0] + blocknum; t[1] = T1->rows[x1] + blocknum; t[2] = T2->rows[x2] + blocknum; t[3] = T3->rows[x3] + blocknum; t[4] = T4->rows[x4] + blocknum; _mzd_combine_5( m0, t, wide); } __M4RI_DD_MZD(M); } void mzd_process_rows6(mzd_t *M, rci_t startrow, rci_t stoprow, rci_t startcol, int k, mzd_t const *T0, rci_t const *L0, mzd_t const *T1, rci_t const *L1, mzd_t const *T2, rci_t const *L2, mzd_t const *T3, rci_t const *L3, mzd_t const *T4, rci_t const *L4, mzd_t const *T5, rci_t const *L5) { assert(k <= m4ri_radix); wi_t const blocknum = startcol / m4ri_radix; wi_t const wide = M->width - blocknum; int const rem = k % 6; int const ka = k / 6 + ((rem >= 5) ? 1 : 0); int const kb = k / 6 + ((rem >= 4) ? 1 : 0); int const kc = k / 6 + ((rem >= 3) ? 1 : 0); int const kd = k / 6 + ((rem >= 2) ? 1 : 0); int const ke = k / 6 + ((rem >= 1) ? 1 : 0);; int const kf = k / 6; rci_t r; word const ka_bm = __M4RI_LEFT_BITMASK(ka); word const kb_bm = __M4RI_LEFT_BITMASK(kb); word const kc_bm = __M4RI_LEFT_BITMASK(kc); word const kd_bm = __M4RI_LEFT_BITMASK(kd); word const ke_bm = __M4RI_LEFT_BITMASK(ke); word const kf_bm = __M4RI_LEFT_BITMASK(kf); #if __M4RI_HAVE_OPENMP #pragma omp parallel for private(r) shared(startrow, stoprow) schedule(static,512) //if(stoprow-startrow > 128) #endif for(r = startrow; r < stoprow; ++r) { word bits = mzd_read_bits(M, r, startcol, k); rci_t const x0 = L0[ bits & ka_bm ]; bits>>=ka; rci_t const x1 = L1[ bits & kb_bm ]; bits>>=kb; rci_t const x2 = L2[ bits & kc_bm ]; bits>>=kc; rci_t const x3 = L3[ bits & kd_bm ]; bits>>=kd; rci_t const x4 = L4[ bits & ke_bm ]; bits>>=ke; rci_t const x5 = L5[ bits & kf_bm ]; /* Waste three clocks on OR-ing (modern CPU can do three in * parallel) to avoid possible multiple conditional jumps. */ if(((x0 | x1) | (x2 | x3) | (x4 | x5)) == 0) // x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 && x4 == 0 && x5 == 0 continue; word *m0 = M->rows[r] + blocknum; word const *t[6]; t[0] = T0->rows[x0] + blocknum; t[1] = T1->rows[x1] + blocknum; t[2] = T2->rows[x2] + blocknum; t[3] = T3->rows[x3] + blocknum; t[4] = T4->rows[x4] + blocknum; t[5] = T5->rows[x5] + blocknum; _mzd_combine_6( m0, t, wide); } __M4RI_DD_MZD(M); } rci_t _mzd_echelonize_m4ri(mzd_t *A, int const full, int k, int heuristic, double const threshold) { /** * \par General algorithm * \li Step 1.Denote the first column to be processed in a given * iteration as \f$a_i\f$. Then, perform Gaussian elimination on the * first \f$3k\f$ rows after and including the \f$i\f$-th row to * produce an identity matrix in \f$a_{i,i} ... a_{i+k-1,i+k-1},\f$ * and zeroes in \f$a_{i+k,i} ... a_{i+3k-1,i+k-1}\f$. * * \li Step 2. Construct a table consisting of the \f$2^k\f$ binary strings of * length k in a Gray code. Thus with only \f$2^k\f$ vector * additions, all possible linear combinations of these k rows * have been precomputed. * * \li Step 3. One can rapidly process the remaining rows from \f$i + * 3k\f$ until row \f$m\f$ (the last row) by using the table. For * example, suppose the \f$j\f$-th row has entries \f$a_{j,i} * ... a_{j,i+k-1}\f$ in the columns being processed. Selecting the * row of the table associated with this k-bit string, and adding it * to row j will force the k columns to zero, and adjust the * remaining columns from \f$ i + k\f$ to n in the appropriate way, * as if Gaussian elimination had been performed. * * \li Step 4. While the above form of the algorithm will reduce a * system of boolean linear equations to unit upper triangular form, * and thus permit a system to be solved with back substitution, the * M4RI algorithm can also be used to invert a matrix, or put the * system into reduced row echelon form (RREF). Simply run Step 3 * on rows \f$0 ... i-1\f$ as well as on rows \f$i + 3k * ... m\f$. This only affects the complexity slightly, changing the * 2.5 coeffcient to 3. * * \attention This function implements a variant of the algorithm * described above. If heuristic is true, then this algorithm, will * switch to PLUQ based echelon form computation once the density * reaches the threshold. */ rci_t const ncols = A->ncols; if (k == 0) { k = m4ri_opt_k(A->nrows, ncols, 0); if (k >= 7) k = 7; if (0.75 * __M4RI_TWOPOW(k) * ncols > __M4RI_CPU_L3_CACHE / 2.0) k -= 1; } int kk = 6 * k; mzd_t *U = mzd_init(kk, ncols); mzd_t *T0 = mzd_init(__M4RI_TWOPOW(k), ncols); mzd_t *T1 = mzd_init(__M4RI_TWOPOW(k), ncols); mzd_t *T2 = mzd_init(__M4RI_TWOPOW(k), ncols); mzd_t *T3 = mzd_init(__M4RI_TWOPOW(k), ncols); mzd_t *T4 = mzd_init(__M4RI_TWOPOW(k), ncols); mzd_t *T5 = mzd_init(__M4RI_TWOPOW(k), ncols); rci_t *L0 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L1 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L2 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L3 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L4 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L5 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t last_check = 0; rci_t r = 0; rci_t c = 0; if (heuristic) { if (c < ncols && r < A->nrows && _mzd_density(A, 32, 0, 0) >= threshold) { wi_t const tmp = c / m4ri_radix; rci_t const tmp2 = tmp * m4ri_radix; mzd_t *Abar = mzd_init_window(A, r, tmp2, A->nrows, ncols); r += mzd_echelonize_pluq(Abar, full); mzd_free(Abar); c = ncols; } } while(c < ncols) { if (heuristic && c > (last_check + 256)) { last_check = c; if (c < ncols && r < A->nrows && _mzd_density(A, 32, r, c) >= threshold) { mzd_t *Abar = mzd_init_window(A, r, (c / m4ri_radix) * m4ri_radix, A->nrows, ncols); if (!full) { r += mzd_echelonize_pluq(Abar, full); } else { rci_t r2 = mzd_echelonize_pluq(Abar, full); if (r > 0) _mzd_top_echelonize_m4ri(A, 0, r, c, r); r += r2; } mzd_free(Abar); break; } } if(c + kk > ncols) { kk = ncols - c; } int kbar; if (full) { kbar = _mzd_gauss_submatrix_full(A, r, c, A->nrows, kk); } else { kbar = _mzd_gauss_submatrix(A, r, c, A->nrows, kk); /* this isn't necessary, adapt make_table */ U = mzd_submatrix(U, A, r, 0, r + kbar, ncols); _mzd_gauss_submatrix_top(A, r, c, kbar); } if (kbar > 5 * k) { int const rem = kbar % 6; int const ka = kbar / 6 + ((rem >= 5) ? 1 : 0); int const kb = kbar / 6 + ((rem >= 4) ? 1 : 0); int const kc = kbar / 6 + ((rem >= 3) ? 1 : 0); int const kd = kbar / 6 + ((rem >= 2) ? 1 : 0); int const ke = kbar / 6 + ((rem >= 1) ? 1 : 0);; int const kf = kbar / 6; if(full || kbar == kk) { mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4); mzd_make_table(A, r+ka+kb+kc+kd+ke, c, kf, T5, L5); } if(kbar == kk) mzd_process_rows6(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4, T5, L5); if(full) mzd_process_rows6(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4, T5, L5); } else if (kbar > 4 * k) { int const rem = kbar % 5; int const ka = kbar / 5 + ((rem >= 4) ? 1 : 0); int const kb = kbar / 5 + ((rem >= 3) ? 1 : 0); int const kc = kbar / 5 + ((rem >= 2) ? 1 : 0); int const kd = kbar / 5 + ((rem >= 1) ? 1 : 0); int const ke = kbar / 5; if(full || kbar == kk) { mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4); } if(kbar == kk) mzd_process_rows5(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4); if(full) mzd_process_rows5(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4); } else if (kbar > 3 * k) { int const rem = kbar % 4; int const ka = kbar / 4 + ((rem >= 3) ? 1 : 0); int const kb = kbar / 4 + ((rem >= 2) ? 1 : 0); int const kc = kbar / 4 + ((rem >= 1) ? 1 : 0); int const kd = kbar / 4; if(full || kbar == kk) { mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); } if(kbar == kk) mzd_process_rows4(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3); if(full) mzd_process_rows4(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2, T3, L3); } else if (kbar > 2 * k) { int const rem = kbar % 3; int const ka = kbar / 3 + ((rem >= 2) ? 1 : 0); int const kb = kbar / 3 + ((rem >= 1) ? 1 : 0); int const kc = kbar / 3; if(full || kbar == kk) { mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); } if(kbar == kk) mzd_process_rows3(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1, T2, L2); if(full) mzd_process_rows3(A, 0, r, c, kbar, T0, L0, T1, L1, T2, L2); } else if (kbar > k) { int const ka = kbar / 2; int const kb = kbar - ka; if(full || kbar == kk) { mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); } if(kbar == kk) mzd_process_rows2(A, r+kbar, A->nrows, c, kbar, T0, L0, T1, L1); if(full) mzd_process_rows2(A, 0, r, c, kbar, T0, L0, T1, L1); } else if(kbar > 0) { if(full || kbar == kk) { mzd_make_table(A, r, c, kbar, T0, L0); } if(kbar == kk) mzd_process_rows(A, r+kbar, A->nrows, c, kbar, T0, L0); if(full) mzd_process_rows(A, 0, r, c, kbar, T0, L0); } if (!full) { _mzd_copy_back_rows(A, U, r, c, kbar); } r += kbar; c += kbar; if(kk != kbar) { rci_t cbar; rci_t rbar; if (mzd_find_pivot(A, r, c, &rbar, &cbar)) { c = cbar; mzd_row_swap(A, r, rbar); } else { break; } //c++; } } mzd_free(T0); m4ri_mm_free(L0); mzd_free(T1); m4ri_mm_free(L1); mzd_free(T2); m4ri_mm_free(L2); mzd_free(T3); m4ri_mm_free(L3); mzd_free(T4); m4ri_mm_free(L4); mzd_free(T5); m4ri_mm_free(L5); mzd_free(U); __M4RI_DD_MZD(A); __M4RI_DD_RCI(r); return r; } rci_t _mzd_top_echelonize_m4ri(mzd_t *A, int k, rci_t r, rci_t c, rci_t max_r) { rci_t const ncols = A->ncols; int kbar = 0; if (k == 0) { k = m4ri_opt_k(max_r, A->ncols, 0); if (k >= 7) k = 7; if (0.75 * __M4RI_TWOPOW(k) *A->ncols > __M4RI_CPU_L3_CACHE / 2.0) k -= 1; } int kk = 6 * k; mzd_t *U = mzd_init(kk, A->ncols); mzd_t *T0 = mzd_init(__M4RI_TWOPOW(k), A->ncols); mzd_t *T1 = mzd_init(__M4RI_TWOPOW(k), A->ncols); mzd_t *T2 = mzd_init(__M4RI_TWOPOW(k), A->ncols); mzd_t *T3 = mzd_init(__M4RI_TWOPOW(k), A->ncols); mzd_t *T4 = mzd_init(__M4RI_TWOPOW(k), A->ncols); mzd_t *T5 = mzd_init(__M4RI_TWOPOW(k), A->ncols); rci_t *L0 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L1 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L2 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L3 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L4 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); rci_t *L5 = (rci_t*)m4ri_mm_calloc(__M4RI_TWOPOW(k), sizeof(rci_t)); while(c < ncols) { if(c+kk > A->ncols) { kk = ncols - c; } kbar = _mzd_gauss_submatrix_full(A, r, c, MIN(A->nrows,r+kk), kk); if (kbar > 5 * k) { int const rem = kbar % 6; int const ka = kbar / 6 + ((rem >= 5) ? 1 : 0); int const kb = kbar / 6 + ((rem >= 4) ? 1 : 0); int const kc = kbar / 6 + ((rem >= 3) ? 1 : 0); int const kd = kbar / 6 + ((rem >= 2) ? 1 : 0); int const ke = kbar / 6 + ((rem >= 1) ? 1 : 0);; int const kf = kbar / 6; mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4); mzd_make_table(A, r+ka+kb+kc+kd+ke, c, kf, T5, L5); mzd_process_rows6(A, 0, MIN(r, max_r), c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4, T5, L5); } else if (kbar > 4 * k) { int const rem = kbar % 5; int const ka = kbar / 5 + ((rem >= 4) ? 1 : 0); int const kb = kbar / 5 + ((rem >= 3) ? 1 : 0); int const kc = kbar / 5 + ((rem >= 2) ? 1 : 0); int const kd = kbar / 5 + ((rem >= 1) ? 1 : 0); int const ke = kbar / 5; mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); mzd_make_table(A, r+ka+kb+kc+kd, c, ke, T4, L4); mzd_process_rows5(A, 0, MIN(r, max_r), c, kbar, T0, L0, T1, L1, T2, L2, T3, L3, T4, L4); } else if (kbar > 3 * k) { const int rem = kbar%4; const int ka = kbar/4 + ((rem >= 3) ? 1 : 0); const int kb = kbar/4 + ((rem >= 2) ? 1 : 0); const int kc = kbar/4 + ((rem >= 1) ? 1 : 0); const int kd = kbar/4; mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_make_table(A, r+ka+kb+kc, c, kd, T3, L3); mzd_process_rows4(A, 0, MIN(r, max_r), c, kbar, T0, L0, T1, L1, T2, L2, T3, L3); } else if (kbar > 2 * k) { const int rem = kbar%3; const int ka = kbar/3 + ((rem >= 2) ? 1 : 0); const int kb = kbar/3 + ((rem >= 1) ? 1 : 0); const int kc = kbar/3; mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_make_table(A, r+ka+kb, c, kc, T2, L2); mzd_process_rows3(A, 0, MIN(r, max_r), c, kbar, T0, L0, T1, L1, T2, L2); } else if (kbar > k) { const int ka = kbar/2; const int kb = kbar - ka; mzd_make_table(A, r, c, ka, T0, L0); mzd_make_table(A, r+ka, c, kb, T1, L1); mzd_process_rows2(A, 0, MIN(r, max_r), c, kbar, T0, L0, T1, L1); } else if(kbar > 0) { mzd_make_table(A, r, c, kbar, T0, L0); mzd_process_rows(A, 0, MIN(r, max_r), c, kbar, T0, L0); } r += kbar; c += kbar; if(kk != kbar) { c++; } } mzd_free(T0); m4ri_mm_free(L0); mzd_free(T1); m4ri_mm_free(L1); mzd_free(T2); m4ri_mm_free(L2); mzd_free(T3); m4ri_mm_free(L3); mzd_free(T4); m4ri_mm_free(L4); mzd_free(T5); m4ri_mm_free(L5); mzd_free(U); __M4RI_DD_MZD(A); __M4RI_DD_RCI(r); return r; } void mzd_top_echelonize_m4ri(mzd_t *M, int k) { _mzd_top_echelonize_m4ri(M,k,0,0,M->nrows); } mzd_t *mzd_inv_m4ri(mzd_t *B, mzd_t const* A, int k) { assert(A->nrows == A->ncols); if(B == NULL) { B = mzd_init(A->nrows, A->ncols); } else { assert(B->ncols == A->ncols && B->nrows && A->ncols); } const rci_t n = A->nrows; const rci_t nr = m4ri_radix * A->width; mzd_t *C = mzd_init(n, 2*nr); mzd_t *AW = mzd_init_window(C, 0, 0, n, n); mzd_t *BW = mzd_init_window(C, 0, nr, n, nr+n); mzd_copy(AW, A); mzd_set_ui(BW, 1); mzd_echelonize_m4ri(C, TRUE, 0); mzd_copy(B, BW); mzd_free_window(AW); mzd_free_window(BW); mzd_free(C); __M4RI_DD_MZD(B); return B; } mzd_t *mzd_mul_m4rm(mzd_t *C, mzd_t const *A, mzd_t const *B, int k) { rci_t a = A->nrows; rci_t c = B->ncols; if(A->ncols != B->nrows) m4ri_die("mzd_mul_m4rm: A ncols (%d) need to match B nrows (%d).\n", A->ncols, B->nrows); if (C == NULL) { C = mzd_init(a, c); } else { if (C->nrows != a || C->ncols != c) m4ri_die("mzd_mul_m4rm: C (%d x %d) has wrong dimensions.\n", C->nrows, C->ncols); } return _mzd_mul_m4rm(C, A, B, k, TRUE); } mzd_t *mzd_addmul_m4rm(mzd_t *C, mzd_t const *A, mzd_t const *B, int k) { rci_t a = A->nrows; rci_t c = B->ncols; if(C->ncols == 0 || C->nrows == 0) return C; if(A->ncols != B->nrows) m4ri_die("mzd_mul_m4rm A ncols (%d) need to match B nrows (%d) .\n", A->ncols, B->nrows); if (C == NULL) { C = mzd_init(a, c); } else { if (C->nrows != a || C->ncols != c) m4ri_die("mzd_mul_m4rm: C has wrong dimensions.\n"); } return _mzd_mul_m4rm(C, A, B, k, FALSE); } #define __M4RI_M4RM_NTABLES 8 mzd_t *_mzd_mul_m4rm(mzd_t *C, mzd_t const *A, mzd_t const *B, int k, int clear) { /** * The algorithm proceeds as follows: * * Step 1. Make a Gray code table of all the \f$2^k\f$ linear combinations * of the \f$k\f$ rows of \f$B_i\f$. Call the \f$x\f$-th row * \f$T_x\f$. * * Step 2. Read the entries * \f$a_{j,(i-1)k+1}, a_{j,(i-1)k+2} , ... , a_{j,(i-1)k+k}.\f$ * * Let \f$x\f$ be the \f$k\f$ bit binary number formed by the * concatenation of \f$a_{j,(i-1)k+1}, ... , a_{j,ik}\f$. * * Step 3. for \f$h = 1,2, ... , c\f$ do * calculate \f$C_{jh} = C_{jh} + T_{xh}\f$. */ rci_t x[__M4RI_M4RM_NTABLES]; rci_t *L[__M4RI_M4RM_NTABLES]; word const *t[__M4RI_M4RM_NTABLES]; mzd_t *T[__M4RI_M4RM_NTABLES]; #ifdef __M4RI_HAVE_SSE2 mzd_t *Talign[__M4RI_M4RM_NTABLES]; int c_align = (__M4RI_ALIGNMENT(C->rows[0], 16) == 8); #endif word *c; rci_t const a_nr = A->nrows; rci_t const a_nc = A->ncols; rci_t const b_nc = B->ncols; if (b_nc < m4ri_radix-10 || a_nr < 16) { if(clear) return mzd_mul_naive(C, A, B); else return mzd_addmul_naive(C, A, B); } /* clear first */ if (clear) { mzd_set_ui(C, 0); } const int blocksize = __M4RI_MUL_BLOCKSIZE; if(k==0) { /* __M4RI_CPU_L2_CACHE == 2^k * B->width * 8 * 8 */ k = (int)log2((__M4RI_CPU_L2_CACHE/64)/(double)B->width); if ((__M4RI_CPU_L2_CACHE - 64*__M4RI_TWOPOW(k)*B->width) > (64*__M4RI_TWOPOW(k+1)*B->width - __M4RI_CPU_L2_CACHE)) k++; rci_t const klog = round(0.75 * log2_floor(MIN(MIN(a_nr,a_nc),b_nc))); if(klog < k) k = klog; } if (k<2) k=2; else if(k>8) k=8; const wi_t wide = C->width; const word bm = __M4RI_TWOPOW(k)-1; rci_t *buffer = (rci_t*)m4ri_mm_malloc(__M4RI_M4RM_NTABLES * __M4RI_TWOPOW(k) * sizeof(rci_t)); for(int z=0; z<__M4RI_M4RM_NTABLES; z++) { L[z] = buffer + z*__M4RI_TWOPOW(k); #ifdef __M4RI_HAVE_SSE2 /* we make sure that T are aligned as C */ Talign[z] = mzd_init(__M4RI_TWOPOW(k), b_nc+m4ri_radix); T[z] = mzd_init_window(Talign[z], 0, c_align*m4ri_radix, Talign[z]->nrows, b_nc + c_align*m4ri_radix); #else T[z] = mzd_init(__M4RI_TWOPOW(k), b_nc); #endif } /* process stuff that fits into multiple of k first, but blockwise (babystep-giantstep)*/ int const kk = __M4RI_M4RM_NTABLES * k; assert(kk <= m4ri_radix); rci_t const end = a_nc / kk; for (rci_t giantstep = 0; giantstep < a_nr; giantstep += blocksize) { for(rci_t i = 0; i < end; ++i) { #if __M4RI_HAVE_OPENMP #pragma omp parallel for schedule(static,1) #endif for(int z=0; z<__M4RI_M4RM_NTABLES; z++) { mzd_make_table( B, kk*i + k*z, 0, k, T[z], L[z]); } const rci_t blockend = MIN(giantstep+blocksize, a_nr); #if __M4RI_HAVE_OPENMP #pragma omp parallel for schedule(static,512) private(x,t) #endif for(rci_t j = giantstep; j < blockend; j++) { const word a = mzd_read_bits(A, j, kk*i, kk); switch(__M4RI_M4RM_NTABLES) { case 8: t[7] = T[ 7]->rows[ L[7][ (a >> 7*k) & bm ] ]; case 7: t[6] = T[ 6]->rows[ L[6][ (a >> 6*k) & bm ] ]; case 6: t[5] = T[ 5]->rows[ L[5][ (a >> 5*k) & bm ] ]; case 5: t[4] = T[ 4]->rows[ L[4][ (a >> 4*k) & bm ] ]; case 4: t[3] = T[ 3]->rows[ L[3][ (a >> 3*k) & bm ] ]; case 3: t[2] = T[ 2]->rows[ L[2][ (a >> 2*k) & bm ] ]; case 2: t[1] = T[ 1]->rows[ L[1][ (a >> 1*k) & bm ] ]; case 1: t[0] = T[ 0]->rows[ L[0][ (a >> 0*k) & bm ] ]; break; default: m4ri_die("__M4RI_M4RM_NTABLES must be <= 8 but got %d", __M4RI_M4RM_NTABLES); } c = C->rows[j]; switch(__M4RI_M4RM_NTABLES) { case 8: _mzd_combine_8(c, t, wide); break; case 7: _mzd_combine_7(c, t, wide); break; case 6: _mzd_combine_6(c, t, wide); break; case 5: _mzd_combine_5(c, t, wide); break; case 4: _mzd_combine_4(c, t, wide); break; case 3: _mzd_combine_3(c, t, wide); break; case 2: _mzd_combine_2(c, t, wide); break; case 1: _mzd_combine(c, t[0], wide); break; default: m4ri_die("__M4RI_M4RM_NTABLES must be <= 8 but got %d", __M4RI_M4RM_NTABLES); } } } } /* handle stuff that doesn't fit into multiple of kk */ if (a_nc%kk) { rci_t i; for (i = kk / k * end; i < a_nc / k; ++i) { mzd_make_table( B, k*i, 0, k, T[0], L[0]); for(rci_t j = 0; j < a_nr; ++j) { x[0] = L[0][ mzd_read_bits_int(A, j, k*i, k) ]; c = C->rows[j]; t[0] = T[0]->rows[x[0]]; for(wi_t ii = 0; ii < wide; ++ii) { c[ii] ^= t[0][ii]; } } } /* handle stuff that doesn't fit into multiple of k */ if (a_nc%k) { mzd_make_table( B, k*(a_nc/k), 0, a_nc%k, T[0], L[0]); for(rci_t j = 0; j < a_nr; ++j) { x[0] = L[0][ mzd_read_bits_int(A, j, k*i, a_nc%k) ]; c = C->rows[j]; t[0] = T[0]->rows[x[0]]; for(wi_t ii = 0; ii < wide; ++ii) { c[ii] ^= t[0][ii]; } } } } for(int j=0; j<__M4RI_M4RM_NTABLES; j++) { mzd_free(T[j]); #ifdef __M4RI_HAVE_SSE2 mzd_free(Talign[j]); #endif } m4ri_mm_free(buffer); __M4RI_DD_MZD(C); return C; }
batchnormp.c
#include <TH/TH.h> #include "batchnormp.h" #define THNN_CHECK_SHAPE(I1, I2) \ if (I1 != NULL && I2 != NULL && !THFloatTensor_isSameSizeAs(I1, I2)) \ { \ THDescBuff s1 = THFloatTensor_sizeDesc(I1); \ THDescBuff s2 = THFloatTensor_sizeDesc(I2); \ THError(#I1 " and " #I2 " shapes do not match: " \ #I1 " %s, " #I2 " %s", s1.str, s2.str); \ } void BatchNormalizationP_forward( THFloatTensor *input, THFloatTensor *output, THFloatTensor *weight, THFloatTensor *bias, THFloatTensor *running_mean, THFloatTensor *running_var, THFloatTensor *save_mean, THFloatTensor *save_std, int train, double momentum, double eps) { THFloatTensor_resizeAs(output, input); int64_t nInput = THFloatTensor_size(input, 1); int64_t f; ptrdiff_t n = THFloatTensor_nElement(input) / nInput; #pragma omp parallel for for (f = 0; f < nInput; ++f) { THFloatTensor *in = THFloatTensor_newSelect(input, 1, f); THFloatTensor *out = THFloatTensor_newSelect(output, 1, f); float mean, invstd, std; if (train) { // compute mean per input // double sum = 0; // TH_TENSOR_APPLY(float, in, sum += *in_data;); // // mean = (float) sum / n; // THFloatTensor_set1d(save_mean, f, (float) mean); mean = THFloatTensor_get1d(save_mean, f); std = THFloatTensor_get1d(save_std, f); invstd = (float) (1 / (std + eps)); // compute variance per input // sum = 0; // TH_TENSOR_APPLY(float, in, // sum += (*in_data - mean) * (*in_data - mean);); // // if (sum == 0 && eps == 0.0) { // invstd = 0; // } else { // invstd = (float) (1 / sqrt(sum/n + eps)); // } // THFloatTensor_set1d(save_std, f, (float) invstd); // update running averages THFloatTensor_set1d(running_mean, f, (float) (momentum * mean + (1 - momentum) * THFloatTensor_get1d(running_mean, f))); double unbiased_var = std * n / (n - 1); THFloatTensor_set1d(running_var, f, (float) (momentum * unbiased_var + (1 - momentum) * THFloatTensor_get1d(running_var, f))); } else { mean = THFloatTensor_get1d(running_mean, f); invstd = 1 / sqrt(THFloatTensor_get1d(running_var, f) + eps); } // compute output float w = weight ? THFloatTensor_get1d(weight, f) : 1; float b = bias ? THFloatTensor_get1d(bias, f) : 0; TH_TENSOR_APPLY2(float, in, float, out, *out_data = (float) (((*in_data - mean) * invstd) * w + b);); THFloatTensor_free(out); THFloatTensor_free(in); } } void BatchNormalizationP_backward( THFloatTensor *input, THFloatTensor *gradOutput, THFloatTensor *gradInput, THFloatTensor *gradWeight, THFloatTensor *gradBias, THFloatTensor *weight, THFloatTensor *running_mean, THFloatTensor *running_var, THFloatTensor *save_mean, THFloatTensor *save_std, int train, double scale, double eps) { THNN_CHECK_SHAPE(input, gradOutput); int64_t nInput = THFloatTensor_size(input, 1); int64_t f; ptrdiff_t n = THFloatTensor_nElement(input) / nInput; #pragma omp parallel for for (f = 0; f < nInput; ++f) { THFloatTensor *in = THFloatTensor_newSelect(input, 1, f); THFloatTensor *gradOut = THFloatTensor_newSelect(gradOutput, 1, f); float w = weight ? THFloatTensor_get1d(weight, f) : 1; float mean, invstd; if (train) { mean = THFloatTensor_get1d(save_mean, f); invstd = 1 / (THFloatTensor_get1d(save_std, f) + eps); } else { mean = THFloatTensor_get1d(running_mean, f); invstd = 1 / sqrt(THFloatTensor_get1d(running_var, f) + eps); } // sum over all gradOutput in feature plane double sum = 0; TH_TENSOR_APPLY(float, gradOut, sum += *gradOut_data;); // dot product of the Q(X) and gradOuput double dotp = 0; TH_TENSOR_APPLY2(float, in, float, gradOut, dotp += (*in_data - mean) * (*gradOut_data);); if (gradInput) { THFloatTensor_resizeAs(gradInput, input); THFloatTensor *gradIn = THFloatTensor_newSelect(gradInput, 1, f); if (train) { // when in training mode // Q(X) = X - E[x] ; i.e. input centered to zero mean // Y = Q(X) / σ ; i.e. BN output before weight and bias // dL/dX = (Q(dL/dY) - dot(Y, dL/dY) * Y) / σ * w // projection of gradOutput on to output scaled by std float k = (float) dotp * invstd * invstd / n; TH_TENSOR_APPLY2(float, gradIn, float, in, *gradIn_data = (*in_data - mean) * k;); double gradMean = sum / n; TH_TENSOR_APPLY2(float, gradIn, float, gradOut, *gradIn_data = (*gradOut_data - gradMean - *gradIn_data) * invstd * w;); } else { // when in evaluation mode // Q(X) = X - running_mean ; i.e. input centered to zero mean // Y = Q(X) / running_std ; i.e. BN output before weight and bias // dL/dX = w / running_std TH_TENSOR_APPLY2(float, gradIn, float, gradOut, *gradIn_data = *gradOut_data * invstd * w;); } THFloatTensor_free(gradIn); } if (gradWeight) { float val = THFloatTensor_get1d(gradWeight, f); THFloatTensor_set1d(gradWeight, f, val + scale * dotp * invstd); } if (gradBias) { float val = THFloatTensor_get1d(gradBias, f); THFloatTensor_set1d(gradBias, f, val + scale * sum); } THFloatTensor_free(gradOut); THFloatTensor_free(in); } }
ellipticFusedResidualAndNorm.c
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus 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. */ // r = b - Ax // (r,r) extern "C" void fusedResidualAndNorm(const dlong & Nblocks, const dlong & N, const dlong & offset, const dfloat* __restrict__ weights, const dfloat* __restrict__ b_vec, const dfloat* __restrict__ Ax, dfloat* __restrict__ r, dfloat* __restrict__ reduction) { dfloat rdotr = 0.0; #pragma omp parallel for collapse(2) for(int fld = 0 ; fld < p_eNfields; ++fld){ for(int id = 0 ; id < N; ++id){ const dfloat rnew = b_vec[id + fld * offset] - Ax[id + fld * offset]; r[id + fld * offset] = rnew; rdotr += rnew * rnew * weights[id]; } } reduction[0] = rdotr; }
GB_unop__identity_uint8_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__(none)) // op(A') function: GB (_unop_tran__identity_uint8_uint8) // C type: uint8_t // A type: uint8_t // cast: uint8_t cij = aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_unop_apply__(none)) ( uint8_t *Cx, // Cx and Ax may be aliased const uint8_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_uint8_uint8) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_3x3_fp16.c
/* * Copyright (C) 2016-2022 T-Head Semiconductor Co., Ltd. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. */ /* CSI-NN2 version 1.12.x */ /* the conditions for using winograd convolution in_channel >= 16 out_channel >= 16 input_height <= 120 input_width <= 120 */ #include "csi_c906.h" /* padding input for winograd input transform , and change memory layout to [n c/8 h w 8] input layout: [n c h w] input_padded layout: [n c/8 h w 8] constrain: input channel % 8 = 0 */ void csi_c906_pad_input_pack1to8_fp16(const __fp16 *input, __fp16 *input_padded, int inc, int inh, int inw, int padded_h, int padded_w, int pad_top, int pad_left) { int inc8 = inc / 8; int padded_hw = padded_h * padded_w; __fp16 *pad_ptr = input_padded; __fp16 *inp_ptr = (__fp16 *)input; int resi_h = padded_h - pad_top - inh; // remain to pad on h (pad_down) int resi_w = padded_w - pad_left - inw; // remain to pad on w (pad_right) asm volatile( "vsetvli zero, zero, e16, m1\n\t" "vmv.v.x v2, zero\n\t" // clear v2, for memset value 0 "mulw t1, %6, %7\n\t" // pad_top * padded_w "mulw t2, %6, %9\n\t" // pad_down * padded_w "mulw t0, %3, %4\n\t" // input_size per_channel "slli t0, t0, 1\n\t" // load stride = input_size * 2 "slli t6, t0, 3\n\t" // t6 = input_size * 8 * 2 "1:\n\t" // channel loop [inc/8] "mv a0, %0\n\t" // update input_addr "mv t5, %3\n\t" // t5 = in_h "beqz %7, 3f\n\t" // if pad_top = 0 "mv t3, t1\n\t" // t3 = num to memset "2:\n\t" // pad h_top "vse.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "addi t3, t3, -1\n\t" "bnez t3, 2b\n\t" "3:\n\t" // pad h_mid "mv t4, %4\n\t" // t4 = in_w "beqz %8, 5f\n\t" // if pad_left = 0 "mv t3, %8\n\t" // t3 = pad_left "4:\n\t" // pad w_left "vse.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "addi t3, t3, -1\n\t" "bnez t3, 4b\n\t" "5:\n\t" // pad w_mid "vlse.v v4, (a0), t0\n\t" "addi a0, a0, 2\n\t" "vse.v v4, (%1)\n\t" "addi %1, %1, 16\n\t" "addi t4, t4, -1\n\t" "bnez t4, 5b\n\t" "beqz %10, 7f\n\t" // if pad_right = 0 "mv t3, %10\n\t" // t3 = pad_right "6:\n\t" // pad w_right "vse.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "addi t3, t3, -1\n\t" "bnez t3, 6b\n\t" "7:\n\t" "addi t5, t5, -1\n\t" "bnez t5, 3b\n\t" "beqz %9, 9f\n\t" // if pad_down = 0 "mv t3, t2\n\t" // t3 = num to memset 0 "8:\n\t" // pad h_down "vse.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "addi t3, t3, -1\n\t" "bnez t3, 8b\n\t" "9:\n\t" "add %0, %0, t6\n\t" // input_data jump to next 8 channel "addi %2, %2, -1\n\t" "bnez %2, 1b\n\t" :"=r"(inp_ptr), // %0 "=r"(pad_ptr), // %1 "=r"(inc8), // %2 "=r"(inh), // %3 "=r"(inw), // %4 "=r"(padded_hw), // %5 "=r"(padded_w), // %6 "=r"(pad_top), // %7 "=r"(pad_left), // %8 "=r"(resi_h), // %9 "=r"(resi_w) // %10 :"0"(inp_ptr), "1"(pad_ptr), "2"(inc8), "3"(inh), "4"(inw), "5"(padded_hw), "6"(padded_w), "7"(pad_top), "8"(pad_left), "9"(resi_h), "10"(resi_w) :"cc", "memory", "v2", "v4", "a0", "t0", "t1", "t2", "t3", "t4", "t5", "t6" ); } void csi_c906_crop_output_pack8to1_fp16(const __fp16 *output_trans, __fp16 *output, int out_c, int out_h, int out_w, int wino_h, int wino_w) { int out_c8 = out_c / 8; __fp16 *out_tm_ptr = (__fp16 *)output_trans; __fp16 *out_ptr = output; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mulw t0, %3, %4\n\t" // output_size per_channel "slli t0, t0, 1\n\t" // store_stride = output_size * 2 "slli t3, t0, 3\n\t" // t3 = output_size * 8 * 2 "slli t4, %6, 4\n\t" // t4 = wino_w * 8 * 2 "mulw t5, %5, %6\n\t" // crop_size per_channel "slli t5, t5, 4\n\t" // t5 = crop_size * 8 * 2 "1:\n\t" // channel loop [out_ch / 8] "mv a1, %1\n\t" // update output_addr "mv a0, %0\n\t" // update crop_addr per-channel "mv t1, %3\n\t" // t1 = out_h "2:\n\t" // crop h "mv t2, %4\n\t" // t2 = out_w "mv s1, a0\n\t" // update crop_addr per-row "3:\n\t" // crop w "vle.v v2, (s1)\n\t" "addi s1, s1, 16\n\t" "vsse.v v2, (a1), t0\n\t" "addi a1, a1, 2\n\t" "addi t2, t2, -1\n\t" "bnez t2, 3b\n\t" "add a0, a0, t4\n\t" // crop-data jump to next row "addi t1, t1, -1\n\t" "bnez t1, 2b\n\t" "4:\n\t" "add %1, %1, t3\n\t" // output_data jump to next 8 channel "add %0, %0, t5\n\t" // crop-data jump to next 8 channel "addi %2, %2, -1\n\t" "bnez %2, 1b\n\t" :"=r"(out_tm_ptr), // %0 "=r"(out_ptr), // %1 "=r"(out_c8), // %2 "=r"(out_h), // %3 "=r"(out_w), // %4 "=r"(wino_h), // %5 "=r"(wino_w) // %6 :"0"(out_tm_ptr), "1"(out_ptr), "2"(out_c8), "3"(out_h), "4"(out_w), "5"(wino_h), "6"(wino_w) :"cc", "memory", "v2", "v3", "a0", "a1", "s1", "t0", "t1", "t2", "t3", "t4", "t5" ); } /* constrain: output channel % 8 = 0 input channel % 8 = 0 kernel before: [O I 3*3] kernel after : [O/8 8*8 I 8] */ void csi_c906_conv3x3s1_winograd64_transform_kernel_pack8_fp16(struct csi_tensor *o_kernel, struct csi_tensor *t_kernel) { int32_t outch = o_kernel->dim[0]; int32_t inch = o_kernel->dim[1]; __fp16 *kernel_data = (__fp16 *)o_kernel->data; // for kernel transform buf, 3x3 --> 8x8 __fp16 *kernel_tm = (__fp16 *)csi_mem_alloc(outch * inch * 8 * 8 * sizeof(__fp16)); // kernel transform matrix: G const __fp16 ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; // const __fp16 ktm[8][3] = { // {1.0f, 0.0f, 0.0f}, // {-2.0f / 9, -2.0f / 9, -2.0f / 9}, // {-2.0f / 9, 2.0f / 9, -2.0f / 9}, // {1.0f / 90, 1.0f / 45, 2.0f / 45}, // {1.0f / 90, -1.0f / 45, 2.0f / 45}, // {32.0f / 45, 16.0f / 45, 8.0f / 45}, // {32.0f / 45, -16.0f / 45, 8.0f / 45}, // {0.0f, 0.0f, 1.0f} // }; csi_tensor_copy(t_kernel, o_kernel); for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const __fp16* kernel0 = kernel_data + p * inch * 9 + q * 9; __fp16* kernel_tmp = kernel_tm + p * inch * 64 + q * 64; // transform kernel const __fp16 *k0 = kernel0; const __fp16 *k1 = kernel0 + 3; const __fp16 *k2 = kernel0 + 6; // h : first compute the transport matrix tmp = (g * GT)T __fp16 tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 8; j++) { __fp16* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tmp[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // optimized layout for winograd64 __fp16 *kernel_tm_pack8 = (__fp16 *)csi_mem_alloc(outch * inch * 8 * 8 * sizeof(__fp16)); t_kernel->data = kernel_tm_pack8; for (int oc = 0; oc < outch / 8; oc++) { __fp16 *g0 = kernel_tm_pack8 + oc * 64 * inch * 8; const __fp16 *k0 = kernel_tm + oc * 64 * inch * 8; const __fp16 *k1 = k0 + 64 * inch; const __fp16 *k2 = k1 + 64 * inch; const __fp16 *k3 = k2 + 64 * inch; const __fp16 *k4 = k3 + 64 * inch; const __fp16 *k5 = k4 + 64 * inch; const __fp16 *k6 = k5 + 64 * inch; const __fp16 *k7 = k6 + 64 * inch; for (int k = 0; k < 64; k++) { __fp16 *g00 = g0 + k * inch * 8; for (int ic = 0; ic < inch / 8; ic++) { for (int i = 0; i < 8; i++) { const __fp16 *k00 = k0 + (ic * 8 + i) * 64; const __fp16 *k10 = k1 + (ic * 8 + i) * 64; const __fp16 *k20 = k2 + (ic * 8 + i) * 64; const __fp16 *k30 = k3 + (ic * 8 + i) * 64; const __fp16 *k40 = k4 + (ic * 8 + i) * 64; const __fp16 *k50 = k5 + (ic * 8 + i) * 64; const __fp16 *k60 = k6 + (ic * 8 + i) * 64; const __fp16 *k70 = k7 + (ic * 8 + i) * 64; g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k40[k]; g00[5] = k50[k]; g00[6] = k60[k]; g00[7] = k70[k]; g00 += 8; } } } } csi_mem_free(kernel_tm); } /* constrain: output channel % 8 = 0 input channel % 8 = 0 */ int csi_c906_conv3x3s1_winograd64_pack8_fp16(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { // uint64_t start_time, end_time; // start_time = csi_get_timespec(); __fp16 *input_data = (__fp16 *)input->data; __fp16 *output_data = (__fp16 *)output->data; __fp16 *kernel_data = (__fp16 *)params->conv_extra.kernel_tm->data; __fp16 *bias_data = (__fp16 *)bias->data; // param int kernel_h = kernel->dim[2]; int kernel_w = kernel->dim[3]; int stride_h = params->stride_height; int stride_w = params->stride_width; int dilation_h = params->dilation_height; int dilation_w = params->dilation_width; int pad_left = params->pad_left; int pad_top = params->pad_top; int batch = input->dim[0]; int in_c = input->dim[1]; int in_h = input->dim[2]; int in_w = input->dim[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int out_c = kernel->dim[0]; int out_h = output->dim[2]; int out_w = output->dim[3]; int output_size = out_c * out_h * out_w; // winograd param int block_h = (out_h + 5) / 6; int block_w = (out_w + 5) / 6; int padded_in_h = block_h * 6 + 2; // block * 4 for alignment with 4,kernel = 3 * 3 ,stride = 1,thus input_size + 2 int padded_in_w = block_w * 6 + 2; int padded_in_hw = padded_in_h * padded_in_w; // element size after padding per channel /****************************** bias *****************************/ bool flag_bias = 1; // default: conv2d layer include bias if (bias_data == NULL) { flag_bias = 0; bias_data = (__fp16 *)csi_mem_alloc(out_c * sizeof(__fp16)); } for(int n = 0; n < batch; n++) { // pad buffer: [in_c/8 h w 8] __fp16 *input_padd_buf = (__fp16 *)csi_mem_alloc(in_c * padded_in_hw * sizeof(__fp16)); // pad input csi_c906_pad_input_pack1to8_fp16(input_data, input_padd_buf, in_c, in_h, in_w, padded_in_h, padded_in_w, pad_top, pad_left); input_data += input_size; // input transform buffer1: [in_ch/8, 64, blocks, 8] __fp16 *input_tm1_buf = (__fp16 *)csi_mem_alloc(in_c * block_h * block_w * 8 * 8 * sizeof(__fp16)); /****************************** transform input *****************************/ /* BT = { { 1 0 -5.25 0 5.25 0 -1 0 }; { 0 1 1 -4.25 -4.25 1 1 0 }; { 0 -1 1 4.25 -4.25 -1 1 0 }; { 0 0.5 0.25 -2.5 -1.25 2 1 0 }; { 0 -0.5 0.25 2.5 -1.25 -2 1 0 }; { 0 2 4 -2.5 -5 0.5 1 0 }; { 0 -2 4 2.5 -5 -0.5 1 0 }; { 0 -1 0 5.25 0 -5.25 0 1 } }; */ // int in_h_tm = block_h * 8; // input height after transform // int in_w_tm = block_w * 8; int tiles = block_h * block_w; #pragma omp parallel for num_threads(1) for(int q = 0; q < in_c / 8; q++) { __fp16 *img0 = input_padd_buf + q * padded_in_h * padded_in_w * 8; // feature map after padding - q channel __fp16 *img0_tm = input_tm1_buf + q * 64 * tiles * 8; // transform and interleave - q channel __fp16 *tmp = (__fp16 *)csi_mem_alloc(8 * 8 * 8 * sizeof(__fp16)); // __fp16 tmp[512] = {0.0}; // ?????? for(int i = 0; i < block_h; i++) { for(int j = 0; j < block_w; j++) { __fp16 *r0 = img0 + (i * padded_in_w * 6 + j * 6) * 8; // feature map after padding 8*8 start addr __fp16 *r0_tm = img0_tm + (i * block_w + j) * 8; // input_tm1 8*8 block start addr __fp16 ratio[] = {5.25, -4.25, 0.25, -1.25, 4.0, 0.5, -2.5, 2.0}; // note: in fact cannot be output constrain __fp16 *ratio_ptr = ratio; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "li t0, 8\n\t" // m = 8 "mv t5, %2\n\t" // t5 = tmp start addr "slli t1, %4, 4\n\t" // t1 = padded_in_w * 8 * 2bytes "flh fa0, 0(%3)\n\t" // fa0 = 5.25 "flh fa1, 2(%3)\n\t" // fa1 = -4.25 "flh fa2, 4(%3)\n\t" // fa2 = 0.25 "flh fa3, 6(%3)\n\t" // fa3 = -1.25 "flh fa4, 8(%3)\n\t" // fa4 = 4.0 "flh fa5, 10(%3)\n\t" // fa5 = 0.5 "flh fa6, 12(%3)\n\t" // fa6 = -2.5 "flh fa7, 14(%3)\n\t" // fa7 = 2.0 "1:\n\t" "mv s1, %0\n\t" // s1 = r00 addr "mv a0, t5\n\t" // tmp[0][m] "addi a1, a0, 128\n\t" // tmp[1][m] "addi a2, a1, 128\n\t" // tmp[2][m] "addi a3, a2, 128\n\t" // tmp[3][m] "addi a4, a3, 128\n\t" // tmp[4][m] "addi a5, a4, 128\n\t" // tmp[5][m] "addi a6, a5, 128\n\t" // tmp[6][m] "addi a7, a6, 128\n\t" // tmp[7][m] "vle.v v0, (s1)\n\t" // r00 "addi s1, s1, 16\n\t" "vle.v v1, (s1)\n\t" // r01 "addi s1, s1, 16\n\t" "vle.v v2, (s1)\n\t" // r02 "addi s1, s1, 16\n\t" "vle.v v3, (s1)\n\t" // r03 "addi s1, s1, 16\n\t" "vle.v v4, (s1)\n\t" // r04 "addi s1, s1, 16\n\t" "vle.v v5, (s1)\n\t" // r05 "addi s1, s1, 16\n\t" "vle.v v6, (s1)\n\t" // r06 "addi s1, s1, 16\n\t" "vle.v v7, (s1)\n\t" // r07 "addi s1, s1, 16\n\t" "vmv.v.v v10, v6\n\t" //--------------------------------------------- "vfsub.vv v8, v4, v2\n\t" // r04 - r02 "vfsub.vv v9, v3, v5\n\t" // r03 - r05 "vfsub.vv v24, v0, v6\n\t" // r00 - r06 "vfsub.vv v31, v7, v1\n\t" // r07 - r01 "vfmacc.vf v10, fa2, v2\n\t" // r06 + r02 * 0.25f "vfmul.vf v11, v1, fa5\n\t" // r01 * 0.5f "vfmul.vf v12, v1, fa7\n\t" // r01 * 2.0f "vfmacc.vf v24, fa0, v8\n\t" // r00 - r06 + 5.25 * (r04 - r02) = tmp[0][m] "vfmacc.vf v31, fa0, v9\n\t" // r07 - r01 + 5.25 * (r03 - r05) = tmp[7][m] //--------------------------------------------- "vfadd.vv v8, v2, v6\n\t" // r02 + r06 "vfadd.vv v9, v1, v5\n\t" // r01 + r05 "vfmacc.vf v11, fa6, v3\n\t" // r01 * 0.5f - r03 * 2.5f "vfmacc.vf v12, fa6, v3\n\t" // r01 * 2.f - r03 * 2.5f "vfmacc.vf v2, fa3, v4\n\t" // r02 - r04 * 1.25f 注意 "vfmacc.vf v10, fa3, v4\n\t" // r06 + r02 * 0.25f - r04 * 1.25f = tmp34a "vfmacc.vf v8, fa1, v4\n\t" // r02 + r06 - r04 * 4.25f = tmp12a "vfmacc.vf v9, fa1, v3\n\t" // r01 + r05 - r03 * 4.25f = tmp12b "vfmacc.vf v11, fa7, v5\n\t" // r01 * 0.5f - r03 * 2.5f + r05 * 2.0 = tmp34b "vfmacc.vf v12, fa5, v5\n\t" // r01 * 2.f - r03 * 2.5f + r05 * 0.5 = tmp56b "vse.v v24, (a0)\n\t" "vse.v v31, (a7)\n\t" "vfadd.vv v25, v8, v9\n\t" // tmp12a + tmp12b = tmp[1][m] "vfsub.vv v26, v8, v9\n\t" // tmp12a - tmp12b = tmp[2][m] //--------------------------------------------- "vfmacc.vf v6, fa4, v2\n\t" // r06 + (r02 - r04 * 1.25f) * 4 = tmp56a "vfadd.vv v27, v10, v11\n\t" // tmp34a + tmp34b = tmp[3][m] "vfsub.vv v28, v10, v11\n\t" // tmp34a - tmp34b = tmp[4][m] "vfadd.vv v29, v6, v12\n\t" // tmp56a + tmp56b = tmp[5][m] "vfsub.vv v30, v6, v12\n\t" // tmp56a - tmp56b = tmp[6][m] "vse.v v25, (a1)\n\t" "vse.v v26, (a2)\n\t" "vse.v v27, (a3)\n\t" "vse.v v28, (a4)\n\t" "vse.v v29, (a5)\n\t" "vse.v v30, (a6)\n\t" //--------------------------------------------- "add %0, %0, t1\n\t" // padding feature map 8*8 next line addr "addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1] "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "2:\n\t" "mv t5, %2\n\t" // tmp start addr "li t0, 8\n\t" // m = 8 "slli t1, %5, 4\n\t" // t1 = tiles * 8 * 2 bytes "slli t2, %5, 7\n\t" // t2 = tiles * 8 * 8 * 2 bytes "3:\n\t" "mv a0, %1\n\t" // r0_tm_0 "add a1, a0, t1\n\t" // r0_tm_1 "add a2, a1, t1\n\t" // r0_tm_2 "add a3, a2, t1\n\t" // r0_tm_3 "add a4, a3, t1\n\t" // r0_tm_4 "add a5, a4, t1\n\t" // r0_tm_5 "add a6, a5, t1\n\t" // r0_tm_6 "add a7, a6, t1\n\t" // r0_tm_7 "vle.v v0, (t5)\n\t" // tmp[m][0] "addi t5, t5, 16\n\t" "vle.v v1, (t5)\n\t" // tmp[m][1] "addi t5, t5, 16\n\t" "vle.v v2, (t5)\n\t" // tmp[m][2] "addi t5, t5, 16\n\t" "vle.v v3, (t5)\n\t" // tmp[m][3] "addi t5, t5, 16\n\t" "vle.v v4, (t5)\n\t" // tmp[m][4] "addi t5, t5, 16\n\t" "vle.v v5, (t5)\n\t" // tmp[m][5] "addi t5, t5, 16\n\t" "vle.v v6, (t5)\n\t" // tmp[m][6] "addi t5, t5, 16\n\t" "vle.v v7, (t5)\n\t" // tmp[m][7] "addi t5, t5, 16\n\t" "vmv.v.v v10, v6\n\t" //--------------------------------------------- "vfsub.vv v8, v4, v2\n\t" // tmp04 - tmp02 (tmp[m][4] - tmp[m][2]) "vfsub.vv v9, v3, v5\n\t" // tmp03 - tmp05 "vfsub.vv v24, v0, v6\n\t" // tmp00 - tmp06 "vfsub.vv v31, v7, v1\n\t" // tmp07 - tmp01 "vfmacc.vf v10, fa2, v2\n\t" // tmp06 + tmp02 * 0.25f "vfmul.vf v11, v1, fa5\n\t" // tmp01 * 0.5f "vfmul.vf v12, v1, fa7\n\t" // tmp01 * 2.0f "vfmacc.vf v24, fa0, v8\n\t" // tmp00 - tmp06 + 5.25 * (tmp04 - tmp02) = r0_tm_0[m] "vfmacc.vf v31, fa0, v9\n\t" // tmp07 - tmp01 + 5.25 * (tmp03 - tmp05) = r0_tm_7[m] //--------------------------------------------- "vfadd.vv v8, v2, v6\n\t" // tmp02 + tmp06 "vfadd.vv v9, v1, v5\n\t" // tmp01 + tmp05 "vfmacc.vf v11, fa6, v3\n\t" // tmp01 * 0.5f - tmp03 * 2.5f "vfmacc.vf v12, fa6, v3\n\t" // tmp01 * 2.f - tmp03 * 2.5f "vfmacc.vf v2, fa3, v4\n\t" // tmp02 - tmp04 * 1.25f "vfmacc.vf v10, fa3, v4\n\t" // tmp06 + tmp02 * 0.25f - tmp04 * 1.25f = tmp34a "vfmacc.vf v8, fa1, v4\n\t" // tmp02 + tmp06 - tmp04 * 4.25f = tmp12a "vfmacc.vf v9, fa1, v3\n\t" // tmp01 + tmp05 - tmp03 * 4.25f = tmp12b "vfmacc.vf v11, fa7, v5\n\t" // tmp01 * 0.5f - tmp03 * 2.5f + tmp05 * 2.0 = tmp34b "vfmacc.vf v12, fa5, v5\n\t" // tmp01 * 2.f - tmp03 * 2.5f + tmp05 * 0.5 = tmp56b "vse.v v24, (a0)\n\t" "vse.v v31, (a7)\n\t" "vfadd.vv v25, v8, v9\n\t" // tmp12a + tmp12b = r0_tm_1[m] "vfsub.vv v26, v8, v9\n\t" // tmp12a - tmp12b = r0_tm_2[m] //--------------------------------------------- "vfmacc.vf v6, fa4, v2\n\t" // tmp06 + (tmp02 - tmp04 * 1.25f) * 4 = tmp56a "vfadd.vv v27, v10, v11\n\t" // tmp34a + tmp34b = r0_tm_3[m] "vfsub.vv v28, v10, v11\n\t" // tmp34a - tmp34b = r0_tm_4[m] "vfadd.vv v29, v6, v12\n\t" // tmp56a + tmp56b = r0_tm_5[m] "vfsub.vv v30, v6, v12\n\t" // tmp56a - tmp56b = r0_tm_6[m] "vse.v v25, (a1)\n\t" "vse.v v26, (a2)\n\t" "vse.v v27, (a3)\n\t" "vse.v v28, (a4)\n\t" "vse.v v29, (a5)\n\t" "vse.v v30, (a6)\n\t" "add %1, %1, t2\n\t" "addi t0, t0, -1\n\t" "bnez t0, 3b" :"=r"(r0), // %0 "=r"(r0_tm), // %1 "=r"(tmp), // %2 "=r"(ratio_ptr), // %3 "=r"(padded_in_w), // %4 "=r"(tiles) // %5 :"0"(r0), "1"(r0_tm), "2"(tmp), "3"(ratio_ptr), "4"(padded_in_w), "5"(tiles) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7" ); } } csi_mem_free(tmp); } csi_mem_free(input_padd_buf); /*********************************** dot ***************************************/ // reorder input_tm1_buf __fp16 *input_tm2_buf = (__fp16 *)csi_mem_alloc(64 * tiles * in_c * sizeof(__fp16)); #pragma omp parallel for num_threads(1) for (int r = 0; r < 64; r++) { __fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // input_tm2 r channel data int t = 0; for (; t + 7 < tiles; t += 8) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; //---------------------------- // for (int q = 0; q < in_c / 8; q++) { // for (int l = 0; l < 8; l++) { // tm2[0] = tm1[l]; // tm2[1] = tm1[l + 8 * 1]; // tm2[2] = tm1[l + 8 * 2]; // tm2[3] = tm1[l + 8 * 3]; // tm2[4] = tm1[l + 8 * 4]; // tm2[5] = tm1[l + 8 * 5]; // tm2[6] = tm1[l + 8 * 6]; // tm2[7] = tm1[l + 8 * 7]; // tm2 += 8; // } // tm1 += 64 * tiles * 8; // } //----------------------------- asm volatile( "vsetvli zero, zero, e16, m1\n\t" "slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes "srai t2, %3, 3\n\t" // in_ch8 "1:\n\t" // in_ch loop8 "mv a0, %1\n\t" // updata tm1 addr "vle.v v0, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v1, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v2, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v3, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v4, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v5, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v6, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v7, (a0)\n\t" "vsseg8e.v v0, (%0)\n\t" "add %1, %1, t1\n\t" "addi %0, %0, 128\n\t" "addi t2, t2, -1\n\t" "bnez t2, 1b\n\t" :"=r"(tm2), // %0 "=r"(tm1), // %1 "=r"(tiles), // %2 "=r"(in_c) // %3 :"0"(tm2), "1"(tm1), "2"(tiles), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "a0", "t1", "t2" ); } for (; t + 3 < tiles; t += 4) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; // for (int q = 0; q < in_c / 8; q++) { // for (int l = 0; l < 8; l++) { // tm2[0] = tm1[l]; // tm2[1] = tm1[l + 8 * 1]; // tm2[2] = tm1[l + 8 * 2]; // tm2[3] = tm1[l + 8 * 3]; // tm2 += 4; // } // tm1 += 64 * tiles * 8; // } asm volatile( "vsetvli zero, zero, e16, m1\n\t" "slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes "srai t2, %3, 3\n\t" // in_ch8 "1:\n\t" // in_ch loop8 "mv a0, %1\n\t" // updata tm1 addr "vle.v v0, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v1, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v2, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v3, (a0)\n\t" "vsseg4e.v v0, (%0)\n\t" "add %1, %1, t1\n\t" "addi %0, %0, 64\n\t" "addi t2, t2, -1\n\t" "bnez t2, 1b\n\t" :"=r"(tm2), // %0 "=r"(tm1), // %1 "=r"(tiles), // %2 "=r"(in_c) // %3 :"0"(tm2), "1"(tm1), "2"(tiles), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "a0", "t1", "t2" ); } for (; t + 1 < tiles; t += 2) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; // for (int q = 0; q < in_c / 8; q++) { // for (int l = 0; l < 8; l++) { // tm2[0] = tm1[l]; // tm2[1] = tm1[l + 8]; // tm2 += 2; // } // tm1 += 64 * tiles * 8; // } asm volatile( "vsetvli zero, zero, e16, m1\n\t" "slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes "srai t2, %3, 3\n\t" // in_ch8 "1:\n\t" // in_ch loop8 "mv a0, %1\n\t" // updata tm1 addr "vle.v v0, (a0)\n\t" "addi a0, a0, 16\n\t" "vle.v v1, (a0)\n\t" "vsseg2e.v v0, (%0)\n\t" "add %1, %1, t1\n\t" "addi %0, %0, 32\n\t" "addi t2, t2, -1\n\t" "bnez t2, 1b\n\t" :"=r"(tm2), // %0 "=r"(tm1), // %1 "=r"(tiles), // %2 "=r"(in_c) // %3 :"0"(tm2), "1"(tm1), "2"(tiles), "3"(in_c) :"cc", "memory", "v0", "v1", "a0", "t1", "t2" ); } for (; t < tiles; t++) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; // for (int q = 0; q < in_c / 8; q++) { // for (int l = 0; l < 8; l++) { // tm2[0] = tm1[l]; // tm2++; // } // tm1 += 64 * tiles * 8; // } asm volatile( "vsetvli zero, zero, e16, m1\n\t" "slli t1, %2, 10\n\t" // 64 * tiles * 8 * 2 bytes "srai t2, %3, 3\n\t" // in_ch8 "1:\n\t" // in_ch loop8 "mv a0, %1\n\t" // updata tm1 addr "vle.v v0, (a0)\n\t" "addi a0, a0, 16\n\t" "vse.v v0, (%0)\n\t" "add %1, %1, t1\n\t" "addi %0, %0, 16\n\t" "addi t2, t2, -1\n\t" "bnez t2, 1b\n\t" :"=r"(tm2), // %0 "=r"(tm1), // %1 "=r"(tiles), // %2 "=r"(in_c) // %3 :"0"(tm2), "1"(tm1), "2"(tiles), "3"(in_c) :"cc", "memory", "v0", "a0", "t1", "t2" ); } } csi_mem_free(input_tm1_buf); // output_dot_buf: [out_c/8, 64, blocks, 8] __fp16 *output_dot_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 8 * 8 * sizeof(__fp16)); #pragma omp parallel for num_threads(1) for (int p = 0; p < out_c / 8; p++) { __fp16 *output0_tm = output_dot_buf + p * 64 * tiles * 8; __fp16 *kernel0_tm = kernel_data + p * 64 * in_c * 8; for (int r = 0; r < 64; r++) { __fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // img_tm2 第r个channel int t = 0; for (; t + 7 < tiles; t += 8) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" "vmv.v.x v2, zero\n\t" "vmv.v.x v3, zero\n\t" "vmv.v.x v4, zero\n\t" "vmv.v.x v5, zero\n\t" "vmv.v.x v6, zero\n\t" "vmv.v.x v7, zero\n\t" // clear "1:\n\t" "vle.v v8, (%1)\n\t" "addi %1, %1, 16\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "flh fa2, 4(%0)\n\t" "flh fa3, 6(%0)\n\t" "flh fa4, 8(%0)\n\t" "flh fa5, 10(%0)\n\t" "flh fa6, 12(%0)\n\t" "flh fa7, 14(%0)\n\t" "addi %0, %0, 16\n\t" "vfmacc.vf v0, fa0, v8\n\t" "vfmacc.vf v1, fa1, v8\n\t" "vfmacc.vf v2, fa2, v8\n\t" "vfmacc.vf v3, fa3, v8\n\t" "vfmacc.vf v4, fa4, v8\n\t" "vfmacc.vf v5, fa5, v8\n\t" "vfmacc.vf v6, fa6, v8\n\t" "vfmacc.vf v7, fa7, v8\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v2, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v3, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v4, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v5, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v6, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v7, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "t0" ); } for (; t + 3 < tiles; t += 4) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" "vmv.v.x v2, zero\n\t" "vmv.v.x v3, zero\n\t" // clear "1:\n\t" "vle.v v4, (%1)\n\t" "addi %1, %1, 16\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "flh fa2, 4(%0)\n\t" "flh fa3, 6(%0)\n\t" "addi %0, %0, 8\n\t" "vfmacc.vf v0, fa0, v4\n\t" "vfmacc.vf v1, fa1, v4\n\t" "vfmacc.vf v2, fa2, v4\n\t" "vfmacc.vf v3, fa3, v4\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v2, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v3, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "fa0", "fa1", "fa2", "fa3", "t0" ); } for (; t + 1 < tiles; t += 2) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" // clear "1:\n\t" "vle.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "addi %0, %0, 4\n\t" "vfmacc.vf v0, fa0, v2\n\t" "vfmacc.vf v1, fa1, v2\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "fa0", "fa1", "t0" ); } for (; t < tiles; t++) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c= "vmv.v.x v0, zero\n\t" // clear "1:\n\t" "vle.v v1, (%1)\n\t" "addi %1, %1, 16\n\t" "flh fa0, (%0)\n\t" "addi %0, %0, 2\n\t" "vfmacc.vf v0, fa0, v1\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "fa0", "t0" ); } } } csi_mem_free(input_tm2_buf); /*************************** transform output ****************************/ // output_tm1_buf: [out_c/8, out_h6, out_w6, 8] __fp16 *output_tm1_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 6 * 6 * sizeof(__fp16)); /* AT = { { 1 1 1 1 1 1 1 0 }; { 0 1 -1 2 -2 1/2 -1/2 0 }; { 0 1 1 4 4 1/4 1/4 0 }; { 0 1 -1 8 -8 1/8 -1/8 0 }; { 0 1 1 16 16 1/16 1/16 0 }; { 0 1 -1 32 -32 1/32 -1/32 1 } }; AT = { { 1 1 1 1 1 32 32 0 }; { 0 1 -1 2 -2 16 -16 0 }; { 0 1 1 4 4 8 8 0 }; { 0 1 -1 8 -8 4 -4 0 }; { 0 1 1 16 16 2 2 0 }; { 0 1 -1 32 -32 1 -1 1 } }; */ #pragma omp parallel for num_threads(1) for (int p = 0; p < out_c / 8; p++) { __fp16 *bias_tmp = bias_data + p * 8; __fp16 *out0_tm = output_dot_buf + p * 64 * block_h * block_w * 8; // 输出转换前/dot后 第p个channel __fp16 *out0 = output_tm1_buf + p * 6*block_h * 6*block_w * 8; // 转换后输出 第p个channel __fp16 *tmp1 = (__fp16 *)csi_mem_alloc(6 * 8 * 8 * sizeof(__fp16)); // __fp16 tmp[6][8][8]; int out_w6 = block_w * 6; for (int i = 0; i < block_h; i++) { for (int j = 0; j < block_w; j++) { __fp16 *output0_tm_0 = out0_tm + (i * block_w + j) * 8; // 8*8 起始地址 __fp16 *output0 = out0 + (i * block_w * 6 * 6 + j * 6) * 8; // 输出 6*6 的起始地址 __fp16 ratio[] = {2.0, 4.0, 8.0, 16.0, 32.0}; __fp16 *ratio_ptr = ratio; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "li t0, 8\n\t" // m = 8 "mv t5, %2\n\t" // t5 = tmp start addr "slli t1, %4, 4\n\t" // t1 = tiles * 8 * 2 "slli t2, %4, 7\n\t" // t2 = tiles * 8 * 8 * 2 bytes "flh fa0, 0(%3)\n\t" // fa0 = 2 "flh fa1, 2(%3)\n\t" // fa1 = 4 "flh fa2, 4(%3)\n\t" // fa2 = 8 "flh fa3, 6(%3)\n\t" // fa3 = 16 "flh fa4, 8(%3)\n\t" // fa4 = 32 "mv s1, %0\n\t" "1:\n\t" // shape : [6 * 8] * [8 * 8] = [6 * 8] "mv a0, t5\n\t" // tmp[0][m] "addi a1, a0, 128\n\t" // tmp[1][m] "addi a2, a1, 128\n\t" // tmp[2][m] "addi a3, a2, 128\n\t" // tmp[3][m] "addi a4, a3, 128\n\t" // tmp[4][m] "addi a5, a4, 128\n\t" // tmp[5][m] "vle.v v0, (s1)\n\t" // r00 "add s1, s1, t1\n\t" "vle.v v1, (s1)\n\t" // r01 "add s1, s1, t1\n\t" "vle.v v2, (s1)\n\t" // r02 "add s1, s1, t1\n\t" "vle.v v3, (s1)\n\t" // r03 "add s1, s1, t1\n\t" "vle.v v4, (s1)\n\t" // r04 "add s1, s1, t1\n\t" "vle.v v5, (s1)\n\t" // r05 "add s1, s1, t1\n\t" "vle.v v6, (s1)\n\t" // r06 "add s1, s1, t1\n\t" "vle.v v7, (s1)\n\t" // r07 "add s1, s1, t1\n\t" //--------------------------------------------- "vfadd.vv v8, v1, v2\n\t" // r01 + r02 = tmp024a "vfsub.vv v9, v1, v2\n\t" // r01 - r02 = tmp135a "vfadd.vv v10, v3, v4\n\t" // r03 + r04 = tmp024b "vfsub.vv v11, v3, v4\n\t" // r03 - r04 = tmp135b "vfadd.vv v12, v5, v6\n\t" // r05 + r06 = tmp024c "vfsub.vv v13, v5, v6\n\t" // r05 - r06 = tmp135c "vfadd.vv v0, v0, v8\n\t" // r00 + tmp024a "vfadd.vv v7, v7, v9\n\t" // r07 + tmp135a "vmv.v.v v14, v10\n\t" // v14 = tmp024b "vmv.v.v v26, v8\n\t" // v26 = tmp024a "vmv.v.v v28, v8\n\t" // v28 = tmp024a "vfmacc.vf v26, fa1, v10\n\t" // tmp024a + tmp024b * 4 "vfmacc.vf v14, fa4, v12\n\t" // tmp024b + tmp024c * 32 "vfmacc.vf v28, fa3, v10\n\t" // tmp024a + tmp024b * 16 "vmv.v.v v15, v13\n\t" // v15 = tmp135c "vmv.v.v v25, v9\n\t" // v25 = tmp135a "vmv.v.v v27, v9\n\t" // v27 = tmp135a "vfadd.vv v24, v0, v14\n\t" // r00 + tmp024a + tmp024b + tmp024c * 32 = tmp[0][m] "vfmacc.vf v25, fa0, v11\n\t" // tmp135a + tmp135b * 2 "vfmacc.vf v27, fa2, v11\n\t" // tmp135a + tmp135b * 8 //--------------------------------------------- "vse.v v24, (a0)\n\t" "vfmacc.vf v26, fa2, v12\n\t" // tmp024a + tmp024b * 4 + tmp024c * 8 = tmp[2][m] "vfmacc.vf v28, fa0, v12\n\t" // tmp024a + tmp024b * 16 + tmp024c + tmp024c = tmp[4][m] "vfmacc.vf v15, fa4, v11\n\t" // tmp135b * 32 + tmp135c "vse.v v26, (a2)\n\t" "vse.v v28, (a4)\n\t" //--------------------------------------------- "vfmacc.vf v25, fa3, v13\n\t" // tmp135a + tmp135b * 2 + tmp135c * 16 = tmp[1][m] "vfmacc.vf v27, fa1, v13\n\t" // tmp135a + tmp135b * 8 + tmp135c * 4 = tmp[3][m] "vfadd.vv v29, v7, v15\n\t" // r07 + tmp135a + tmp135b * 32 + tmp135c "vse.v v25, (a1)\n\t" "vse.v v27, (a3)\n\t" "vse.v v29, (a5)\n\t" "addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1] "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "2:\n\t" "mv t5, %2\n\t" // tmp start addr "li t0, 6\n\t" // m = 6 "slli t1, %5, 4\n\t" // t1 = out_w6 * 8 * 2bytes "vle.v v16, (%6)\n\t" // load 8 channel bias data "3:\n\t" // shape : [6 * 8] * [6 * 8] = [6 * 6] "mv a0, %1\n\t" "addi a1, a0, 16\n\t" "addi a2, a1, 16\n\t" "addi a3, a2, 16\n\t" "addi a4, a3, 16\n\t" "addi a5, a4, 16\n\t" "vle.v v0, (t5)\n\t" // tmp[m][0] "addi t5, t5, 16\n\t" "vle.v v1, (t5)\n\t" // tmp[m][1] "addi t5, t5, 16\n\t" "vle.v v2, (t5)\n\t" // tmp[m][2] "addi t5, t5, 16\n\t" "vle.v v3, (t5)\n\t" // tmp[m][3] "addi t5, t5, 16\n\t" "vle.v v4, (t5)\n\t" // tmp[m][4] "addi t5, t5, 16\n\t" "vle.v v5, (t5)\n\t" // tmp[m][5] "addi t5, t5, 16\n\t" "vle.v v6, (t5)\n\t" // tmp[m][6] "addi t5, t5, 16\n\t" "vle.v v7, (t5)\n\t" // tmp[m][7] "addi t5, t5, 16\n\t" //--------------------------------------------- "vfadd.vv v8, v1, v2\n\t" // tmp[m][1] + tmp[m][2] = tmp024a "vfsub.vv v9, v1, v2\n\t" // tmp[m][1] - tmp[m][2] = tmp135a "vfadd.vv v10, v3, v4\n\t" // tmp[m][3] + tmp[m][4] = tmp024b "vfsub.vv v11, v3, v4\n\t" // tmp[m][3] - tmp[m][4] = tmp135b "vfadd.vv v12, v5, v6\n\t" // tmp[m][5] + tmp[m][6] = tmp024c "vfsub.vv v13, v5, v6\n\t" // tmp[m][5] - tmp[m][6] = tmp135c "vfadd.vv v0, v0, v8\n\t" // tmp[m][0] + tmp024a "vfadd.vv v7, v7, v9\n\t" // tmp[m][7] + tmp135a "vmv.v.v v14, v10\n\t" // v14 = tmp024b "vmv.v.v v26, v8\n\t" // v26 = tmp024a "vmv.v.v v28, v8\n\t" // v28 = tmp024a "vfmacc.vf v26, fa1, v10\n\t" // tmp024a + tmp024b * 4 "vfmacc.vf v14, fa4, v12\n\t" // tmp024b + tmp024c * 32 "vfmacc.vf v28, fa3, v10\n\t" // tmp024a + tmp024b * 16 "vmv.v.v v15, v13\n\t" // v15 = tmp135c "vmv.v.v v25, v9\n\t" // v25 = tmp135a "vmv.v.v v27, v9\n\t" // v27 = tmp135a "vfadd.vv v24, v0, v14\n\t" // tmp[m][0] + tmp024a + tmp024b + tmp024c * 32 = tmp[0][m] "vfmacc.vf v25, fa0, v11\n\t" // tmp135a + tmp135b * 2 "vfmacc.vf v27, fa2, v11\n\t" // tmp135a + tmp135b * 8 //--------------------------------------------- "vfadd.vv v24, v24, v16\n\t" // + bias "vfmacc.vf v26, fa2, v12\n\t" // tmp024a + tmp024b * 4 + tmp024c * 8 = tmp[2][m] "vfmacc.vf v28, fa0, v12\n\t" // tmp024a + tmp024b * 16 + tmp024c + tmp024c = tmp[4][m] "vfmacc.vf v15, fa4, v11\n\t" // tmp135b * 32 + tmp135c "vse.v v24, (a0)\n\t" "vfmacc.vf v25, fa3, v13\n\t" // tmp135a + tmp135b * 2 + tmp135c * 16 = tmp[1][m] "vfmacc.vf v27, fa1, v13\n\t" // tmp135a + tmp135b * 8 + tmp135c * 4 = tmp[3][m] "vfadd.vv v26, v26, v16\n\t" // + bias "vfadd.vv v28, v28, v16\n\t" // + bias "vfadd.vv v29, v7, v15\n\t" // tmp[m][7] + tmp135a + tmp135b * 32 + tmp135c "vse.v v26, (a2)\n\t" "vse.v v28, (a4)\n\t" //--------------------------------------------- "vfadd.vv v25, v25, v16\n\t" // + bias "vfadd.vv v27, v27, v16\n\t" // + bias "vfadd.vv v29, v29, v16\n\t" // + bias "vse.v v25, (a1)\n\t" "vse.v v27, (a3)\n\t" "vse.v v29, (a5)\n\t" "add %1, %1, t1\n\t" "addi t0, t0, -1\n\t" "bnez t0, 3b" :"=r"(output0_tm_0), // %0 "=r"(output0), // %1 "=r"(tmp1), // %2 "=r"(ratio_ptr), // %3 "=r"(tiles), // %4 "=r"(out_w6), // %5 "=r"(bias_tmp) // %6 :"0"(output0_tm_0), "1"(output0), "2"(tmp1), "3"(ratio_ptr), "4"(tiles), "5"(out_w6), "6"(bias_tmp) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v24", "v25", "v26", "v27", "v28", "v29", "t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "fa0", "fa1", "fa2", "fa3", "fa4" ); } } csi_mem_free(tmp1); } csi_mem_free(output_dot_buf); // crop the output after transform: cut extra part (right , bottom) csi_c906_crop_output_pack8to1_fp16(output_tm1_buf, output_data, out_c, out_h, out_w, block_h * 6, block_w * 6); output_data += output_size; csi_mem_free(output_tm1_buf); } if (!flag_bias) { csi_mem_free(bias_data); bias_data = NULL; } return CSINN_TRUE; } void csi_c906_conv3x3s1_winograd43_transform_kernel_pack8_fp16(struct csi_tensor *o_kernel, struct csi_tensor *t_kernel) { int32_t outch = o_kernel->dim[0]; int32_t inch = o_kernel->dim[1]; __fp16 *kernel_data = (__fp16 *)o_kernel->data; // for kernel transform buf, 3x3 --> 6x6 __fp16 *kernel_tm = (__fp16 *)csi_mem_alloc(outch * inch * 6 * 6 * sizeof(__fp16)); // kernel transform matrix: G const __fp16 ktm[6][3] = { { 1.0f/4, 0.0f, 0.0f}, { -1.0f/6, -1.0f/6, -1.0f/6}, { -1.0f/6, 1.0f/6, -1.0f/6}, { 1.0f/24, 1.0f/12, 1.0f/6}, { 1.0f/24, -1.0f/12, 1.0f/6}, { 0.0f, 0.0f, 1.0f} }; csi_tensor_copy(t_kernel, o_kernel); for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const __fp16* kernel0 = kernel_data + p * inch * 9 + q * 9; __fp16* kernel_tm0 = kernel_tm + p * inch * 36 + q * 36; // transform kernel const __fp16 *k0 = kernel0; const __fp16 *k1 = kernel0 + 3; const __fp16 *k2 = kernel0 + 6; // h : first compute the transport matrix tmp = (g * GT)T __fp16 tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { __fp16* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // [O, I, 6, 6] --> [O/4, 6*6, I, 4] __fp16 *kernel_tm_pack4 = (__fp16 *)csi_mem_alloc(outch * inch * 6 * 6 * sizeof(__fp16)); t_kernel->data = kernel_tm_pack4; for (int oc = 0; oc < outch / 8; oc++) { __fp16 *g0 = kernel_tm_pack4 + oc * 36 * inch * 8; const __fp16 *k0 = kernel_tm + oc * 36 * inch * 8; const __fp16 *k1 = k0 + 36 * inch; const __fp16 *k2 = k1 + 36 * inch; const __fp16 *k3 = k2 + 36 * inch; const __fp16 *k4 = k3 + 36 * inch; const __fp16 *k5 = k4 + 36 * inch; const __fp16 *k6 = k5 + 36 * inch; const __fp16 *k7 = k6 + 36 * inch; for (int k = 0; k < 36; k++) { __fp16 *g00 = g0 + k * inch * 8; for (int ic = 0; ic < inch / 8; ic++) { for (int i = 0; i < 8; i++) { const __fp16 *k00 = k0 + (ic * 8 + i) * 36; const __fp16 *k10 = k1 + (ic * 8 + i) * 36; const __fp16 *k20 = k2 + (ic * 8 + i) * 36; const __fp16 *k30 = k3 + (ic * 8 + i) * 36; const __fp16 *k40 = k4 + (ic * 8 + i) * 36; const __fp16 *k50 = k5 + (ic * 8 + i) * 36; const __fp16 *k60 = k6 + (ic * 8 + i) * 36; const __fp16 *k70 = k7 + (ic * 8 + i) * 36; g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k40[k]; g00[5] = k50[k]; g00[6] = k60[k]; g00[7] = k70[k]; g00 += 8; } } } } csi_mem_free(kernel_tm); } int csi_c906_conv3x3s1_winograd43_pack8_fp16(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { __fp16 *input_data = (__fp16 *)input->data; __fp16 *output_data = (__fp16 *)output->data; __fp16 *kernel_data = (__fp16 *)params->conv_extra.kernel_tm->data; __fp16 *bias_data = (__fp16 *)bias->data; // param int kernel_h = kernel->dim[2]; int kernel_w = kernel->dim[3]; int stride_h = params->stride_height; int stride_w = params->stride_width; int dilation_h = params->dilation_height; int dilation_w = params->dilation_width; int pad_left = params->pad_left; int pad_top = params->pad_top; int batch = input->dim[0]; int in_c = input->dim[1]; int in_h = input->dim[2]; int in_w = input->dim[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int out_c = kernel->dim[0]; int out_h = output->dim[2]; int out_w = output->dim[3]; int output_size = out_c * out_h * out_w; // winograd param int block_h = (out_h + 3) / 4; int block_w = (out_w + 3) / 4; int padded_in_h = block_h * 4 + 2; // block * 4 for alignment with 4,kernel = 3 * 3, stride = 1,thus input_size + 2 int padded_in_w = block_w * 4 + 2; int padded_in_hw = padded_in_h * padded_in_w; // element size after padding per channel /****************************** bias *****************************/ bool flag_bias = 1; // default: conv2d layer include bias if (bias_data == NULL) { flag_bias = 0; bias_data = (__fp16 *)csi_mem_alloc(out_c * sizeof(__fp16)); } for(int n = 0; n < batch; n++) { // pad buffer: [in_c/4 h w 4] __fp16 *input_padd_buf = (__fp16 *)csi_mem_alloc(in_c * padded_in_hw * sizeof(__fp16)); // pad input csi_c906_pad_input_pack1to8_fp16(input_data, input_padd_buf, in_c, in_h, in_w, padded_in_h, padded_in_w, pad_top, pad_left); input_data += input_size; // input transform buffer1: [in_ch/4, 36, blocks, 6] __fp16 *input_tm1_buf = (__fp16 *)csi_mem_alloc(in_c * block_h * block_w * 6 * 6 * sizeof(__fp16)); /****************************** transform input *****************************/ /* BT = { { 4 0 -5 0 1 0 }; { 0 -4 -4 1 1 0 }; { 0 4 -4 -1 1 0 }; { 0 -2 -1 2 1 0 }; { 0 2 -1 -2 1 0 }; { 0 4 0 -5 0 1 } }; */ int tiles = block_h * block_w; #pragma omp parallel for num_threads(1) for(int q = 0; q < in_c / 4; q++) { __fp16 *img0 = input_padd_buf + q * padded_in_h * padded_in_w * 8; // feature map after padding - q channel __fp16 *img0_tm = input_tm1_buf + q * 36 * tiles * 8; // transform and interleave - q channel __fp16 *tmp = (__fp16 *)csi_mem_alloc(6 * 6 * 8 * sizeof(__fp16)); for(int i = 0; i < block_h; i++) { for(int j = 0; j < block_w; j++) { __fp16 *r0 = img0 + (i * padded_in_w * 4 + j * 4) * 8; // feature map after padding 6*6 start addr __fp16 *r0_tm = img0_tm + (i * block_w + j) * 8; // input_tm1 6*6 block start addr __fp16 ratio[] = {4, -4, 2, -2, -5}; // note: in fact cannot be output constrain __fp16 *ratio_ptr = ratio; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "li t0, 6\n\t" // m = 6 "mv t5, %2\n\t" // t5 = tmp start addr "slli t1, %4, 4\n\t" // t1 = padded_in_w * 8 * 2 bytes "flh fa0, 0(%3)\n\t" // fa0 = 4 "flh fa1, 2(%3)\n\t" // fa1 = -4 "flh fa2, 4(%3)\n\t" // fa2 = 2 "flh fa3, 6(%3)\n\t" // fa3 = -2 "flh fa4, 8(%3)\n\t" // fa4 = -5 "1:\n\t" "mv s1, %0\n\t" // s1 = r00 addr "mv a0, t5\n\t" // tmp[0][m] "addi a1, a0, 96\n\t" // tmp[1][m] "addi a2, a1, 96\n\t" // tmp[2][m] "addi a3, a2, 96\n\t" // tmp[3][m] "addi a4, a3, 96\n\t" // tmp[4][m] "addi a5, a4, 96\n\t" // tmp[5][m] "vle.v v0, (s1)\n\t" // r00 "addi s1, s1, 16\n\t" "vle.v v1, (s1)\n\t" // r01 "addi s1, s1, 16\n\t" "vle.v v2, (s1)\n\t" // r02 "addi s1, s1, 16\n\t" "vle.v v3, (s1)\n\t" // r03 "addi s1, s1, 16\n\t" "vle.v v4, (s1)\n\t" // r04 "addi s1, s1, 16\n\t" "vle.v v5, (s1)\n\t" // r05 "addi s1, s1, 16\n\t" "vmv.v.v v24, v4\n\t" "vmv.v.v v29, v5\n\t" //--------------------------------------------- "vfmacc.vf v24, fa0, v0\n\t" // r04 + 4 * r00 "vfmacc.vf v24, fa4, v2\n\t" // r04 + 4 * r00 - 5 * r02 "vse.v v24, (a0)\n\t" //--------------------------------------------- "vfadd.vv v25, v3, v4\n\t" // r03 + r04 "vfadd.vv v6, v1, v2\n\t" // r01 + r02 "vfmacc.vf v25, fa1, v6\n\t" // r03 + r04 - 4 * (r01 - r02) "vse.v v25, (a1)\n\t" //--------------------------------------------- "vfsub.vv v26, v4, v3\n\t" // r04 - r03 "vfsub.vv v7, v1, v2\n\t" // r01 - r02 "vfmacc.vf v26, fa0, v7\n\t" // r04 - r03 + 4 * (r01 - r02) "vse.v v26, (a2)\n\t" //--------------------------------------------- "vfsub.vv v8, v1, v3\n\t" // r01 - r03 "vfsub.vv v27, v4, v2\n\t" // r04 - r02 "vfsub.vv v28, v4, v2\n\t" // r04 - r02 "vfmacc.vf v27, fa3, v8\n\t" // r04 - r02 - 2 * (r01 - r03) "vse.v v27, (a3)\n\t" "vfmacc.vf v28, fa2, v8\n\t" // r04 - r02 + 2 * (r01 - r03) "vse.v v28, (a4)\n\t" //--------------------------------------------- "vfmacc.vf v29, fa0, v1\n\t" // r05 + 4 * r01 "vfmacc.vf v29, fa4, v3\n\t" // r05 + 4 * r01 - 5 * r03 "vse.v v29, (a5)\n\t" //--------------------------------------------- "add %0, %0, t1\n\t" // padding feature map 6*6 next line addr "addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1] "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "2:\n\t" "mv t5, %2\n\t" // tmp start addr "li t0, 6\n\t" // m = 6 "slli t1, %5, 4\n\t" // t1 = tiles * 8 * 2 bytes "mulw t2, t0, t1\n\t" // t2 = tiles * 6 blocks * 8 channels * 2 bytes "3:\n\t" "mv a0, %1\n\t" // r0_tm_0 "add a1, a0, t1\n\t" // r0_tm_1 "add a2, a1, t1\n\t" // r0_tm_2 "add a3, a2, t1\n\t" // r0_tm_3 "add a4, a3, t1\n\t" // r0_tm_4 "add a5, a4, t1\n\t" // r0_tm_5 "vle.v v0, (t5)\n\t" // tmp[m][0] "addi t5, t5, 16\n\t" "vle.v v1, (t5)\n\t" // tmp[m][1] "addi t5, t5, 16\n\t" "vle.v v2, (t5)\n\t" // tmp[m][2] "addi t5, t5, 16\n\t" "vle.v v3, (t5)\n\t" // tmp[m][3] "addi t5, t5, 16\n\t" "vle.v v4, (t5)\n\t" // tmp[m][4] "addi t5, t5, 16\n\t" "vle.v v5, (t5)\n\t" // tmp[m][5] "addi t5, t5, 16\n\t" "vmv.v.v v24, v4\n\t" "vmv.v.v v29, v5\n\t" //--------------------------------------------- "vfmacc.vf v24, fa0, v0\n\t" // r04 + 4 * r00 "vfmacc.vf v24, fa4, v2\n\t" // r04 * 4 * r00 - 5 * r02 "vse.v v24, (a0)\n\t" //--------------------------------------------- "vfadd.vv v25, v3, v4\n\t" // r03 + r04 "vfadd.vv v6, v1, v2\n\t" // r01 + r02 "vfmacc.vf v25, fa1, v6\n\t" // r03 + r04 - 4 * (r01 - r02) "vse.v v25, (a1)\n\t" //--------------------------------------------- "vfsub.vv v26, v4, v3\n\t" // r04 - r03 "vfsub.vv v7, v1, v2\n\t" // r01 - r02 "vfmacc.vf v26, fa0, v7\n\t" // r04 - r03 + 4 * (r01 - r02) "vse.v v26, (a2)\n\t" //--------------------------------------------- "vfsub.vv v8, v1, v3\n\t" // r01 - r03 "vfsub.vv v27, v4, v2\n\t" // r04 - r02 "vfsub.vv v28, v4, v2\n\t" // r04 - r02 "vfmacc.vf v27, fa3, v8\n\t" // r04 - r02 - 2 * (r01 - r03) "vse.v v27, (a3)\n\t" "vfmacc.vf v28, fa2, v8\n\t" // r04 - r02 + 2 * (r01 - r03) "vse.v v28, (a4)\n\t" //--------------------------------------------- "vfmacc.vf v29, fa0, v1\n\t" // r05 + 4 * r01 "vfmacc.vf v29, fa4, v3\n\t" // r05 + 4 * r01 - 5 * r03 "vse.v v29, (a5)\n\t" //--------------------------------------------- "add %1, %1, t2\n\t" "addi t0, t0, -1\n\t" "bnez t0, 3b" :"=r"(r0), // %0 "=r"(r0_tm), // %1 "=r"(tmp), // %2 "=r"(ratio_ptr), // %3 "=r"(padded_in_w), // %4 "=r"(tiles) // %5 :"0"(r0), "1"(r0_tm), "2"(tmp), "3"(ratio_ptr), "4"(padded_in_w), "5"(tiles) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v24", "v25", "v26", "v27", "v28", "v29", "t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5" ); } } csi_mem_free(tmp); } csi_mem_free(input_padd_buf); /*********************************** dot ***************************************/ // reorder input_tm1_buf __fp16 *input_tm2_buf = (__fp16 *)csi_mem_alloc(36 * tiles * in_c * sizeof(__fp16)); #pragma omp parallel for num_threads(1) for (int r = 0; r < 36; r++) { __fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // input_tm2 r channel data int t = 0; for (; t + 7 < tiles; t += 8) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; //----------------- for (int q = 0; q < in_c / 8; q++) { for (int l = 0; l < 8; l++) { tm2[0] = tm1[l]; tm2[1] = tm1[l + 8 * 1]; tm2[2] = tm1[l + 8 * 2]; tm2[3] = tm1[l + 8 * 3]; tm2[4] = tm1[l + 8 * 4]; tm2[5] = tm1[l + 8 * 5]; tm2[6] = tm1[l + 8 * 6]; tm2[7] = tm1[l + 8 * 7]; tm2 += 8; } tm1 += 36 * tiles * 8; } } for (; t + 3 < tiles; t += 4) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; for (int q = 0; q < in_c / 8; q++) { for (int l = 0; l < 8; l++) { tm2[0] = tm1[l]; tm2[1] = tm1[l + 8 * 1]; tm2[2] = tm1[l + 8 * 2]; tm2[3] = tm1[l + 8 * 3]; tm2 += 4; } tm1 += 36 * tiles * 8; } } for (; t + 1 < tiles; t += 2) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; for (int q = 0; q < in_c / 8; q++) { for (int l = 0; l < 8; l++) { tm2[0] = tm1[l]; tm2[1] = tm1[l + 8]; tm2 += 2; } tm1 += 36 * tiles * 8; } } for (; t < tiles; t++) { __fp16 *tm2 = img_tm2 + t * in_c; // img_tm2 row data __fp16 *tm1 = input_tm1_buf; tm1 += (r * tiles + t) * 8; for (int q = 0; q < in_c / 8; q++) { for (int l = 0; l < 8; l++) { tm2[0] = tm1[l]; tm2++; } tm1 += 36 * tiles * 8; } } } csi_mem_free(input_tm1_buf); // output_dot_buf: [out_c/4, 36, blocks, 4] __fp16 *output_dot_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 6 * 6 * sizeof(__fp16)); #pragma omp parallel for num_threads(1) for (int p = 0; p < out_c / 8; p++) { __fp16 *output0_tm = output_dot_buf + p * 36 * tiles * 8; // 8 channel dot output __fp16 *kernel0_tm = kernel_data + p * 36 * in_c * 8; // 8 channel kernel for (int r = 0; r < 36; r++) { __fp16 *img_tm2 = input_tm2_buf + r * tiles * in_c; // img_tm2 第r个channel int t = 0; for (; t + 7 < tiles; t += 8) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" "vmv.v.x v2, zero\n\t" "vmv.v.x v3, zero\n\t" "vmv.v.x v4, zero\n\t" "vmv.v.x v5, zero\n\t" "vmv.v.x v6, zero\n\t" "vmv.v.x v7, zero\n\t" // clear "1:\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "flh fa2, 4(%0)\n\t" "flh fa3, 6(%0)\n\t" "flh fa4, 8(%0)\n\t" "flh fa5, 10(%0)\n\t" "flh fa6, 12(%0)\n\t" "flh fa7, 14(%0)\n\t" "addi %0, %0, 16\n\t" "vle.v v8, (%1)\n\t" "addi %1, %1, 16\n\t" "vfmacc.vf v0, fa0, v8\n\t" "vfmacc.vf v1, fa1, v8\n\t" "vfmacc.vf v2, fa2, v8\n\t" "vfmacc.vf v3, fa3, v8\n\t" "vfmacc.vf v4, fa4, v8\n\t" "vfmacc.vf v5, fa5, v8\n\t" "vfmacc.vf v6, fa6, v8\n\t" "vfmacc.vf v7, fa7, v8\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v2, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v3, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v4, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v5, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v6, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v7, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "t0" ); } for (; t + 3 < tiles; t += 4) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" "vmv.v.x v2, zero\n\t" "vmv.v.x v3, zero\n\t" // clear "1:\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "flh fa2, 4(%0)\n\t" "flh fa3, 6(%0)\n\t" "addi %0, %0, 8\n\t" "vle.v v4, (%1)\n\t" "addi %1, %1, 16\n\t" "vfmacc.vf v0, fa0, v4\n\t" "vfmacc.vf v1, fa1, v4\n\t" "vfmacc.vf v2, fa2, v4\n\t" "vfmacc.vf v3, fa3, v4\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v2, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v3, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "fa0", "fa1", "fa2", "fa3", "t0" ); } for (; t + 1 < tiles; t += 2) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" "vmv.v.x v1, zero\n\t" // clear "1:\n\t" "flh fa0, (%0)\n\t" "flh fa1, 2(%0)\n\t" "addi %0, %0, 4\n\t" "vle.v v2, (%1)\n\t" "addi %1, %1, 16\n\t" "vfmacc.vf v0, fa0, v2\n\t" "vfmacc.vf v1, fa1, v2\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" "vse.v v1, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "v2", "fa0", "fa1", "t0" ); } for (; t < tiles; t++) { __fp16 *r0 = img_tm2 + t * in_c; __fp16 *k0 = kernel0_tm + r * in_c * 8; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "mv t0, %3\n\t" // t0 = in_c "vmv.v.x v0, zero\n\t" // clear "1:\n\t" "flw fa0, (%0)\n\t" "addi %0, %0, 2\n\t" "vle.v v1, (%1)\n\t" "addi %1, %1, 16\n\t" "vfmacc.vf v0, fa0, v1\n\t" "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "vse.v v0, (%2)\n\t" "addi %2, %2, 16\n\t" :"=r"(r0), // %0 "=r"(k0), // %1 "=r"(output0_tm), // %2 "=r"(in_c) // %3 :"0"(r0), "1"(k0), "2"(output0_tm), "3"(in_c) :"cc", "memory", "v0", "v1", "fa0", "t0" ); } } } csi_mem_free(input_tm2_buf); /*************************** transform output ****************************/ // output_tm1_buf: [out_c/4, out_h4, out_w4, 4] __fp16 *output_tm1_buf = (__fp16 *)csi_mem_alloc(out_c * block_h * block_w * 4 * 4 * sizeof(__fp16)); /* AT = { { 1 1 1 1 1 0 }, { 0 1 -1 2 -2 0 }, { 0 1 1 4 4 0 }, { 0 1 -1 8 -8 1 } }; */ #pragma omp parallel for num_threads(1) for (int p = 0; p < out_c / 8; p++) { __fp16 *bias_tmp = bias_data + p * 8; __fp16 *out0_tm = output_dot_buf + p * 36 * block_h * block_w * 8; // 输出转换前/dot后 第p个channel __fp16 *out0 = output_tm1_buf + p * 4*block_h * 4*block_w * 8; // 转换后输出 第p个channel __fp16 *tmp1 = (__fp16 *)csi_mem_alloc(4 * 6 * 8 * sizeof(__fp16)); int out_w4 = block_w * 4; for (int i = 0; i < block_h; i++) { for (int j = 0; j < block_w; j++) { __fp16 *output0_tm_0 = out0_tm + (i * block_w + j) * 8; // 6*6 起始地址 __fp16 *output0 = out0 + (i * block_w * 4 * 4 + j * 4) * 8; // 输出 4*4 的起始地址 __fp16 ratio[] = {2.0, 4.0, 8.0}; __fp16 *ratio_ptr = ratio; asm volatile( "vsetvli zero, zero, e16, m1\n\t" "li t0, 6\n\t" // m = 6 "mv t5, %2\n\t" // t5 = tmp start addr "slli t1, %4, 4\n\t" // t1 = tiles * 8 * 2 "mulw t2, t0, t1\n\t" // t2 = tiles * 6 blocks * 8 channels * 2 bytes "flh fa0, 0(%3)\n\t" // fa0 = 2 "flh fa1, 2(%3)\n\t" // fa1 = 4 "flh fa2, 4(%3)\n\t" // fa2 = 8 "mv s1, %0\n\t" "1:\n\t" // shape : [4 * 6] * [6 * 6] = [4 * 6] "mv a0, t5\n\t" // tmp[0][m] "addi a1, a0, 96\n\t" // tmp[1][m] "addi a2, a1, 96\n\t" // tmp[2][m] "addi a3, a2, 96\n\t" // tmp[3][m] "vle.v v0, (s1)\n\t" // r00 "add s1, s1, t1\n\t" "vle.v v1, (s1)\n\t" // r01 "add s1, s1, t1\n\t" "vle.v v2, (s1)\n\t" // r02 "add s1, s1, t1\n\t" "vle.v v3, (s1)\n\t" // r03 "add s1, s1, t1\n\t" "vle.v v4, (s1)\n\t" // r04 "add s1, s1, t1\n\t" "vle.v v5, (s1)\n\t" // r05 "add s1, s1, t1\n\t" //--------------------------------------------- "vfadd.vv v26, v1, v2\n\t" // r01 + r02 = tmp02a "vfsub.vv v6, v1, v2\n\t" // r01 - r02 = tmp13a "vfadd.vv v7, v3, v4\n\t" // r03 + r04 = tmp02b "vfsub.vv v8, v3, v4\n\t" // r03 - r04 = tmp13b "vmv.v.v v25, v6\n\t" // v25 = tmp13a //--------------------------------------------- "vfadd.vv v24, v0, v26\n\t" // r00 + tmp02a "vfadd.vv v24, v24, v7\n\t" // r00 + tmp02a + tmp02b "vse.v v24, (a0)\n\t" "vfmacc.vf v25, fa0, v8\n\t" // tmp13a + 2 * tmp13b "vse.v v25, (a1)\n\t" "vfmacc.vf v26, fa1, v7\n\t" // tmp02a + 4 * tmp02b "vse.v v26, (a2)\n\t" "vfadd.vv v27, v5, v6\n\t" // r05 + tmp13a "vfmacc.vf v27, fa2, v8\n\t" // r05 + tmp13a * 8 tmp13b "vse.v v27, (a3)\n\t" //--------------------------------------------- "addi t5, t5, 16\n\t" // tmp[0][0] --> tmp[0][1] "addi t0, t0, -1\n\t" "bnez t0, 1b\n\t" "2:\n\t" "mv t5, %2\n\t" // tmp start addr "li t0, 4\n\t" // m = 4 "slli t1, %5, 4\n\t" // t1 = out_w4 * 8 * 2 bytes "vle.v v16, (%6)\n\t" // load 8 channel bias data "3:\n\t" // shape : [4 * 6] * [6 * 4] = [4 * 4] "mv a0, %1\n\t" "addi a1, a0, 16\n\t" "addi a2, a1, 16\n\t" "addi a3, a2, 16\n\t" "vle.v v0, (t5)\n\t" // tmp[m][0] "addi t5, t5, 16\n\t" "vle.v v1, (t5)\n\t" // tmp[m][1] "addi t5, t5, 16\n\t" "vle.v v2, (t5)\n\t" // tmp[m][2] "addi t5, t5, 16\n\t" "vle.v v3, (t5)\n\t" // tmp[m][3] "addi t5, t5, 16\n\t" "vle.v v4, (t5)\n\t" // tmp[m][4] "addi t5, t5, 16\n\t" "vle.v v5, (t5)\n\t" // tmp[m][5] "addi t5, t5, 16\n\t" //--------------------------------------------- "vfadd.vv v26, v1, v2\n\t" // r01 + r02 = tmp02a "vfsub.vv v6, v1, v2\n\t" // r01 - r02 = tmp13a "vfadd.vv v7, v3, v4\n\t" // r03 + r04 = tmp02b "vfsub.vv v8, v3, v4\n\t" // r03 - r04 = tmp13b "vmv.v.v v25, v6\n\t" // v25 = tmp13a //--------------------------------------------- "vfadd.vv v24, v0, v26\n\t" // r00 + tmp02a "vfadd.vv v24, v24, v7\n\t" // r00 + tmp02a + tmp02b "vfadd.vv v24, v24, v16\n\t" // add bias "vse.v v24, (a0)\n\t" "vfmacc.vf v25, fa0, v8\n\t" // tmp13a + 2 * tmp13b "vfadd.vv v25, v25, v16\n\t" // add bias "vse.v v25, (a1)\n\t" "vfmacc.vf v26, fa1, v7\n\t" // tmp02a + 4 * tmp02b "vfadd.vv v26, v26, v16\n\t" // add bias "vse.v v26, (a2)\n\t" "vfadd.vv v27, v5, v6\n\t" // r05 + tmp13a "vfmacc.vf v27, fa2, v8\n\t" // r05 + tmp13a * 8 tmp13b "vfadd.vv v27, v27, v16\n\t" // add bias "vse.v v27, (a3)\n\t" "add %1, %1, t1\n\t" "addi t0, t0, -1\n\t" "bnez t0, 3b" :"=r"(output0_tm_0), // %0 "=r"(output0), // %1 "=r"(tmp1), // %2 "=r"(ratio_ptr), // %3 "=r"(tiles), // %4 "=r"(out_w4), // %5 "=r"(bias_tmp) // %6 :"0"(output0_tm_0), "1"(output0), "2"(tmp1), "3"(ratio_ptr), "4"(tiles), "5"(out_w4), "6"(bias_tmp) :"cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v16", "v24", "v25", "v26", "v27", "t0", "t1", "t2", "t5", "s1", "a0", "a1", "a2", "a3", "fa0", "fa1", "fa2" ); } } csi_mem_free(tmp1); } csi_mem_free(output_dot_buf); // crop the output after transform: cut extra part (right , bottom) csi_c906_crop_output_pack8to1_fp16(output_tm1_buf, output_data, out_c, out_h, out_w, block_h * 4, block_w * 4); output_data += output_size; csi_mem_free(output_tm1_buf); } if (!flag_bias) { csi_mem_free(bias_data); bias_data = NULL; } return CSINN_TRUE; } void csi_c906_conv3x3s1_fp16(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { /* to do */ } void csi_c906_conv3x3s2_fp16(struct csi_tensor *input, struct csi_tensor *output, struct csi_tensor *kernel, struct csi_tensor *bias, struct conv2d_params *params) { /* to do */ }
HDF5Dumper_MPI.h
/* * HDF5Dumper_MPI.h * Cubism * * Created by Babak Hejazialhosseini on 5/24/09. * Copyright 2009 CSE Lab, ETH Zurich. All rights reserved. * */ #pragma once #include <cassert> #include <cstdio> #include <iostream> #include <vector> #include <string> #include <sstream> #include <mpi.h> #include "HDF5Dumper.h" CUBISM_NAMESPACE_BEGIN // The following requirements for the data TStreamer are required: // TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor) // TStreamer::operate : Data access methods for read and write // TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor") template<typename TStreamer, typename hdf5Real, typename TGrid> void DumpHDF5_MPI(const TGrid &grid, const typename TGrid::Real absTime, const std::string &fileroot, // Filename without folder or extension. const std::string &dirname = ".", const bool bXMF = true) { #ifdef CUBISM_USE_HDF typedef typename TGrid::BlockType B; std::string filename_h5 = fileroot + ".h5"; std::string fullpath_h5 = dirname + "/" + filename_h5; std::string fullpath_xmf = dirname + "/" + fileroot + ".xmf"; int rank; MPI_Comm comm = grid.getCartComm(); MPI_Comm_rank(comm, &rank); int coords[3]; grid.peindex(coords); herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; /////////////////////////////////////////////////////////////////////////// // write mesh std::vector<int> mesh_dims; std::vector<std::string> dset_name; dset_name.push_back("/vx"); dset_name.push_back("/vy"); dset_name.push_back("/vz"); if (0 == rank) { H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); file_id = H5Fcreate(fullpath_h5.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl_id); status = H5Pclose(fapl_id); for (size_t i = 0; i < 3; ++i) { const MeshMap<B>& m = grid.getMeshMap(i); std::vector<double> vertices(m.ncells()+1, m.start()); mesh_dims.push_back(vertices.size()); for (size_t j = 0; j < m.ncells(); ++j) vertices[j+1] = vertices[j] + m.cell_width(j); hsize_t dim[1] = {vertices.size()}; fspace_id = H5Screate_simple(1, dim, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices.data()); status = H5Sclose(fspace_id); status = H5Dclose(dataset_id); } // shutdown h5 file status = H5Fclose(file_id); H5close(); } MPI_Barrier(comm); /////////////////////////////////////////////////////////////////////////// // startup file H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); status = H5Pset_fapl_mpio(fapl_id, comm, MPI_INFO_NULL); if(status<0) H5Eprint1(stdout); file_id = H5Fopen(fullpath_h5.c_str(), H5F_ACC_RDWR, fapl_id); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); /////////////////////////////////////////////////////////////////////////// // write data const unsigned int NX = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(0))*B::sizeX; const unsigned int NY = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(1))*B::sizeY; const unsigned int NZ = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(2))*B::sizeZ; const unsigned int NCHANNELS = TStreamer::NCHANNELS; if (rank==0) { std::cout << "Allocating " << (NX * NY * NZ * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.*1024.) << " GB of HDF5 data"; } hdf5Real * array_all = new hdf5Real[NX * NY * NZ * NCHANNELS]; std::vector<BlockInfo> vInfo_local = grid.getResidentBlocksInfo(); hsize_t count[4] = {NZ, NY, NX, NCHANNELS}; hsize_t dims[4] = { static_cast<unsigned int>(grid.getBlocksPerDimension(2))*B::sizeZ, static_cast<unsigned int>(grid.getBlocksPerDimension(1))*B::sizeY, static_cast<unsigned int>(grid.getBlocksPerDimension(0))*B::sizeX, NCHANNELS}; if (rank==0) { std::cout << " (Total " << (dims[0] * dims[1] * dims[2] * dims[3] * sizeof(hdf5Real))/(1024.*1024.*1024.) << " GB)" << std::endl; } hsize_t offset[4] = { static_cast<unsigned int>(coords[2]) * NZ, static_cast<unsigned int>(coords[1]) * NY, static_cast<unsigned int>(coords[0]) * NX, 0 }; #pragma omp parallel for for(size_t i=0; i<vInfo_local.size(); i++) { BlockInfo& info = vInfo_local[i]; const int idx[3] = {info.index[0], info.index[1], info.index[2]}; B & b = *(B*)info.ptrBlock; for(int iz=0; iz<static_cast<int>(B::sizeZ); iz++) { const int gz = idx[2]*B::sizeZ + iz; for(int iy=0; iy<static_cast<int>(B::sizeY); iy++) { const int gy = idx[1]*B::sizeY + iy; for(int ix=0; ix<static_cast<int>(B::sizeX); ix++) { const int gx = idx[0]*B::sizeX + ix; const ptrdiff_t idl = NCHANNELS * (gx + NX * (gy + NY * gz)); assert(idl < NX * NY * NZ * NCHANNELS); hdf5Real * const ptr = array_all + idl; hdf5Real output[NCHANNELS]; for(unsigned k=0; k<NCHANNELS; ++k) output[k] = 0; TStreamer::operate(b, ix, iy, iz, (hdf5Real*)output); for(unsigned k=0; k<NCHANNELS; ++k) ptr[k] = output[k]; } } } } fapl_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(fapl_id, H5FD_MPIO_COLLECTIVE); fspace_id = H5Screate_simple(4, dims, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif fspace_id = H5Dget_space(dataset_id); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); status = H5Dwrite(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all); if (status < 0) H5Eprint1(stdout); status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout); status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout); H5close(); delete [] array_all; if (bXMF && rank==0) { FILE *xmf = 0; xmf = fopen(fullpath_xmf.c_str(), "w"); fprintf(xmf, "<?xml version=\"1.0\" ?>\n"); fprintf(xmf, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"); fprintf(xmf, "<Xdmf Version=\"2.0\">\n"); fprintf(xmf, " <Domain>\n"); fprintf(xmf, " <Grid GridType=\"Uniform\">\n"); fprintf(xmf, " <Time Value=\"%e\"/>\n\n", absTime); fprintf(xmf, " <Topology TopologyType=\"3DRectMesh\" Dimensions=\"%d %d %d\"/>\n\n", mesh_dims[2], mesh_dims[1], mesh_dims[0]); fprintf(xmf, " <Geometry GeometryType=\"VxVyVz\">\n"); fprintf(xmf, " <DataItem Name=\"mesh_vx\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[0]); fprintf(xmf, " %s:/vx\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vy\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[1]); fprintf(xmf, " %s:/vy\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vz\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[2]); fprintf(xmf, " %s:/vz\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Geometry>\n\n"); fprintf(xmf, " <Attribute Name=\"data\" AttributeType=\"%s\" Center=\"Cell\">\n", TStreamer::getAttributeName()); fprintf(xmf, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" Precision=\"%d\" Format=\"HDF\">\n",(int)dims[0], (int)dims[1], (int)dims[2], (int)dims[3], (int)sizeof(hdf5Real)); fprintf(xmf, " %s:/data\n", filename_h5.c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Attribute>\n"); fprintf(xmf, " </Grid>\n"); fprintf(xmf, " </Domain>\n"); fprintf(xmf, "</Xdmf>\n"); fclose(xmf); } #else _warn_no_hdf5(); #endif } template<typename TStreamer, typename hdf5Real, typename TGrid> void ReadHDF5_MPI(TGrid &grid, const std::string& fname, const std::string& dpath=".") { #ifdef CUBISM_USE_HDF typedef typename TGrid::BlockType B; int rank; // fname is the base filepath tail without file type extension and // additional identifiers std::ostringstream filename; std::ostringstream fullpath; filename << fname; fullpath << dpath << "/" << filename.str(); herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; MPI_Comm comm = grid.getCartComm(); MPI_Comm_rank(comm, &rank); int coords[3]; grid.peindex(coords); const unsigned int NX = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(0))*B::sizeX; const unsigned int NY = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(1))*B::sizeY; const unsigned int NZ = static_cast<unsigned int>(grid.getResidentBlocksPerDimension(2))*B::sizeZ; const unsigned int NCHANNELS = TStreamer::NCHANNELS; hdf5Real * array_all = new hdf5Real[NX * NY * NZ * NCHANNELS]; std::vector<BlockInfo> vInfo_local = grid.getResidentBlocksInfo(); hsize_t count[4] = {NZ, NY, NX, NCHANNELS}; hsize_t offset[4] = { static_cast<unsigned int>(coords[2]) * NZ, static_cast<unsigned int>(coords[1]) * NY, static_cast<unsigned int>(coords[0]) * NX, 0 }; H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); status = H5Pset_fapl_mpio(fapl_id, comm, MPI_INFO_NULL); if(status<0) H5Eprint1(stdout); file_id = H5Fopen((fullpath.str()+".h5").c_str(), H5F_ACC_RDONLY, fapl_id); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); dataset_id = H5Dopen2(file_id, "data", H5P_DEFAULT); fapl_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(fapl_id, H5FD_MPIO_COLLECTIVE); fspace_id = H5Dget_space(dataset_id); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); status = H5Dread(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all); if (status < 0) H5Eprint1(stdout); #pragma omp parallel for for(size_t i=0; i<vInfo_local.size(); i++) { BlockInfo& info = vInfo_local[i]; const int idx[3] = {info.index[0], info.index[1], info.index[2]}; B & b = *(B*)info.ptrBlock; for(int iz=0; iz<static_cast<int>(B::sizeZ); iz++) for(int iy=0; iy<static_cast<int>(B::sizeY); iy++) for(int ix=0; ix<static_cast<int>(B::sizeX); ix++) { const int gx = idx[0]*B::sizeX + ix; const int gy = idx[1]*B::sizeY + iy; const int gz = idx[2]*B::sizeZ + iz; hdf5Real * const ptr_input = array_all + NCHANNELS*(gx + NX * (gy + NY * gz)); TStreamer::operate(b, ptr_input, ix, iy, iz); } } status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout); status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout); H5close(); delete [] array_all; #else _warn_no_hdf5(); #endif } CUBISM_NAMESPACE_END
two.c
#include "two.h" #pragma omp declare target //static int state = 2; int two(void) { return state; } #pragma omp end declare target
GB_unop__trunc_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__trunc_fp32_fp32) // op(A') function: GB (_unop_tran__trunc_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = truncf (aij) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = truncf (x) ; // casting #define GB_CAST(z, aij) \ float z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ float z = aij ; \ Cx [pC] = truncf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TRUNC || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__trunc_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = truncf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = truncf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__trunc_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
sptensor.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "sptensor.h" #include "matrix.h" #include "sort.h" #include "io.h" #include "timer.h" #include "util.h" #include <math.h> /****************************************************************************** * PRIVATE FUNCTONS *****************************************************************************/ static inline int p_same_coord( sptensor_t const * const tt, idx_t const i, idx_t const j) { idx_t const nmodes = tt->nmodes; if(nmodes == 3) { return (tt->ind[0][i] == tt->ind[0][j]) && (tt->ind[1][i] == tt->ind[1][j]) && (tt->ind[2][i] == tt->ind[2][j]); } else { for(idx_t m=0; m < nmodes; ++m) { if(tt->ind[m][i] != tt->ind[m][j]) { return 0; } } return 1; } } /****************************************************************************** * PUBLIC FUNCTONS *****************************************************************************/ val_t tt_normsq(sptensor_t const * const tt) { val_t norm = 0.0; val_t const * const restrict tv = tt->vals; for(idx_t n=0; n < tt->nnz; ++n) { norm += tv[n] * tv[n]; } return norm; } double tt_density( sptensor_t const * const tt) { double root = pow((double)tt->nnz, 1./(double)tt->nmodes); double density = 1.0; for(idx_t m=0; m < tt->nmodes; ++m) { density *= root / (double)tt->dims[m]; } return density; } idx_t * tt_get_slices( sptensor_t const * const tt, idx_t const m, idx_t * nunique) { /* get maximum number of unique slices */ idx_t minidx = tt->dims[m]; idx_t maxidx = 0; idx_t const nnz = tt->nnz; idx_t const * const inds = tt->ind[m]; /* find maximum number of uniques */ for(idx_t n=0; n < nnz; ++n) { minidx = SS_MIN(minidx, inds[n]); maxidx = SS_MAX(maxidx, inds[n]); } /* +1 because maxidx is inclusive, not exclusive */ idx_t const maxrange = 1 + maxidx - minidx; /* mark slices which are present and count uniques */ idx_t * slice_mkrs = calloc(maxrange, sizeof(*slice_mkrs)); idx_t found = 0; for(idx_t n=0; n < nnz; ++n) { assert(inds[n] >= minidx); idx_t const idx = inds[n] - minidx; if(slice_mkrs[idx] == 0) { slice_mkrs[idx] = 1; ++found; } } *nunique = found; /* now copy unique slices */ idx_t * slices = splatt_malloc(found * sizeof(*slices)); idx_t ptr = 0; for(idx_t i=0; i < maxrange; ++i) { if(slice_mkrs[i] == 1) { slices[ptr++] = i + minidx; } } free(slice_mkrs); return slices; } idx_t * tt_get_hist( sptensor_t const * const tt, idx_t const mode) { idx_t * restrict hist = splatt_malloc(tt->dims[mode] * sizeof(*hist)); memset(hist, 0, tt->dims[mode] * sizeof(*hist)); idx_t const * const restrict inds = tt->ind[mode]; #pragma omp parallel for schedule(static) for(idx_t x=0; x < tt->nnz; ++x) { #pragma omp atomic ++hist[inds[x]]; } return hist; } sptensor_t * tt_copy( sptensor_t const * const tt) { idx_t const nnz = tt->nnz; idx_t const nmodes = tt->nmodes; sptensor_t * ret = tt_alloc(nnz, nmodes); ret->tiled = tt->tiled; ret->type = tt->type; memcpy(ret->dims, tt->dims, nmodes * sizeof(*(tt->dims))); /* copy vals */ par_memcpy(ret->vals, tt->vals, nnz * sizeof(*(tt->vals))); /* copy inds */ for(idx_t m=0; m < nmodes; ++m) { par_memcpy(ret->ind[m], tt->ind[m], nnz * sizeof(**(tt->ind))); if(tt->indmap[m] != NULL) { ret->indmap[m] = splatt_malloc(tt->dims[m] * sizeof(**(ret->indmap))); par_memcpy(ret->indmap[m], tt->indmap[m], tt->dims[m] * sizeof(**(ret->indmap))); } else { ret->indmap[m] = NULL; } } return ret; } sptensor_t * tt_union( sptensor_t * const tt_a, sptensor_t * const tt_b) { assert(tt_a->nmodes == tt_b->nmodes); idx_t const nmodes = tt_a->nmodes; tt_sort(tt_a, 0, NULL); tt_sort(tt_b, 0, NULL); /* count nnz in the union */ idx_t uniq = 0; idx_t ptra = 0; idx_t ptrb = 0; while(ptra < tt_a->nnz && ptrb < tt_b->nnz) { /* if nnz are the same */ bool same = true; /* if -1 if tt_a smaller, 0 for same sparsity, 1 for tt_b larger */ int order = 0; if(tt_a->vals[ptra] != tt_b->vals[ptrb]) { same = false; } for(idx_t m=0; m < nmodes; ++m) { if(tt_a->ind[m][ptra] != tt_b->ind[m][ptrb]) { same = false; if(tt_a->ind[m][ptra] < tt_b->ind[m][ptrb]) { order = -1; } else { order = 1; } break; } } if(same) { #if 0 printf("same: %lu/%lu = %lu/%lu -> %lu\n", ptra, tt_a->nnz, ptrb, tt_b->nnz, uniq); printf("A: (%lu %lu %lu %0.1f) B: (%lu %lu %lu %0.1f)\n", tt_a->ind[0][ptra], tt_a->ind[1][ptra], tt_a->ind[2][ptra], tt_a->vals[ptra], tt_b->ind[0][ptrb], tt_b->ind[1][ptrb], tt_b->ind[2][ptrb], tt_b->vals[ptrb]); #endif /* just copy one */ ++ptra; ++ptrb; } else { /* if tt_a and tt_b have the same idx but different values */ if(order == 0) { ++ptra; ++ptrb; ++uniq; /* account for both */ } else if(order == -1) { ++ptra; } else { ++ptrb; } } ++uniq; } /* grab leftovers */ uniq += (tt_a->nnz - ptra) + (tt_b->nnz - ptrb); /* allocate */ sptensor_t * ret = tt_alloc(uniq, nmodes); /* now copy every thing over */ uniq = 0; ptra = 0; ptrb = 0; while(ptra < tt_a->nnz && ptrb < tt_b->nnz) { /* if nnz are the same */ bool same = true; /* if -1 if tt_a smaller, 0 for same sparsity, 1 for tt_b larger */ int order = 0; if(tt_a->vals[ptra] != tt_b->vals[ptrb]) { same = false; } for(idx_t m=0; m < nmodes; ++m) { if(tt_a->ind[m][ptra] != tt_b->ind[m][ptrb]) { same = false; if(tt_a->ind[m][ptra] < tt_b->ind[m][ptrb]) { order = -1; } else { order = 1; } break; } } if(same) { /* just copy one */ ret->vals[uniq] = tt_a->vals[ptra]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_a->ind[m][ptra]; } ++ptra; ++ptrb; } else { if(order == 0) { /* just grab both */ ret->vals[uniq] = tt_a->vals[ptra]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_a->ind[m][ptra]; } ++uniq; ret->vals[uniq] = tt_b->vals[ptrb]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_b->ind[m][ptrb]; } ++ptra; ++ptrb; } else if(order == -1) { ret->vals[uniq] = tt_a->vals[ptra]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_a->ind[m][ptra]; } ++ptra; } else { ret->vals[uniq] = tt_b->vals[ptrb]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_b->ind[m][ptrb]; } ++ptrb; } } ++uniq; } /* grab leftovers */ for(; ptra < tt_a->nnz; ++ptra) { ret->vals[uniq] = tt_a->vals[ptra]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_a->ind[m][ptra]; } ++uniq; } for(; ptrb < tt_b->nnz; ++ptrb) { ret->vals[uniq] = tt_b->vals[ptrb]; for(idx_t m=0; m < nmodes; ++m) { ret->ind[m][uniq] = tt_b->ind[m][ptrb]; } ++uniq; } /* grab new dims */ tt_fill_dims(ret); return ret; } void tt_fill_dims( sptensor_t * const tt) { for(idx_t m=0; m < tt->nmodes; ++m) { idx_t dim = 0; #pragma omp parallel for reduction(max:dim) for(idx_t n=0; n < tt->nnz; ++n) { dim = SS_MAX(dim, tt->ind[m][n] + 1); } tt->dims[m] = dim; } } idx_t tt_remove_dups( sptensor_t * const tt) { tt_sort(tt, 0, NULL); idx_t const nmodes = tt->nmodes; idx_t newnnz = 0; for(idx_t nnz = 1; nnz < tt->nnz; ++nnz) { /* if the two nnz are the same, average them */ if(p_same_coord(tt, newnnz, nnz)) { tt->vals[newnnz] += tt->vals[nnz]; } else { /* new another nnz */ ++newnnz; for(idx_t m=0; m < nmodes; ++m) { tt->ind[m][newnnz] = tt->ind[m][nnz]; } tt->vals[newnnz] = tt->vals[nnz]; } } ++newnnz; idx_t const diff = tt->nnz - newnnz; tt->nnz = newnnz; return diff; } idx_t tt_remove_empty( sptensor_t * const tt) { idx_t dim_sizes[MAX_NMODES]; idx_t nremoved = 0; /* Allocate indmap */ idx_t const nmodes = tt->nmodes; idx_t const nnz = tt->nnz; idx_t maxdim = 0; for(idx_t m=0; m < tt->nmodes; ++m) { maxdim = tt->dims[m] > maxdim ? tt->dims[m] : maxdim; } /* slice counts */ idx_t * scounts = splatt_malloc(maxdim * sizeof(*scounts)); for(idx_t m=0; m < nmodes; ++m) { dim_sizes[m] = 0; memset(scounts, 0, maxdim * sizeof(*scounts)); /* Fill in indmap */ for(idx_t n=0; n < tt->nnz; ++n) { /* keep track of #unique slices */ if(scounts[tt->ind[m][n]] == 0) { scounts[tt->ind[m][n]] = 1; ++dim_sizes[m]; } } /* move on if no remapping is necessary */ if(dim_sizes[m] == tt->dims[m]) { tt->indmap[m] = NULL; continue; } nremoved += tt->dims[m] - dim_sizes[m]; /* Now scan to remove empty slices */ idx_t ptr = 0; for(idx_t i=0; i < tt->dims[m]; ++i) { if(scounts[i] == 1) { scounts[i] = ptr++; } } tt->indmap[m] = splatt_malloc(dim_sizes[m] * sizeof(**tt->indmap)); /* relabel all indices in mode m */ tt->dims[m] = dim_sizes[m]; for(idx_t n=0; n < tt->nnz; ++n) { idx_t const global = tt->ind[m][n]; idx_t const local = scounts[global]; assert(local < dim_sizes[m]); tt->indmap[m][local] = global; /* store local -> global mapping */ tt->ind[m][n] = local; } } splatt_free(scounts); return nremoved; } /****************************************************************************** * PUBLIC FUNCTONS *****************************************************************************/ sptensor_t * tt_read( char const * const ifname) { return tt_read_file(ifname); } sptensor_t * tt_alloc( idx_t const nnz, idx_t const nmodes) { sptensor_t * tt = splatt_malloc(sizeof(*tt)); tt->tiled = SPLATT_NOTILE; tt->nnz = nnz; tt->vals = splatt_malloc(nnz * sizeof(*(tt->vals))); tt->nmodes = nmodes; tt->type = (nmodes == 3) ? SPLATT_3MODE : SPLATT_NMODE; tt->dims = splatt_malloc(nmodes * sizeof(*(tt->dims))); tt->ind = splatt_malloc(nmodes * sizeof(*(tt->ind))); for(idx_t m=0; m < nmodes; ++m) { tt->ind[m] = splatt_malloc(nnz * sizeof(**(tt->ind))); tt->indmap[m] = NULL; } return tt; } void tt_fill( sptensor_t * const tt, idx_t const nnz, idx_t const nmodes, idx_t ** const inds, val_t * const vals) { tt->tiled = SPLATT_NOTILE; tt->nnz = nnz; tt->vals = vals; tt->ind = inds; tt->nmodes = nmodes; tt->type = (nmodes == 3) ? SPLATT_3MODE : SPLATT_NMODE; tt->dims = splatt_malloc(nmodes * sizeof(*tt->dims)); for(idx_t m=0; m < nmodes; ++m) { tt->indmap[m] = NULL; } tt_fill_dims(tt); } void tt_free( sptensor_t * tt) { tt->nnz = 0; for(idx_t m=0; m < tt->nmodes; ++m) { splatt_free(tt->ind[m]); splatt_free(tt->indmap[m]); } tt->nmodes = 0; splatt_free(tt->dims); splatt_free(tt->ind); splatt_free(tt->vals); splatt_free(tt); } spmatrix_t * tt_unfold( sptensor_t * const tt, idx_t const mode) { idx_t nrows = tt->dims[mode]; idx_t ncols = 1; for(idx_t m=1; m < tt->nmodes; ++m) { ncols *= tt->dims[(mode + m) % tt->nmodes]; } /* sort tt */ tt_sort(tt, mode, NULL); /* allocate and fill matrix */ spmatrix_t * mat = spmat_alloc(nrows, ncols, tt->nnz); idx_t * const rowptr = mat->rowptr; idx_t * const colind = mat->colind; val_t * const mvals = mat->vals; /* make sure to skip ahead to the first non-empty slice */ idx_t row = 0; for(idx_t n=0; n < tt->nnz; ++n) { /* increment row and account for possibly empty ones */ while(row <= tt->ind[mode][n]) { rowptr[row++] = n; } mvals[n] = tt->vals[n]; idx_t col = 0; idx_t mult = 1; for(idx_t m = 0; m < tt->nmodes; ++m) { idx_t const off = tt->nmodes - 1 - m; if(off == mode) { continue; } col += tt->ind[off][n] * mult; mult *= tt->dims[off]; } colind[n] = col; } /* account for any empty rows at end, too */ for(idx_t r=row; r <= nrows; ++r) { rowptr[r] = tt->nnz; } return mat; }
GB_binop__bshift_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_08__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_02__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_04__bshift_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bshift_int32) // C+=b function (dense accum): GB (_Cdense_accumb__bshift_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_int32) // C=scalar+B GB (_bind1st__bshift_int32) // C=scalar+B' GB (_bind1st_tran__bshift_int32) // C=A+scalar GB (_bind2nd__bshift_int32) // C=A'+scalar GB (_bind2nd_tran__bshift_int32) // C type: int32_t // A type: int32_t // B,b type: int8_t // BinaryOp: cij = GB_bitshift_int32 (aij, bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 0 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_bitshift_int32 (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BSHIFT || GxB_NO_INT32 || GxB_NO_BSHIFT_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bshift_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bshift_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bshift_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bshift_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bshift_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bshift_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bshift_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bshift_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bshift_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_bitshift_int32 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bshift_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_bitshift_int32 (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_int32 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__bshift_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_int32 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__bshift_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
axmyzManyPfloat.c
// This kernel is needed as it used for mixed-precision Jacobi preconditioning extern "C" void FUNC(axmyzManyPfloat)(const dlong & N, const dlong & Nfields, const dlong & offset, const dfloat & alpha, const dfloat * __restrict__ x, const pfloat * __restrict__ y, dfloat * __restrict__ z){ #ifdef __NEKRS__OMP__ #pragma omp parallel for #endif for(dlong n=0;n<N;++n){ for(int fld = 0; fld < Nfields; ++fld){ const int id = n + fld *offset; z[id] = dfloat(alpha*x[id]*y[id]); } } }
pca_yinyang.c
#include "pca_yinyang.h" #include "kmeans_utils.h" #include "../../utils/matrix/csr_matrix/csr_to_vector_list.h" #include "../../utils/matrix/vector_list/vector_list_math.h" #include "../../utils/matrix/csr_matrix/csr_math.h" #include "../../utils/vector/common/common_vector_math.h" #include "../../utils/vector/sparse/sparse_vector_math.h" #include "../../utils/fcl_logging.h" #include <math.h> #include <unistd.h> #include <float.h> struct kmeans_result* pca_yinyang_kmeans(struct csr_matrix* samples, struct kmeans_params *prms) { uint32_t i; uint64_t j; struct sparse_vector* pca_projection_samples; /* projection matrix of samples */ struct sparse_vector* pca_projection_clusters; /* projection matrix of clusters */ uint64_t no_groups; uint32_t disable_optimizations; uint64_t *cluster_to_group; struct general_kmeans_context ctx; VALUE_TYPE* vector_lengths_pca_samples; VALUE_TYPE* vector_lengths_pca_clusters; struct kmeans_result* res; VALUE_TYPE* distance_clustersold_to_clustersnew; /* distance between clusters before/after a shift */ struct group* groups; VALUE_TYPE *group_max_drift; VALUE_TYPE **lower_bounds; pca_projection_clusters = NULL; pca_projection_samples = NULL; disable_optimizations = (prms->ext_vects == NULL || prms->kmeans_algorithm_id == ALGORITHM_YINYANG); initialize_general_context(prms, &ctx, samples); if (disable_optimizations && prms->kmeans_algorithm_id == ALGORITHM_PCA_YINYANG) { if (prms->verbose) LOG_ERROR("Unable to do pca_yinyang since no file_input_vectors was supplied. Doing regular yinyang instead!"); } if (!disable_optimizations) { /* create pca projections for the samples */ pca_projection_samples = matrix_dot(samples, prms->ext_vects); calculate_vector_list_lengths(pca_projection_samples, samples->sample_count, &vector_lengths_pca_samples); /* create pca projections for the clusters */ pca_projection_clusters = sparse_vectors_matrix_dot(ctx.cluster_vectors, ctx.no_clusters, prms->ext_vects); vector_lengths_pca_clusters = NULL; } distance_clustersold_to_clustersnew = (VALUE_TYPE*) calloc(ctx.no_clusters, sizeof(VALUE_TYPE)); /* no_groups is set to no_clusters / 10 as suggested in the yinyang paper */ no_groups = ctx.no_clusters / 10; if (no_groups == 0) no_groups = 1; /* create yinyang cluster groups by doing 5 k-means iterations on the clusters */ create_kmeans_cluster_groups(ctx.cluster_vectors , ctx.no_clusters , ctx.samples->sample_count , &groups, &no_groups); group_max_drift = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); lower_bounds = (VALUE_TYPE**) calloc(ctx.samples->sample_count, sizeof(VALUE_TYPE*)); for (i = 0; i < ctx.samples->sample_count; i++) { lower_bounds[i] = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); } cluster_to_group = (uint64_t*) calloc(ctx.no_clusters, sizeof(uint64_t)); for (i = 0; i < no_groups; i++) { for (j = 0; j < groups[i].no_clusters; j++) { cluster_to_group[groups[i].clusters[j]] = i; } } for (i = 0; i < prms->iteration_limit && !ctx.converged && !prms->stop; i++) { uint64_t saved_calculations_pca; uint64_t done_pca_calcs; uint64_t saved_calculations_prev_cluster; uint64_t saved_calculations_global, saved_calculations_local; uint64_t groups_not_skipped; saved_calculations_global = 0; saved_calculations_local = 0; saved_calculations_prev_cluster = 0; groups_not_skipped = 0; /* initialize data needed for the iteration */ pre_process_iteration(&ctx); if (!disable_optimizations) { /* reset all calculation counters */ done_pca_calcs = 0; saved_calculations_pca = 0; free(vector_lengths_pca_clusters); calculate_vector_list_lengths(pca_projection_clusters, ctx.no_clusters, &vector_lengths_pca_clusters); } if (i == 0) { /* first iteration is done with regular kmeans to find the upper and lower bounds */ uint64_t sample_id, l; /* do one regular kmeans step to initialize bounds */ #pragma omp parallel for schedule(dynamic, 1000) private(l) for (sample_id = 0; sample_id < ctx.samples->sample_count; sample_id++) { uint64_t cluster_id; VALUE_TYPE dist; uint32_t is_first_assignment; is_first_assignment = 0; if (omp_get_thread_num() == 0) check_signals(&(prms->stop)); if (!prms->stop) { for (l = 0; l < no_groups; l++) { lower_bounds[sample_id][l] = DBL_MAX; } for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) { if (!disable_optimizations) { dist = euclid_vector(pca_projection_samples[sample_id].keys , pca_projection_samples[sample_id].values , pca_projection_samples[sample_id].nnz , pca_projection_clusters[cluster_id].keys , pca_projection_clusters[cluster_id].values , pca_projection_clusters[cluster_id].nnz , vector_lengths_pca_samples[sample_id] , vector_lengths_pca_clusters[cluster_id]); done_pca_calcs += 1; /* we do this fabs to not run into numeric errors */ if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) { saved_calculations_pca += 1; goto end_cluster_init; } } dist = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, cluster_id , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; if (dist < ctx.cluster_distances[sample_id]) { if (is_first_assignment) { is_first_assignment = 0; } else { lower_bounds[sample_id][cluster_to_group[ctx.cluster_assignments[sample_id]]] = ctx.cluster_distances[sample_id]; } ctx.cluster_distances[sample_id] = dist; ctx.cluster_assignments[sample_id] = cluster_id; } else { end_cluster_init:; if (dist < lower_bounds[sample_id][cluster_to_group[cluster_id]]) { lower_bounds[sample_id][cluster_to_group[cluster_id]] = dist; } } } } } } else { #pragma omp parallel for schedule(dynamic, 1000) for (j = 0; j < ctx.samples->sample_count; j++) { VALUE_TYPE dist; uint64_t cluster_id, sample_id, l; VALUE_TYPE *temp_lower_bounds; VALUE_TYPE global_lower_bound; VALUE_TYPE *should_group_be_updated; sample_id = j; if (omp_get_thread_num() == 0) check_signals(&(prms->stop)); if (!prms->stop) { /* update upper bound of this sample with drift of assigned cluster */ ctx.cluster_distances[sample_id] = ctx.cluster_distances[sample_id] + distance_clustersold_to_clustersnew[ctx.cluster_assignments[sample_id]]; temp_lower_bounds = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); should_group_be_updated = (VALUE_TYPE*) calloc(no_groups, sizeof(VALUE_TYPE)); global_lower_bound = DBL_MAX; for (l = 0; l < no_groups; l++) { temp_lower_bounds[l] = lower_bounds[sample_id][l]; lower_bounds[sample_id][l] = lower_bounds[sample_id][l] - group_max_drift[l]; if (global_lower_bound > lower_bounds[sample_id][l]) global_lower_bound = lower_bounds[sample_id][l]; } /* check if the global lower bound is already bigger than the current upper bound */ if (global_lower_bound >= ctx.cluster_distances[sample_id]) { saved_calculations_global += ctx.no_clusters; goto end; } /* tighten the upper bound by calculating the actual distance to the current closest cluster */ ctx.cluster_distances[sample_id] = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, ctx.cluster_assignments[sample_id] , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; /* recheck if the global lower bound is now bigger than the current upper bound */ if (global_lower_bound >= ctx.cluster_distances[sample_id]) { saved_calculations_global += ctx.no_clusters - 1; goto end; } for (l = 0; l < no_groups; l++) { if (lower_bounds[sample_id][l] < ctx.cluster_distances[sample_id]) { should_group_be_updated[l] = 1; groups_not_skipped += 1; lower_bounds[sample_id][l] = DBL_MAX; } } for (cluster_id = 0; cluster_id < ctx.no_clusters; cluster_id++) { if (!should_group_be_updated[cluster_to_group[cluster_id]]) { saved_calculations_prev_cluster++; continue; } if (ctx.cluster_counts[cluster_id] == 0 || cluster_id == ctx.previous_cluster_assignments[sample_id]) continue; if (lower_bounds[sample_id][cluster_to_group[cluster_id]] < temp_lower_bounds[cluster_to_group[cluster_id]] - distance_clustersold_to_clustersnew[cluster_id]) { dist = lower_bounds[sample_id][cluster_to_group[cluster_id]]; saved_calculations_local += 1; goto end_cluster; } if (!disable_optimizations) { if (i < 15) { /* pca optimizations */ dist = euclid_vector(pca_projection_samples[sample_id].keys , pca_projection_samples[sample_id].values , pca_projection_samples[sample_id].nnz , pca_projection_clusters[cluster_id].keys , pca_projection_clusters[cluster_id].values , pca_projection_clusters[cluster_id].nnz , vector_lengths_pca_samples[sample_id] , vector_lengths_pca_clusters[cluster_id]); done_pca_calcs += 1; /* we do this fabs to not run into numeric errors */ if (dist >= ctx.cluster_distances[sample_id] && fabs(dist - ctx.cluster_distances[sample_id]) >= 1e-6) { saved_calculations_pca += 1; goto end_cluster; } } } dist = euclid_vector_list(samples, sample_id, ctx.cluster_vectors, cluster_id , ctx.vector_lengths_samples, ctx.vector_lengths_clusters); /*#pragma omp critical*/ ctx.done_calculations += 1; if (dist < ctx.cluster_distances[sample_id]) { lower_bounds[sample_id][cluster_to_group[ctx.cluster_assignments[sample_id]]] = ctx.cluster_distances[sample_id]; ctx.cluster_distances[sample_id] = dist; ctx.cluster_assignments[sample_id] = cluster_id; } else { end_cluster:; if (dist < lower_bounds[sample_id][cluster_to_group[cluster_id]]) { lower_bounds[sample_id][cluster_to_group[cluster_id]] = dist; } } } end:; free(should_group_be_updated); free(temp_lower_bounds); } } /* block iterate over samples */ } /* block is first iteration */ post_process_iteration(&ctx, prms); /* shift clusters to new position */ calculate_shifted_clusters(&ctx); /* calculate distance between a cluster before and after the shift */ calculate_distance_clustersold_to_clustersnew(distance_clustersold_to_clustersnew , ctx.shifted_cluster_vectors , ctx.cluster_vectors , ctx.no_clusters , ctx.vector_lengths_shifted_clusters , ctx.vector_lengths_clusters , ctx.clusters_not_changed); switch_to_shifted_clusters(&ctx); if (!disable_optimizations) { /* update only projections for cluster that shifted */ update_dot_products(ctx.cluster_vectors, ctx.no_clusters, prms->ext_vects, ctx.clusters_not_changed, pca_projection_clusters); d_add_ilist(&(prms->tr), "iteration_pca_calcs", done_pca_calcs); d_add_ilist(&(prms->tr), "iteration_pca_calcs_success", saved_calculations_pca); } /* ------------ calculate maximum drift for every group ------------- */ { uint64_t *clusters; uint64_t n_clusters, l, k; VALUE_TYPE drift; for (l = 0; l < no_groups; l++) { clusters = groups[l].clusters; n_clusters = groups[l].no_clusters; group_max_drift[l] = 0; for (k = 0; k < n_clusters; k++) { drift = distance_clustersold_to_clustersnew[clusters[k]]; if (group_max_drift[l] < drift) group_max_drift[l] = drift; } } } print_iteration_summary(&ctx, prms, i); /* print pca and yinyang statistics */ if (prms->verbose) LOG_INFO("PCA statistics b:%" PRINTF_INT64_MODIFIER "u/db:%" PRINTF_INT64_MODIFIER "u [YY] grp_not_skip=%" PRINTF_INT64_MODIFIER "u/pc:%" PRINTF_INT64_MODIFIER "u/g=%" PRINTF_INT64_MODIFIER "u/l=%" PRINTF_INT64_MODIFIER "u" , saved_calculations_pca , done_pca_calcs , groups_not_skipped , saved_calculations_prev_cluster , saved_calculations_global , saved_calculations_local); } if (prms->verbose) LOG_INFO("total total_no_calcs = %" PRINTF_INT64_MODIFIER "u", ctx.total_no_calcs); res = create_kmeans_result(prms, &ctx); /* cleanup all */ free_general_context(&ctx, prms); if (!disable_optimizations) { free_vector_list(pca_projection_samples, samples->sample_count); free(vector_lengths_pca_samples); free(pca_projection_samples); free_vector_list(pca_projection_clusters, ctx.no_clusters); free(pca_projection_clusters); free(vector_lengths_pca_clusters); } free_null(distance_clustersold_to_clustersnew); free_null(group_max_drift); for (i = 0; i < ctx.samples->sample_count; i++) { free_null(lower_bounds[i]); } for (i = 0; i < no_groups; i++) { free_null(groups[i].clusters); } free_null(groups); free_null(lower_bounds); free_null(cluster_to_group); return res; }
threading.h
#ifndef LIGHTGBM_UTILS_THREADING_H_ #define LIGHTGBM_UTILS_THREADING_H_ #include <LightGBM/utils/openmp_wrapper.h> #include <vector> #include <functional> namespace LightGBM { class Threading { public: template<typename INDEX_T> static inline void For(INDEX_T start, INDEX_T end, const std::function<void(int, INDEX_T, INDEX_T)>& inner_fun) { int num_threads = 1; #pragma omp parallel #pragma omp master { num_threads = omp_get_num_threads(); } INDEX_T num_inner = (end - start + num_threads - 1) / num_threads; if (num_inner <= 0) { num_inner = 1; } OMP_INIT_EX(); #pragma omp parallel for schedule(static,1) for (int i = 0; i < num_threads; ++i) { OMP_LOOP_EX_BEGIN(); INDEX_T inner_start = start + num_inner * i; INDEX_T inner_end = inner_start + num_inner; if (inner_end > end) { inner_end = end; } if (inner_start < end) { inner_fun(i, inner_start, inner_end); } OMP_LOOP_EX_END(); } OMP_THROW_EX(); } }; } // namespace LightGBM #endif // LightGBM_UTILS_THREADING_H_
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _sum4 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "veor q6, q6 \n" "veor q15, q15 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmla.f32 q6, q11, %e14[1] \n" "vmla.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmla.f32 q14, q11, %e14[1] \n" "vmla.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "veor q6, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "veor q14, q14 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q8, q8, q15 \n" "veor q15, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum2 = vdupq_n_f32(0.f); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "veor q13, q13 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmla.f32 q13, q10, %e10[1] \n" "vmla.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "veor q13, q13 \n" "vadd.f32 q7, q7, q14 \n" "veor q14, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(8*8, inch, outch); const float ktm[8][3] = { { 1.0f, 0.0f, 0.0f}, {-2.0f/9, -2.0f/9, -2.0f/9}, {-2.0f/9, 2.0f/9, -2.0f/9}, {1.0f/90, 1.0f/45, 2.0f/45}, {1.0f/90, -1.0f/45, 2.0f/45}, {1.0f/45, 1.0f/90, 1.0f/180}, {1.0f/45, -1.0f/90, 1.0f/180}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = kernel.data + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i=0; i<8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j=0; j<8; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<8; i++) { kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd64_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8*8, w_tm/8 * h_tm/8, inch); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm = img0_tm.row(i * w_tm/8 + j); // TODO neon optimize for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; r0_tm += 8; } } } } } // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8*8, w_tm/8 * h_tm/8, outch); #pragma omp parallel for for (int p = 0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k2); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k3); vst1q_f32(output0_tm, _output0_tm); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; float32x4_t _output0_tmn = vld1q_f32(output0_tm); float32x4_t _r0n = vld1q_f32(r0); float32x4_t _r1n = vld1q_f32(r1); float32x4_t _r2n = vld1q_f32(r2); float32x4_t _r3n = vld1q_f32(r3); float32x4_t _k0n = vld1q_f32(k0); float32x4_t _k1n = vld1q_f32(k1); float32x4_t _k2n = vld1q_f32(k2); float32x4_t _k3n = vld1q_f32(k3); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); _output0_tmn = vmlaq_f32(_output0_tmn, _r2n, _k2n); _output0_tmn = vmlaq_f32(_output0_tmn, _r3n, _k3n); vst1q_f32(output0_tm, _output0_tmn); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; } #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "mov r4, %0 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "vmla.f32 q15, q9, q11 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(k0), // %5 "=r"(k1), // %6 "=r"(k2), // %7 "=r"(k3) // %8 : "0"(output0_tm), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(k0), "6"(k1), "7"(k2), "8"(k3) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k0 -= 64; k1 -= 64; k2 -= 64; k3 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; output0_tm[m] += r2[m] * k2[m]; output0_tm[m] += r3[m] * k3[m]; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 64; output0_tm += 64; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm = out0_tm.row(i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; // TODO neon optimize for (int m=0; m<8; m++) { float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm += 8; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s1_winograd64_neon2(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, inch); const int tiles = w_tm/8 * h_tm/8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm01 = img0_tm.row(i * w_tm/8 + j); float* r0_tm23 = img0_tm.row(tiles + i * w_tm/8 + j); float* r0_tm45 = img0_tm.row(tiles * 2 + i * w_tm/8 + j); float* r0_tm67 = img0_tm.row(tiles * 3 + i * w_tm/8 + j); for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tms[4] = { r0_tm01, r0_tm23, r0_tm45, r0_tm67 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm = r0_tms[m/2] + (m%2) * 8; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; } } } } } // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k1n = vld1q_f32(k1+4); float32x4_t _k1nn = vld1q_f32(k1+8); float32x4_t _k1nnn = vld1q_f32(k1+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; float32x4_t _k1; float32x4_t _k1n; float32x4_t _k1nn; float32x4_t _k1nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "pld [%1, #512] \n" "vld1.f32 {%e4-%f4}, [%1 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e5-%f5}, [%1 :128]! \n" "vld1.f32 {%e6-%f6}, [%0 :128]! \n" "vld1.f32 {%e8-%f8}, [%1 :128]! \n" "vld1.f32 {%e7-%f7}, [%0 :128]! \n" "vld1.f32 {%e9-%f9}, [%1 :128]! \n" : "=r"(k0), // %0 "=r"(k1), // %1 "=w"(_k0), // %2 "=w"(_k0n), // %3 "=w"(_k1), // %4 "=w"(_k1n), // %5 "=w"(_k0nn), // %6 "=w"(_k0nnn), // %7 "=w"(_k1nn), // %8 "=w"(_k1nnn) // %9 : "0"(k0), "1"(k1) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; } #else if (nn > 0) { #if 1 asm volatile( "mov r4, %1 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "0: \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "subs %0, #1 \n" "vst1.f32 {d20-d23}, [r4 :128]! \n" "bne 0b \n" "sub %1, #32 \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(r1), "w"(_k0), // %8 "w"(_k0n), // %9 "w"(_k1), // %10 "w"(_k1n), // %11 "w"(_k0nn), // %12 "w"(_k0nnn), // %13 "w"(_k1nn), // %14 "w"(_k1nnn) // %15 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q9, q13, %q7 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "vmla.f32 q8, q14, %q8 \n" "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q9, q15, %q9 \n" "vmla.f32 q10, q12, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q10, q14, %q12 \n" "vmla.f32 q11, q15, %q13 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1) // %2 : "0"(output0_tm), "1"(r0), "2"(r1), "w"(_k0), // %6 "w"(_k0n), // %7 "w"(_k1), // %8 "w"(_k1n), // %9 "w"(_k0nn), // %10 "w"(_k0nnn), // %11 "w"(_k1nn), // %12 "w"(_k1nnn) // %13 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; } r0 += 16; r1 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; k1 += 16; #endif // __aarch64__ #else k0 += 16; k1 += 16; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e1-%f1}, [%0 :128]! \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e4-%f4}, [%0 :128]! \n" : "=r"(k0), // %0 "=w"(_k0), // %1 "=w"(_k0n), // %2 "=w"(_k0nn), // %3 "=w"(_k0nnn) // %4 : "0"(k0) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q4 \n" "vmla.f32 q9, q13, %q5 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q6 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "vmla.f32 q11, q13, %q7 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k0), // %4 "w"(_k0n), // %5 "w"(_k0nn), // %6 "w"(_k0nnn) // %7 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; #endif // __aarch64__ #else k0 += 16; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm/8 * h_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm01 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm23 = out0_tm.row(tiles + i * w_tm/8 + j); const float* output0_tm45 = out0_tm.row(tiles * 2 + i * w_tm/8 + j); const float* output0_tm67 = out0_tm.row(tiles * 3 + i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms[4] = { output0_tm01, output0_tm23, output0_tm45, output0_tm67 }; for (int m=0; m<8; m++) { const float* output0_tm = output0_tms[m/2] + (m%2) * 8; float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmla.f32 q10, q3, %e10[1] \n" "pld [%2, #128] \n" "vld2.f32 {d16-d17}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #128] \n" "vld2.f32 {d16-d17}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #128] \n" "vld2.f32 {d16-d17}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "veor q10, q10 \n" "vadd.f32 q0, q0, q11 \n" "veor q11, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } }
wpapsk.h
/* * This software is Copyright (c) 2012 Lukas Odzioba <lukas dot odzioba at gmail dot com> * and Copyright (c) 2012-2014 magnum * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without modification, are permitted. * * hccap format was introduced by oclHashcat-plus, and it is described here: http://hashcat.net/wiki/hccap * Code is based on Aircrack-ng source */ #ifndef _WPAPSK_H #define _WPAPSK_H #include "arch.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "stdint.h" #include <assert.h> #include <openssl/hmac.h> #define HCCAP_SIZE sizeof(hccap_t) #define BINARY_SIZE sizeof(mic_t) #define BINARY_ALIGN 4 #define PLAINTEXT_LENGTH 63 /* We can do 64 but spec. says 63 */ #define SALT_SIZE (sizeof(hccap_t) - sizeof(mic_t)) #define SALT_ALIGN MEM_ALIGN_NONE #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define FORMAT_TAG "$WPAPSK$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) /** if you want to change hccap_t structure is also defined in hccap2john.c **/ typedef struct { char essid[36]; unsigned char mac1[6]; unsigned char mac2[6]; unsigned char nonce1[32]; unsigned char nonce2[32]; unsigned char eapol[256]; int eapol_size; int keyver; unsigned char keymic[16]; } hccap_t; typedef struct { unsigned char keymic[16]; } mic_t; typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH + 1]; } wpapsk_password; typedef struct { uint32_t v[8]; } wpapsk_hash; typedef struct { uint32_t length; #ifdef JOHN_OCL_WPAPSK uint8_t eapol[256 + 64]; uint32_t eapol_size; // blocks uint8_t data[64 + 12]; #endif uint8_t salt[36]; // essid } wpapsk_salt; #ifndef _WPAPSK_CUDA_KERNEL static struct fmt_tests tests[] = { /* WPA2 testcase from http://wiki.wireshark.org/SampleCaptures */ {"$WPAPSK$Coherer#..l/Uf7J..qHUXMunTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosMyXdNxfBZUAYmgKqeb6GBPxLiIZr56NtWTGR/Cp5ldAk61.5I0.Ec.2...........nTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosM.................................................................3X.I.E..1uk0.E..1uk2.E..1uk0....................................................................................................................................................................................../t.....U...8FWdk8OpPckhewBwt4MXYI", "Induction"}, {"$WPAPSK$Harkonen#./FgTY0../B4zX6AKFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL.WK3GkF2rXfkPFGGi38MHkHDMbH.sm49Vc3pO4HPSUJE21.5I0.Ec.2........../KFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL..................................................................3X.I.E..1uk2.E..1uk2.E..1uk0.E..................................................................................................................................................................................../t.....U...BIpIs8sePU4r8yNnOxKHfM", "12345678"}, /* WPA, from aircrack-ng tests */ {"$WPAPSK$test#..qHuv0A..ZPYJBRzZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsRIfQN2Zar6EXp2BYcRuSkWEJIWjEJJvb4DWZCspbZ51.21.3zy.EY.6........../zZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsQ..................................................................BoK.31m.E2..31m.U2..31m.U2..31m.U................................................................................................................................................................................/X.....E...AkkDQmDg9837LBHG.dGlKA", "biscotte"}, /* Maximum length, 63 characters */ {"$WPAPSK$Greased Lighting#kA5.CDNB.07cofsOMXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGqgvfcXnuF1f7L5fgn4fQMLmDrKjdBNjb6LClRmfLiTYk21.5I0.Ec............7MXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGo.................................................................3X.I.E..1uk2.E..1uk2.E..1uk00...................................................................................................................................................................................../t.....U...D06LUdWVfGPaP1Oa3AV9Hg", "W*A5z&1?op2_L&Hla-OA$#5i_Lu@F+6d?je?u5!6+6766eluu7-l+jOEkIwLe90"}, {NULL} }; #endif /** Below are common variables used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/ static hccap_t hccap; ///structure with hccap data static wpapsk_salt currentsalt; ///structure for essid static mic_t *mic; ///table for MIC keys #ifndef JOHN_OCL_WPAPSK static wpapsk_password *inbuffer; ///table for candidate passwords static wpapsk_hash *outbuffer; ///table for PMK calculated by GPU #endif static int new_keys = 1; static char last_ssid[sizeof(hccap.essid)]; /** Below are common functions used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/ static hccap_t *decode_hccap(char *ciphertext) { static hccap_t hccap; char *essid = ciphertext + FORMAT_TAG_LEN; char *hash = strrchr(ciphertext, '#'); char *d = hccap.essid; char *cap = hash + 1; unsigned char tbuf[sizeof(hccap_t)]; unsigned char *dst = tbuf; int i; memset(&hccap, 0, sizeof(hccap)); if (hash == NULL) return &hccap; while (essid != hash) { ///copy essid to hccap *d++ = *essid++; } *d = '\0'; assert(*essid == '#'); for (i = 0; i < 118; i++) { dst[0] = (atoi64[ARCH_INDEX(cap[0])] << 2) | (atoi64[ARCH_INDEX(cap[1])] >> 4); dst[1] = (atoi64[ARCH_INDEX(cap[1])] << 4) | (atoi64[ARCH_INDEX(cap[2])] >> 2); dst[2] = (atoi64[ARCH_INDEX(cap[2])] << 6) | (atoi64[ARCH_INDEX(cap[3])]); dst += 3; cap += 4; } dst[0] = (atoi64[ARCH_INDEX(cap[0])] << 2) | (atoi64[ARCH_INDEX(cap[1])] >> 4); dst[1] = (atoi64[ARCH_INDEX(cap[1])] << 4) | (atoi64[ARCH_INDEX(cap[2])] >> 2); /* This emits warnings on some compilers */ //memcpy(&hccap.mac1,tbuf,sizeof(hccap_t)-36); memcpy(((char*)&hccap) + 36, tbuf, sizeof(hccap_t) - 36); #if !ARCH_LITTLE_ENDIAN hccap.eapol_size = JOHNSWAP(hccap.eapol_size); hccap.keyver = JOHNSWAP(hccap.keyver); #endif return &hccap; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD_32 dummy; } binary; hccap_t *hccap = decode_hccap(ciphertext); memcpy(binary.c, hccap->keymic, BINARY_SIZE); return binary.c; } static void *get_salt(char *ciphertext) { static hccap_t s; memcpy(&s, decode_hccap(ciphertext), SALT_SIZE); return &s; } static int valid(char *ciphertext, struct fmt_main *self) { char *hash; int hashlength = 0; hccap_t *hccap; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; hash = strrchr(ciphertext, '#'); if (hash == NULL || hash - (ciphertext + FORMAT_TAG_LEN) > 32) return 0; hash++; while (hash < ciphertext + strlen(ciphertext)) { if (atoi64[ARCH_INDEX(*hash++)] == 0x7f) return 0; hashlength++; } if (hashlength != 475) return 0; hccap = decode_hccap(ciphertext); if (strlen(hccap->essid) > 32) /* real life limit */ return 0; if(hccap->eapol_size > 256) return 0; if(hccap->eapol_size < 0) return 0; return 1; } #ifndef JOHN_OCL_WPAPSK static MAYBE_INLINE void prf_512(uint32_t * key, uint8_t * data, uint32_t * ret) { HMAC_CTX ctx; char *text = (char*)"Pairwise key expansion"; unsigned char buff[100]; memcpy(buff, text, 22); memcpy(buff + 23, data, 76); buff[22] = 0; buff[76 + 23] = 0; HMAC_Init(&ctx, key, 32, EVP_sha1()); HMAC_Update(&ctx, buff, 100); HMAC_Final(&ctx, (unsigned char *) ret, NULL); HMAC_CTX_cleanup(&ctx); } #endif static void insert_mac(uint8_t * data) { int k = memcmp(hccap.mac1, hccap.mac2, 6); if (k > 0) { memcpy(data, hccap.mac2, 6); memcpy(data + 6, hccap.mac1, 6); } else { memcpy(data, hccap.mac1, 6); memcpy(data + 6, hccap.mac2, 6); } } static void insert_nonce(uint8_t * data) { int k = memcmp(hccap.nonce1, hccap.nonce2, 32); if (k > 0) { memcpy(data, hccap.nonce2, 32); memcpy(data + 32, hccap.nonce1, 32); } else { memcpy(data, hccap.nonce1, 32); memcpy(data + 32, hccap.nonce2, 32); } } #ifdef WPAPSK_DEBUG static char *tomac(unsigned char *p) { static char buf[48]; sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", p[0], p[1], p[2], p[3], p[4], p[5]); return buf; } static char *hex(unsigned char *p, int len) { static char buf[1024]; char *op=buf; int i; if (len > 32) { do { for (i = 0; i < 32; ++i) { op += sprintf (op, "%02X", p[i]); if (i<31&&i%4==3) op += sprintf (op, " "); if (i==15) op += sprintf (op, ": "); } len -= 32; p += 32; op += sprintf (op, "\n "); } while (len > 32); } for (i = 0; i < len; ++i) { op += sprintf (op, "%02X", p[i]); if (i<31&&i%4==3) op += sprintf (op, " "); if (i==15) op += sprintf (op, ": "); } return buf; } static void Debug_hccap() { printf("essid: %s\n", hccap.essid); printf("mac1: %s\n", tomac(hccap.mac1)); printf("mac2: %s\n", tomac(hccap.mac2)); printf("nonce1: %s\n", hex(hccap.nonce1, 32)); printf("nonce2: %s\n", hex(hccap.nonce2, 32)); printf("eapol: %s\n", hex(hccap.eapol, 256)); printf("epol_sz: %d (0x%02X)\n", hccap.eapol_size, hccap.eapol_size); printf("keyver: %d\n", hccap.keyver); printf("keymic: %s\n", hex(hccap.keymic, 16)); } #endif static void set_salt(void *salt) { memcpy(&hccap, salt, SALT_SIZE); strncpy((char*)currentsalt.salt, hccap.essid, sizeof(currentsalt.salt)); currentsalt.length = strlen(hccap.essid); #ifdef JOHN_OCL_WPAPSK currentsalt.eapol_size = 1 + (hccap.eapol_size + 8) / 64; memcpy(currentsalt.eapol, hccap.eapol, hccap.eapol_size); memset(currentsalt.eapol + hccap.eapol_size, 0x80, 1); memset(currentsalt.eapol + hccap.eapol_size + 1, 0, 256 + 64 - hccap.eapol_size - 1); if (hccap.keyver != 1) alter_endianity(currentsalt.eapol, 256+56); ((unsigned int*)currentsalt.eapol)[16 * ((hccap.eapol_size + 8) / 64) + ((hccap.keyver == 1) ? 14 : 15)] = (64 + hccap.eapol_size) << 3; insert_mac(currentsalt.data); insert_nonce(currentsalt.data + 12); alter_endianity(currentsalt.data, 64 + 12); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(wpapsk_salt), &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); #endif //Debug_hccap(); } #ifndef JOHN_OCL_WPAPSK static void clear_keys(void) { new_keys = 1; } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static void wpapsk_postprocess(int keys) { int i; uint8_t data[64 + 12]; insert_mac(data); insert_nonce(data + 12); if (hccap.keyver == 1) { #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic) #endif for (i = 0; i < keys; i++) { uint32_t prf[20/4]; prf_512(outbuffer[i].v, data, prf); HMAC(EVP_md5(), prf, 16, hccap.eapol, hccap.eapol_size, mic[i].keymic, NULL); } } else { #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic) #endif for (i = 0; i < keys; i++) { uint32_t prf[20/4]; unsigned char keymic[20]; prf_512(outbuffer[i].v, data, prf); HMAC(EVP_sha1(), prf, 16, hccap.eapol, hccap.eapol_size, keymic, NULL); memcpy(mic[i].keymic, keymic, 16); } } } #endif static int binary_hash_0(void *binary) { #ifdef WPAPSK_DEBUG puts("binary"); uint32_t i, *b = binary; for (i = 0; i < 4; i++) printf("%08x ", b[i]); puts(""); #endif return ((uint32_t *) binary)[0] & PH_MASK_0; } static int get_hash_0(int index) { #ifdef WPAPSK_DEBUG int i; puts("get_hash"); uint32_t *b = (uint32_t *)mic[index].keymic; for (i = 0; i < 4; i++) printf("%08x ", b[i]); puts(""); #endif uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_0; } static int get_hash_1(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_1; } static int get_hash_2(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_2; } static int get_hash_3(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_3; } static int get_hash_4(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_4; } static int get_hash_5(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_5; } static int get_hash_6(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_6; } static int cmp_all(void *binary, int count) { uint32_t i, b = ((uint32_t *) binary)[0]; for (i = 0; i < count; i++) { uint32_t *m = (uint32_t*) mic[i].keymic; if (b == m[0]) return 1; } return 0; } static int cmp_one(void *binary, int index) { uint8_t i; uint32_t *b = (uint32_t*) binary; uint32_t *m = (uint32_t*) mic[index].keymic; for (i = 0; i < BINARY_SIZE / 4; i++) if (b[i] != m[i]) return 0; return 1; } static int cmp_exact(char *source, int index) { return 1; } static int salt_compare(const void *x, const void *y) { int c = strncmp((const char*)x, (const char*)y, 36); if (c) return c; return memcmp((const char*)x, (const char*)y, SALT_SIZE); } #endif
ScalarWave_RHSs.h
const REAL invdx0 = 1.0/dxx[0]; const REAL invdx1 = 1.0/dxx[1]; const REAL invdx2 = 1.0/dxx[2]; #pragma omp parallel for for(int i2=NGHOSTS; i2<NGHOSTS+Nxx[2]; i2++) { for(int i1=NGHOSTS; i1<NGHOSTS+Nxx[1]; i1++) { for(int i0=NGHOSTS; i0<NGHOSTS+Nxx[0]; i0++) { { /* * NRPy+ Finite Difference Code Generation, Step 1 of 2: Read from main memory and compute finite difference stencils: */ /* * Original SymPy expressions: * "[const double uu_dDD00 = invdx0**2*(-5*uu/2 + 4*uu_i0m1_i1_i2/3 - uu_i0m2_i1_i2/12 + 4*uu_i0p1_i1_i2/3 - uu_i0p2_i1_i2/12), * const double uu_dDD11 = invdx1**2*(-5*uu/2 + 4*uu_i0_i1m1_i2/3 - uu_i0_i1m2_i2/12 + 4*uu_i0_i1p1_i2/3 - uu_i0_i1p2_i2/12), * const double uu_dDD22 = invdx2**2*(-5*uu/2 + 4*uu_i0_i1_i2m1/3 - uu_i0_i1_i2m2/12 + 4*uu_i0_i1_i2p1/3 - uu_i0_i1_i2p2/12)]" */ const double uu_i0_i1_i2m2 = in_gfs[IDX4(UUGF, i0,i1,i2-2)]; const double uu_i0_i1_i2m1 = in_gfs[IDX4(UUGF, i0,i1,i2-1)]; const double uu_i0_i1m2_i2 = in_gfs[IDX4(UUGF, i0,i1-2,i2)]; const double uu_i0_i1m1_i2 = in_gfs[IDX4(UUGF, i0,i1-1,i2)]; const double uu_i0m2_i1_i2 = in_gfs[IDX4(UUGF, i0-2,i1,i2)]; const double uu_i0m1_i1_i2 = in_gfs[IDX4(UUGF, i0-1,i1,i2)]; const double uu = in_gfs[IDX4(UUGF, i0,i1,i2)]; const double uu_i0p1_i1_i2 = in_gfs[IDX4(UUGF, i0+1,i1,i2)]; const double uu_i0p2_i1_i2 = in_gfs[IDX4(UUGF, i0+2,i1,i2)]; const double uu_i0_i1p1_i2 = in_gfs[IDX4(UUGF, i0,i1+1,i2)]; const double uu_i0_i1p2_i2 = in_gfs[IDX4(UUGF, i0,i1+2,i2)]; const double uu_i0_i1_i2p1 = in_gfs[IDX4(UUGF, i0,i1,i2+1)]; const double uu_i0_i1_i2p2 = in_gfs[IDX4(UUGF, i0,i1,i2+2)]; const double vv = in_gfs[IDX4(VVGF, i0,i1,i2)]; const double tmpFD0 = -(5.0 / 2.0)*uu; const double uu_dDD00 = pow(invdx0, 2)*(tmpFD0 + ((4.0 / 3.0))*uu_i0m1_i1_i2 - (1.0 / 12.0)*uu_i0m2_i1_i2 + ((4.0 / 3.0))*uu_i0p1_i1_i2 - (1.0 / 12.0)*uu_i0p2_i1_i2); const double uu_dDD11 = pow(invdx1, 2)*(tmpFD0 + ((4.0 / 3.0))*uu_i0_i1m1_i2 - (1.0 / 12.0)*uu_i0_i1m2_i2 + ((4.0 / 3.0))*uu_i0_i1p1_i2 - (1.0 / 12.0)*uu_i0_i1p2_i2); const double uu_dDD22 = pow(invdx2, 2)*(tmpFD0 + ((4.0 / 3.0))*uu_i0_i1_i2m1 - (1.0 / 12.0)*uu_i0_i1_i2m2 + ((4.0 / 3.0))*uu_i0_i1_i2p1 - (1.0 / 12.0)*uu_i0_i1_i2p2); /* * NRPy+ Finite Difference Code Generation, Step 2 of 2: Evaluate SymPy expressions and write to main memory: */ /* * Original SymPy expressions: * "[rhs_gfs[IDX4(UUGF, i0, i1, i2)] = vv, * rhs_gfs[IDX4(VVGF, i0, i1, i2)] = uu_dDD00*wavespeed**2 + uu_dDD11*wavespeed**2 + uu_dDD22*wavespeed**2]" */ const double tmp0 = pow(wavespeed, 2); rhs_gfs[IDX4(UUGF, i0, i1, i2)] = vv; rhs_gfs[IDX4(VVGF, i0, i1, i2)] = tmp0*uu_dDD00 + tmp0*uu_dDD11 + tmp0*uu_dDD22; } } // END LOOP: for(int i0=NGHOSTS; i0<NGHOSTS+Nxx[0]; i0++) } // END LOOP: for(int i1=NGHOSTS; i1<NGHOSTS+Nxx[1]; i1++) } // END LOOP: for(int i2=NGHOSTS; i2<NGHOSTS+Nxx[2]; i2++)