text
stringlengths
1
1.05M
; A022794: Place where n-th 1 occurs in A023132. ; 1,2,3,5,7,9,12,15,18,22,26,30,35,40,45,51,57,64,71,78,86,94,102,111,120,129,139,149,159,170,181,192,204,216,229,242,255,269,283,297,312,327,342,358,374,390,407,424,441,459,477,496,515,534,554,574 mov $3,$0 add $3,1 mov $4,$0 lpb $3 mov $0,$4 mov $2,0 sub $3,1 sub $0,$3 seq $0,172474 ; a(n) = floor(n*sqrt(2)/4). add $2,$0 add $2,1 add $1,$2 lpe mov $0,$1
; A002066: a(n) = 10*4^n. ; 10,40,160,640,2560,10240,40960,163840,655360,2621440,10485760,41943040,167772160,671088640,2684354560,10737418240,42949672960,171798691840,687194767360,2748779069440,10995116277760,43980465111040,175921860444160,703687441776640,2814749767106560,11258999068426240,45035996273704960,180143985094819840,720575940379279360,2882303761517117440,11529215046068469760,46116860184273879040,184467440737095516160,737869762948382064640,2951479051793528258560,11805916207174113034240,47223664828696452136960,188894659314785808547840,755578637259143234191360,3022314549036572936765440,12089258196146291747061760,48357032784585166988247040,193428131138340667952988160,773712524553362671811952640,3094850098213450687247810560,12379400392853802748991242240,49517601571415210995964968960,198070406285660843983859875840,792281625142643375935439503360,3169126500570573503741758013440,12676506002282294014967032053760,50706024009129176059868128215040,202824096036516704239472512860160,811296384146066816957890051440640,3245185536584267267831560205762560,12980742146337069071326240823050240,51922968585348276285304963292200960,207691874341393105141219853168803840,830767497365572420564879412675215360 mov $1,4 pow $1,$0 mul $1,10 mov $0,$1
/*========================================================================= Program: Visualization Toolkit Module: vtkGlobeSource.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #include "vtkGlobeSource.h" #include "vtkCellArray.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkGeoMath.h" #include "vtkTimerLog.h" #include <cmath> vtkStandardNewMacro(vtkGlobeSource); // 0=NE, 1=SE, 2=SW, 3=NW //---------------------------------------------------------------------------- vtkGlobeSource::vtkGlobeSource() { VTK_LEGACY_BODY(vtkGlobeSource::vtkGlobeSource, "VTK 8.2"); this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Radius = vtkGeoMath::EarthRadiusMeters(); this->AutoCalculateCurtainHeight = true; this->CurtainHeight = 1000.0; this->LongitudeResolution = 10; this->LatitudeResolution = 10; this->StartLongitude = 0.0; this->EndLongitude = 360.0; this->StartLatitude = 0.0; this->EndLatitude = 180.0; this->QuadrilateralTessellation = 0; this->SetNumberOfInputPorts(0); } //---------------------------------------------------------------------------- void vtkGlobeSource::ComputeGlobePoint( double theta, double phi, double radius, double* x, double* normal) { // Lets keep this conversion code in a single place. double tmp = cos( vtkMath::RadiansFromDegrees( phi ) ); double n0 = -tmp * sin( vtkMath::RadiansFromDegrees( theta ) ); double n1 = tmp * cos( vtkMath::RadiansFromDegrees( theta ) ); double n2 = sin( vtkMath::RadiansFromDegrees( phi ) ); x[0] = n0 * radius; x[1] = n1 * radius; x[2] = n2 * radius; if (normal) { normal[0] = n0; normal[1] = n1; normal[2] = n2; } } //---------------------------------------------------------------------------- void vtkGlobeSource::ComputeLatitudeLongitude( double* x, double& theta, double& phi) { double rho = sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]); double S = sqrt(x[0]*x[0] + x[1]*x[1]); phi = acos(x[2] / rho); if (x[0] >= 0) { theta = asin(x[1] / S); } else { theta = vtkMath::Pi() - asin(x[1] / S); } phi = vtkMath::DegreesFromRadians( vtkMath::Pi() / 2.0 - phi ); theta = vtkMath::DegreesFromRadians( theta - vtkMath::Pi()/2.0 ); } //---------------------------------------------------------------------------- void vtkGlobeSource::AddPoint( double theta, double phi, double radius, vtkPoints* newPoints, vtkFloatArray* newNormals, vtkFloatArray* newLongitudeArray, vtkFloatArray* newLatitudeArray, vtkDoubleArray* newLatLongArray) { double x[3], n[3]; vtkGlobeSource::ComputeGlobePoint(theta, phi, radius, x, n); x[0] -= this->Origin[0]; x[1] -= this->Origin[1]; x[2] -= this->Origin[2]; newPoints->InsertNextPoint(x); newNormals->InsertNextTuple(n); newLongitudeArray->InsertNextValue(theta); newLatitudeArray->InsertNextValue(phi); newLatLongArray->InsertNextValue(phi); newLatLongArray->InsertNextValue(theta); } //---------------------------------------------------------------------------- int vtkGlobeSource::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // I used this to see if the background thread was really // operating asynchronously. //Sleep(2000); // I am going to compute the curtain height based on the level of the // terrain patch. if(this->AutoCalculateCurtainHeight) { this->CurtainHeight = (this->EndLongitude-this->StartLongitude) * this->Radius / 3600.0; } // get the output vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); int i, j; int numPts, numPolys; vtkPoints *newPoints; vtkFloatArray *newLongitudeArray; vtkFloatArray *newLatitudeArray; vtkDoubleArray *newLatLongArray; vtkFloatArray *newNormals; vtkCellArray *newPolys; double phi, theta; vtkIdType pts[4]; // Set things up; allocate memory // numPts = this->LatitudeResolution * this->LongitudeResolution; // creating triangles numPolys = (this->LatitudeResolution-1)*(this->LongitudeResolution-1) * 2; // Add more for curtains. numPts += 2*(this->LatitudeResolution + this->LongitudeResolution); newPoints = vtkPoints::New(); newPoints->Allocate(numPts); newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->Allocate(3*numPts); newNormals->SetName("Normals"); newLongitudeArray = vtkFloatArray::New(); newLongitudeArray->SetNumberOfComponents(1); newLongitudeArray->Allocate(numPts); newLongitudeArray->SetName("Longitude"); newLatitudeArray = vtkFloatArray::New(); newLatitudeArray->SetNumberOfComponents(1); newLatitudeArray->Allocate(numPts); newLatitudeArray->SetName("Latitude"); newLatLongArray = vtkDoubleArray::New(); newLatLongArray->SetNumberOfComponents(2); newLatLongArray->Allocate(2*numPts); newLatLongArray->SetName("LatLong"); newPolys = vtkCellArray::New(); newPolys->Allocate(newPolys->EstimateSize(numPolys, 3)); // Create sphere // double deltaLongitude; double deltaLatitude; // Check data, determine increments, and convert to radians deltaLongitude = (this->EndLongitude - this->StartLongitude) / static_cast<double>(this->LongitudeResolution-1); deltaLatitude = (this->EndLatitude - this->StartLatitude) / static_cast<double>(this->LatitudeResolution-1); // Create points and point data. for (j=0; j<this->LatitudeResolution; j++) { phi = this->StartLatitude + j*deltaLatitude; for (i=0; i < this->LongitudeResolution; i++) { theta = this->StartLongitude + i*deltaLongitude; this->AddPoint(theta, phi, this->Radius, newPoints, newNormals, newLongitudeArray, newLatitudeArray, newLatLongArray); } this->UpdateProgress( 0.10 + 0.50*j/static_cast<float>(this->LatitudeResolution)); } // Create the extra points for the curtains. for (i=0; i < this->LongitudeResolution; i++) { theta = this->StartLongitude + i*deltaLongitude; phi = this->StartLatitude; this->AddPoint(theta, phi, this->Radius-this->CurtainHeight, newPoints, newNormals, newLongitudeArray, newLatitudeArray, newLatLongArray); } for (i=0; i < this->LongitudeResolution; i++) { theta = this->StartLongitude + i*deltaLongitude; phi = this->EndLatitude; this->AddPoint(theta, phi, this->Radius-this->CurtainHeight, newPoints, newNormals, newLongitudeArray, newLatitudeArray, newLatLongArray); } for (j=0; j < this->LatitudeResolution; j++) { theta = this->StartLongitude; phi = this->StartLatitude + j*deltaLatitude; this->AddPoint(theta, phi, this->Radius-this->CurtainHeight, newPoints, newNormals, newLongitudeArray, newLatitudeArray, newLatLongArray); } for (j=0; j < this->LatitudeResolution; j++) { theta = this->EndLongitude; phi = this->StartLatitude + j*deltaLatitude; this->AddPoint(theta, phi, this->Radius-this->CurtainHeight, newPoints, newNormals, newLongitudeArray, newLatitudeArray, newLatLongArray); } // Generate mesh connectivity vtkIdType rowId = 0; vtkIdType cornerId; for (j=1; j < this->LatitudeResolution; ++j) { cornerId = rowId; for (i=1; i < this->LongitudeResolution; ++i) { pts[0] = cornerId; pts[2] = cornerId + this->LongitudeResolution; pts[1] = pts[2] + 1; newPolys->InsertNextCell(3, pts); pts[2] = pts[1]; pts[1] = cornerId + 1; newPolys->InsertNextCell(3, pts); ++cornerId; } rowId += this->LongitudeResolution; this->UpdateProgress( 0.70 + 0.30*j/static_cast<double>(this->LatitudeResolution)); } // Create curtain quads. vtkIdType curtainPointId = this->LongitudeResolution * this->LatitudeResolution; vtkIdType edgeOffset; edgeOffset = 0; for (i=1; i < this->LongitudeResolution; ++i) { pts[0] = edgeOffset + i; // i starts at 1. pts[1] = pts[0] - 1; pts[2] = curtainPointId; pts[3] = curtainPointId + 1; newPolys->InsertNextCell(4, pts); ++curtainPointId; } ++curtainPointId; // Skip 2 to the next edge. edgeOffset = (this->LongitudeResolution)*(this->LatitudeResolution-1); for (i=1; i < this->LongitudeResolution; ++i) { pts[0] = edgeOffset + i - 1; // i starts at 1 pts[1] = pts[0] + 1; pts[2] = curtainPointId + 1; pts[3] = curtainPointId; newPolys->InsertNextCell(4, pts); ++curtainPointId; } ++curtainPointId; edgeOffset = 0; for (j=1; j < this->LatitudeResolution; ++j) { pts[0] = edgeOffset + j*this->LongitudeResolution; pts[1] = pts[0] - this->LongitudeResolution; pts[2] = curtainPointId; pts[3] = curtainPointId + 1; newPolys->InsertNextCell(4, pts); ++curtainPointId; } ++curtainPointId; edgeOffset = (this->LongitudeResolution-1); for (j=1; j < this->LatitudeResolution; ++j) { pts[0] = edgeOffset + (j-1)*this->LongitudeResolution; pts[1] = pts[0] + this->LongitudeResolution; pts[2] = curtainPointId + 1; pts[3] = curtainPointId; newPolys->InsertNextCell(4, pts); ++curtainPointId; } // Update ourselves and release memory // newPoints->Squeeze(); output->SetPoints(newPoints); newPoints->Delete(); newNormals->Squeeze(); output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); newLongitudeArray->Squeeze(); output->GetPointData()->AddArray(newLongitudeArray); newLongitudeArray->Delete(); newLatitudeArray->Squeeze(); output->GetPointData()->AddArray(newLatitudeArray); newLatitudeArray->Delete(); newLatLongArray->Squeeze(); output->GetPointData()->AddArray(newLatLongArray); newLatLongArray->Delete(); newPolys->Squeeze(); output->SetPolys(newPolys); newPolys->Delete(); return 1; } //---------------------------------------------------------------------------- void vtkGlobeSource::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "AutoCalculateCurtainHeight: " << (this->AutoCalculateCurtainHeight ? "ON" : "OFF") << "\n"; os << indent << "CurtainHeight: " << this->CurtainHeight << "\n"; os << indent << "Longitude Resolution: " << this->LongitudeResolution << "\n"; os << indent << "Latitude Resolution: " << this->LatitudeResolution << "\n"; os << indent << "Longitude Start: " << this->StartLongitude << "\n"; os << indent << "Latitude Start: " << this->StartLatitude << "\n"; os << indent << "Longitude End: " << this->EndLongitude << "\n"; os << indent << "Latitude End: " << this->EndLatitude << "\n"; os << indent << "Radius: " << this->Radius << "\n"; os << indent << "Origin: " << this->Origin[0] << "," << this->Origin[1] << "," << this->Origin[2] << "\n"; os << indent << "Quadrilateral Tessellation: " << this->QuadrilateralTessellation << "\n"; }
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r8 push %r9 push %rdx lea addresses_A_ht+0x1b7e6, %r8 nop nop sub %rdx, %rdx movb (%r8), %r13b nop nop xor $21127, %r9 pop %rdx pop %r9 pop %r8 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r14 push %rax push %rbp push %rcx push %rdi // Load lea addresses_RW+0x4237, %rdi nop nop nop nop nop cmp %rax, %rax vmovups (%rdi), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $1, %xmm3, %rbp nop nop nop xor %rax, %rax // Faulty Load lea addresses_WC+0x9566, %rax nop nop nop inc %rdi movb (%rax), %r10b lea oracles, %rcx and $0xff, %r10 shlq $12, %r10 mov (%rcx,%r10,1), %r10 pop %rdi pop %rcx pop %rbp pop %rax pop %r14 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_WC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A049451: Twice second pentagonal numbers. ; 0,4,14,30,52,80,114,154,200,252,310,374,444,520,602,690,784,884,990,1102,1220,1344,1474,1610,1752,1900,2054,2214,2380,2552,2730,2914,3104,3300,3502,3710,3924,4144,4370,4602,4840,5084,5334,5590,5852,6120,6394,6674,6960,7252,7550,7854,8164,8480,8802,9130,9464,9804,10150,10502,10860,11224,11594,11970,12352,12740,13134,13534,13940,14352,14770,15194,15624,16060,16502,16950,17404,17864,18330,18802,19280,19764,20254,20750,21252,21760,22274,22794,23320,23852,24390,24934,25484,26040,26602,27170,27744 mov $1,3 mul $1,$0 mul $1,$0 add $1,$0 mov $0,$1
//////////////////////////////////////////////////////////////////////////////// // HeightField.cpp // Height field support for our mech sim // Copyright Bjoern Ganster 2007-2008 //////////////////////////////////////////////////////////////////////////////// #include "Heightfield.h" //////////////////////////////////////////////////////////////////////////////// // Constructor, destructor HeightField::HeightField(size_t xsize, size_t ysize) : RenderableObject (HeightFieldID, NULL, "Heightfield"), m_sizex (xsize), m_sizey (ysize), m_mesh (NULL) { heights.resize(m_sizex*m_sizey); for (size_t y = 0; y < m_sizey; y++) for (size_t x = 0; x < m_sizex; x++) { setHeight (x, y, 0); } } HeightField::~HeightField() { delete m_mesh; } //////////////////////////////////////////////////////////////////////////////// // Create random height field void HeightField::createHeightField(int mountCount, double mountHeight, double mountSlope, double noise, size_t smoothTimes) { /*addPeaks (0.5*mountHeight, mountHeight, 0, 0, m_sizex, m_sizey, mountCount); smoothen (0, 0, m_sizex, m_sizey, 3); propagateValues(mountSlope); addNoise (0, noise);*/ randomize(); addPeaks(0.25*mountHeight, mountHeight, 0, 0, m_sizex, m_sizey, mountCount); propagateValues(mountSlope); addNoise(0, noise); smoothen (0, 0, m_sizex-1, m_sizey-1, 5, smoothTimes); createMesh(); } //////////////////////////////////////////////////////////////////////////////// // Add noise to entire height field void HeightField::addNoise (double min, double max) { for (size_t x = 1; x < m_sizex-1; x++) for (size_t y = 1; y < m_sizey-1; y++) { double oldH = getHeight(x, y); double diff = min+frandom()*(max-min); setHeight(x, y, oldH + diff); } } //////////////////////////////////////////////////////////////////////////////// // Add peaks to restricted area void HeightField::addPeaks (double min, double max, size_t x1, size_t y1, size_t x2, size_t y2, size_t count) { for (size_t i = 0; i < count; i++) { size_t x = (size_t) random ((int) x1, (int) x2); size_t y = (size_t) random ((int) y1, (int) y2); double h = frandom (min, max); setHeight (x, y, h); } } //////////////////////////////////////////////////////////////////////////////// // Propagate height values void HeightField::propagateValues(double mountSlope) { // For every height field cell, subtract mountSlope from the highest // neighbour to find this cell's height int passes = 100; //2*mountHeight/mountSlope; for (int i = 0; i < passes; i++) { for (size_t x = 1; x < m_sizex-1; x++) for (size_t y = 1; y < m_sizey-1; y++) { double max = getHeight(x,y); bool changed = false; for (int dx = -1; dx < 2; dx++) for (int dy = -1; dy < 2; dy++) { double h = getHeight(x+dx, y+dy); if (h > max) { max = h; changed = true; } } if (changed) setHeight(x, y, max-mountSlope); } } } //////////////////////////////////////////////////////////////////////////////// // Smoothen landscape void HeightField::smoothen (size_t x1, size_t y1, size_t x2, size_t y2, size_t range, size_t times) { for (size_t i = 0; i < times; i++) { printf("%i/%i\n", i, times); for (size_t y = 0; y < m_sizey; y++) { for (size_t x = 0; x < m_sizex; x++) { double sum = 0; //size_t count = 0; int sx = bgmax((int) (x-range), 0); int sy = bgmax((int) (y-range), 0); int ex = bgmin (m_sizex-1, x+range); int ey = bgmin (m_sizey-1, y+range); for (int ry = sy; ry <= ey; ry++) { for (int rx = sx; rx <= ex; rx++) { sum += getHeight (rx, ry); //count++; } } size_t count = (ex-sx+1)*(ey-sy+1); setHeight (x, y, sum / count); } } } } //////////////////////////////////////////////////////////////////////////////// // Create mesh void HeightField::createMesh() { m_mesh = new Mesh2(); m_mesh->color = Color (1, 1, 1); for (size_t y = 0; y < m_sizey; y++) for (size_t x = 0; x < m_sizex; x++) { Point3D p (x, getHeight (x, y), y); Point3D n1, n2, n; double h = getHeight (x, y); if (x == 0) n1 = Point3D (1, h+getHeight(x-1, y), 0); else if (x == m_sizex-1) n1 = Point3D (1, h-getHeight(x+1, y), 0); else if (x > 0 && x < m_sizex-1) { n1 = Point3D (2, getHeight(x-1, y)-getHeight(x+1, y), 0); } if (y == 0) n2 = Point3D (0, h+getHeight(x, y-1), 1); else if (y == m_sizey-1) n2 = Point3D (0, h-getHeight(x, y+1), 1); else if (y > 0 && y < m_sizey-1) { n2 = Point3D (0, getHeight(x, y-1)-getHeight(x, y+1), 2); } n1.unitLength(); n2.unitLength(); n = n2.crossMultiply(n1); n.unitLength(); //n = Point3D(0, 1, 0); m_mesh->addPoint (p, n, x % 2, y%2); //m_mesh->addPoint (p.x, p.y, p.z); //m_mesh->addNormal (n.x, n.y, n.z); //m_mesh->addTextureCoords(x % 2, y%2); } Point3D n (0, 1, 0); for (size_t y = 0; y < m_sizey-1; y++) for (size_t x = 0; x < m_sizex-1; x++) { size_t i = x+m_sizex*y; //MeshPolygon* poly = m_mesh->addQuad(i, i+1, i+m_sizex+1, i+m_sizex); //m_mesh->getNormal(i, poly->normal); //poly->PerVertexLighting = false; //poly->color = Color (0.5, 0.5, 0.5); } m_mesh->color = Color (0.5, 0.5, 0.5); /*Texture* material = new Texture(); if (material->loadFromFile ("Material\\grass1.bmp")) m_mesh->setTexture (material); else delete material;*/ } //////////////////////////////////////////////////////////////////////////////// // Render void HeightField::renderSelf() { m_mesh->renderSelf(); /*glBegin(GL_QUADS); for (size_t x = 0; x < m_sizex-1; x++) for (size_t y = 0; y < m_sizey-1; y++) { double h = getHeight(x,y); glColor3d(h/50.0, h/50.0, h/50.0); glVertex3d (x, h, y); h = getHeight(x+1, y); glColor3d(h/50.0, h/50.0, h/50.0); glVertex3d (x+1, h, y); h = getHeight(x+1,y+1); glColor3d(h/50.0, h/50.0, h/50.0); glVertex3d (x+1, h, y+1); h = getHeight(x,y+1); glColor3d(h/50.0, h/50.0, h/50.0); glVertex3d (x, h, y+1); } glEnd();*/ } //////////////////////////////////////////////////////////////////////////////// // Render double HeightField::getHeight (size_t x, size_t y) { if (x < m_sizex && y < m_sizey) return heights[m_sizex*y+x]; else return 0.0; } double HeightField::getHeightD (double x, double y) { int x1 = (int) x; int x2 = x1+1; int y1 = (int) y; int y2 = y1+1; if (x1 >= 0 && x2 < (int) m_sizex && y1 >= 0 && y2 < (int) m_sizey) { double dx = x - x1; double dy = y - y1; double hy1 = dx * heights[m_sizex*y1+x2] + (1.0 - dx) * heights[m_sizex*y1+x1]; double hy2 = dx * heights[m_sizex*y2+x2] + (1.0 - dx) * heights[m_sizex*y2+x1]; return dy * hy2 + (1.0 - dy) * hy1; } else return 0.0; }
; =============================================================== ; Dec 2013 ; =============================================================== ; ; int ffsl(long i) ; ; Return bit position of least significant bit set. Bit ; positions are numbered 1-32 with 0 returned if no bits ; are set. ; ; =============================================================== SECTION code_string PUBLIC asm_ffsl EXTERN asm0_ffs, asm1_ffs, asm2_ffs asm_ffsl: ; enter : dehl = long ; ; exit : hl = bit pos or 0 if no set bits ; carry set if set bit present ; ; uses : af, hl ld a,l or a jp nz, asm0_ffs ld a,h or a jp nz, asm1_ffs ld a,e or a jr nz, bits_17_24 ld a,d or a ret z bits_25_32: ld l,25 jp asm2_ffs bits_17_24: ld l,17 jp asm2_ffs
; CRT0 stub for the Old School Computer Architecture (FLOS) ; ; Stefano Bodrato - Jul. 2011 ; ; ; EXTRA OPTIONS: ; ; At C source level: ; #pragma output osca_bank=(0..14) set the memory bank for locations > 32768 before loading program ; #pragma output osca_stack=<value> put the stack in a differen place, i.e. 32767 ; #pragma output nostreams - No stdio disc files ; #pragma output noredir - do not insert the file redirection option while parsing the ; command line arguments (useless if "nostreams" is set) ; ; At compile time: ; -zorg=<location> parameter permits to specify the program position ; ; $Id: osca_crt0.asm,v 1.27 2015/01/21 07:05:00 stefano Exp $ ; MODULE osca_crt0 ; ; Initially include the zcc_opt.def file to find out lots of lovely ; information about what we should do.. ; INCLUDE "zcc_opt.def" ; No matter what set up we have, main is always, always external to ; this file EXTERN _main PUBLIC snd_tick PUBLIC bit_irqstatus ; current irq status when DI is necessary ; ; Some variables which are needed for both app and basic startup ; PUBLIC cleanup PUBLIC l_dcal ; Integer rnd seed PUBLIC _std_seed ; vprintf is internal to this file so we only ever include one of the set ; of routines PUBLIC _vfprintf ;Exit variables PUBLIC exitsp PUBLIC exitcount ;For stdin, stdout, stder PUBLIC __sgoioblk PUBLIC heaplast ;Near malloc heap variables PUBLIC heapblocks ; Graphics stuff PUBLIC base_graphics PUBLIC coords ; FLOS system variables PUBLIC sector_lba0 ; keep this byte order PUBLIC sector_lba1 PUBLIC sector_lba2 PUBLIC sector_lba3 PUBLIC a_store1 PUBLIC bc_store1 PUBLIC de_store1 PUBLIC hl_store1 PUBLIC a_store2 PUBLIC bc_store2 PUBLIC de_store2 PUBLIC hl_store2 PUBLIC storeix PUBLIC storeiy PUBLIC storesp PUBLIC storepc PUBLIC storef PUBLIC store_registers PUBLIC com_start_addr PUBLIC cursor_y ;keep this byte order PUBLIC cursor_x ;(allows read as word with y=LSB) PUBLIC current_scancode PUBLIC current_asciicode PUBLIC FRAMES ;-------- ; OSCA / FLOS specific definitions ;-------- INCLUDE "flos.def" INCLUDE "osca.def" ; Now, getting to the real stuff now! ;-------- ; Set an origin for the application (-zorg=) default to $5000 ;-------- IF !myzorg defc myzorg = $5000 ENDIF IF ((myzorg = $5000) | (!DEFINED_osca_bank)) org myzorg ELSE ; optional Program Location File Header org myzorg defb $ed defb $00 jr start defw myzorg IF DEFINED_osca_bank defb osca_bank ELSE defb 0 ENDIF defb $00 ; control byte: 1=truncate basing on next 3 bytes ;defw 0 ; Load length 15:0 only needed if truncate flag is set ;defb 0 ; Load length ..bits 23:16, only needed if truncate flag is set ENDIF start: di ;push hl ;pop bc ld b,h ld c,l ld hl,0 add hl,sp ld (start1+1),hl IF (!DEFINED_osca_stack) ld sp,-64 ELSE ld sp,osca_stack ENDIF ;ld sp,$7FFF ld (exitsp),sp push bc ; keep ptr to arg list ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "amalloc.def" ENDIF IF (!DEFINED_osca_notimer) ld hl,(FLOS_irq_vector) ; The label "irq_vector" = $A01 (contained in equates file) ld (original_irq_vector),hl ; Store the original FLOS vecotr for restoration later. ld hl,my_custom_irq_handler ld (FLOS_irq_vector),hl ld a,@10000111 ; Enable keyboard, mouse and timer interrupts out (sys_irq_enable),a ld a,250 neg out (sys_timer),a ld a,@00000100 out (sys_clear_irq_flags),a ; Clear the timer IRQ flag ELSE ld b,255 .v_srand_loop ld hl,FLOSvarsaddr add (hl) ld (FRAMES),a inc hl djnz v_srand_loop ENDIF ei IF !DEFINED_nostreams IF DEFINED_ANSIstdio ; Set up the std* stuff so we can be called again ld hl,__sgoioblk+2 ld (hl),19 ;stdin ld hl,__sgoioblk+6 ld (hl),21 ;stdout ld hl,__sgoioblk+10 ld (hl),21 ;stderr ENDIF ENDIF ; Push pointers to argv[n] onto the stack now ; We must start from the end ld hl,0 ; NULL pointer at end, just in case ld b,h ; parameter counter ld c,h ; character counter ex (sp),hl ; retrieve ptr to argument list / store NULL ptr ld a,(hl) and a jr z,argv_done dec hl find_end: inc hl inc c ld a,(hl) and a jr nz,find_end dec hl ; now HL points to the end of command line ; and C holds the length of args buffer ; Try to find the end of the arguments argv_loop_1: ld a,(hl) cp ' ' jr nz,argv_loop_2 ld (hl),0 dec hl dec c jr nz,argv_loop_1 ; We've located the end of the last argument, try to find the start argv_loop_2: ld a,(hl) cp ' ' jr nz,argv_loop_3 ;ld (hl),0 inc hl IF !DEFINED_noredir IF !DEFINED_nostreams IF DEFINED_ANSIstdio EXTERN freopen xor a add b jr nz,no_redir_stdout ld a,(hl) cp '>' jr nz,no_redir_stdout push hl inc hl cp (hl) dec hl ld de,redir_fopen_flag ; "a" or "w" jr nz,noappendb ld a,'a' ld (de),a inc hl noappendb: inc hl push bc push hl ; file name ptr push de ld de,__sgoioblk+4 ; file struct for stdout push de call freopen pop de pop de pop hl pop bc pop hl dec hl jr argv_zloop no_redir_stdout: ld a,(hl) cp '<' jr nz,no_redir_stdin push hl inc hl ld de,redir_fopen_flagr push bc push hl ; file name ptr push de ld de,__sgoioblk ; file struct for stdin push de call freopen pop de pop de pop hl pop bc pop hl dec hl jr argv_zloop no_redir_stdin: ENDIF ENDIF ENDIF push hl inc b dec hl ; skip extra blanks argv_zloop: ld (hl),0 dec c jr z,argv_done dec hl ld a,(hl) cp ' ' jr z,argv_zloop inc c inc hl argv_loop_3: dec hl dec c jr nz,argv_loop_2 argv_done: ld hl,end ;name of program (NULL) push hl inc b ld hl,0 add hl,sp ;address of argv ld c,b ld b,0 push bc ;argc push hl ;argv call _main ;Call user code pop bc ;kill argv pop bc ;kill argc cleanup: ; ; Deallocate memory which has been allocated here! ; push hl IF !DEFINED_nostreams IF DEFINED_ANSIstdio EXTERN closeall call closeall ENDIF ENDIF ; kjt_flos_display restores the text mode but makes the screen flicker ; if it is in text mode already ; ;call $10c4 ; kjt_flos_display (added in v547) IF (!DEFINED_osca_notimer) di ld hl,(original_irq_vector) ld (FLOS_irq_vector),hl ld a,@10000011 ; Enable keyboard and mouse interrupts only out (sys_irq_enable),a ei ENDIF pop hl start1: ld sp,0 xor a or h ; ATM we are not mamaging the 'spawn' exception jr nz,cmdok ld l,a cmdok: ld a,l ; return code (lowest byte only) and a ; set Z flag to set the eventual error condition ;xor a ; (set A and flags for RESULT=OK) ret l_dcal: jp (hl) IF (!DEFINED_osca_notimer) ; ---------------------------------- ; Custom Interrupt handlers ; ---------------------------------- my_custom_irq_handler: push af in a,(sys_irq_ps2_flags) bit 0,a call nz,kjt_keyboard_irq_code ; Kernal keyboard irq handler bit 1,a call nz,kjt_mouse_irq_code ; Kernal mouse irq handler bit 2,a call nz,my_timer_irq_code ; User's timer irq handler pop af ei reti my_timer_irq_code: push af ; (do whatever, push/pop registers!) push hl ; ld hl,(frames_pre) ; inc (hl) ; ld a,(hl) ; bit 4,a ; jr nz,timer_irq_count_done ld hl,(FRAMES) inc hl ld (FRAMES),hl ;;ld (palette),hl ; testing purposes ld a,h or l jr nz,timer_irq_count_done ld hl,(FRAMES+2) inc hl ld (FRAMES+2),hl timer_irq_count_done: ld a,@00000100 out (sys_clear_irq_flags),a ; Clear the timer IRQ flag pop hl pop af ret ENDIF original_irq_vector: defw 0 ;frames_pre: ; ; defb 0 FRAMES: defw 0 defw 0 ; Now, define some values for stdin, stdout, stderr __sgoioblk: IF DEFINED_ANSIstdio INCLUDE "stdio_fp.asm" ELSE defw -11,-12,-10 ENDIF ; Now, which of the vfprintf routines do we need? _vfprintf: IF DEFINED_floatstdio EXTERN vfprintf_fp jp vfprintf_fp ELSE IF DEFINED_complexstdio EXTERN vfprintf_comp jp vfprintf_comp ELSE IF DEFINED_ministdio EXTERN vfprintf_mini jp vfprintf_mini ENDIF ENDIF ENDIF ;Seed for integer rand() routines _std_seed: defw 0 ;Atexit routine exitsp: defw 0 exitcount: defb 0 ; Heap stuff heaplast: defw 0 heapblocks: defw 0 IF DEFINED_USING_amalloc EXTERN ASMTAIL PUBLIC _heap ; The heap pointer will be wiped at startup, ; but first its value (based on ASMTAIL) ; will be kept for sbrk() to setup the malloc area _heap: defw ASMTAIL ; Location of the last program byte defw 0 ENDIF ; mem stuff base_graphics: defw $2000 coords: defw 0 IF DEFINED_NEED1bitsound snd_tick: defb 0 ; Sound variable bit_irqstatus: defw 0 ENDIF ;-------------------------------------------------------------------------------------------- ; ; OS_variables location as defined in system_equates.asm ; FLOSv582 sets it to $B00, hopefully it won't change much ; but we keep the option for making it dynamic ; ;-------------------------------------------------------------------------------------------- IF !DEFINED_FLOSvarsaddr defc FLOSvarsaddr = $B00 ENDIF ;-------------------------------------------------------------------------------------------- DEFVARS FLOSvarsaddr { sector_lba0 ds.b 1 ; keep this byte order sector_lba1 ds.b 1 sector_lba2 ds.b 1 sector_lba3 ds.b 1 a_store1 ds.b 1 bc_store1 ds.b 2 de_store1 ds.b 2 hl_store1 ds.b 2 a_store2 ds.b 1 bc_store2 ds.b 2 de_store2 ds.b 2 hl_store2 ds.b 2 storeix ds.b 2 storeiy ds.b 2 storesp ds.b 2 storepc ds.b 2 storef ds.b 1 store_registers ds.b 1 com_start_addr ds.w 1 cursor_y ds.b 1 ;keep this byte order cursor_x ds.b 1 ;(allows read as word with y=LSB) current_scancode ds.b 1 current_asciicode ds.b 1 ; The other variable positions depend on the FLOS version ; .. } ;-------------------------------------------------------------------------------------------- ; Signature defm "Small C+ OSCA" end: defb 0 ;All the float stuff is kept in a different file...for ease of altering! ;It will eventually be integrated into the library ; ;Here we have a minor (minor!) problem, we've no idea if we need the ;float package if this is separated from main (we had this problem before ;but it wasn't critical..so, now we will have to read in a file from ;the directory (this will be produced by zcc) which tells us if we need ;the floatpackage, and if so what it is..kludgey, but it might just work! ; ;Brainwave time! The zcc_opt file could actually be written by the ;compiler as it goes through the modules, appending as necessary - this ;way we only include the package if we *really* need it! IF NEED_floatpack INCLUDE "float.asm" ;seed for random number generator - not used yet.. fp_seed: defb $80,$80,0,0,0,0 ;Floating point registers... extra: defs 6 fa: defs 6 fasign: defb 0 ENDIF IF !DEFINED_noredir IF !DEFINED_nostreams IF DEFINED_ANSIstdio redir_fopen_flag: defb 'w' defb 0 redir_fopen_flagr: defb 'r' defb 0 ENDIF ENDIF ENDIF ; SD CARD interface IF DEFINED_NEED_SDCARD PUBLIC card_select PUBLIC sd_card_info PUBLIC sector_buffer_loc ; Keep the following 2 bytes in the right order (1-card_select, 2-sd_card_info) !!! card_select: defb 0 ; Currently selected MMC/SD slot sd_card_info: defb 0 ; Card type flags.. sector_buffer_loc: defw sector_buffer sector_buffer: defs 513 ENDIF
public _levels public _tileAttr section RODATA_0 _levels: include "levels.inc" section RODATA_5 _tileAttr: binary "attrib.dat"
/******************************Module*Header*******************************\ * Module Name: CPrinting.cpp * * This file contains the code to support the functionality test harness * for GDI+. This includes menu options and calling the appropriate * functions for execution. * * Created: 05-May-2000 - Jeff Vezina [t-jfvez] * * Copyright (c) 2000 Microsoft Corporation * \**************************************************************************/ #include "CPrinting.h" CPrinting::CPrinting(BOOL bRegression) { strcpy(m_szName,"Printing"); m_bRegression=bRegression; } CPrinting::~CPrinting() { } VOID CPrinting::TestTextPrinting(Graphics *g) { Font f(L"Arial", 60); FontFamily ff(L"Arial"); RectF rectf1( 20, 0, 300, 200); RectF rectf2( 20, 300, 300, 200); RectF rectf3(220, 0, 300, 200); RectF rectf4(220, 300, 300, 200); Color color1(0xff, 100, 0, 200); Color color2(128, 100, 0, 200); Color color3(0xff, 0, 100, 200); Color color4(128, 0, 100, 0); SolidBrush brush1(color1); SolidBrush brush2(color2); LinearGradientBrush brush3(rectf3, color3, color4, LinearGradientModeForwardDiagonal); g->DrawString(L"Color1", 6, &f, rectf1, NULL, &brush1); g->DrawString(L"Color2", 6, &f, rectf2, NULL, &brush2); g->DrawString(L"Color3", 6, &f, rectf3, NULL, &brush3); } VOID CPrinting::TestPerfPrinting(Graphics *g) { /* Analyze file size based on output of StretchDIBits. The claim by DonC is that when we StretchDIBits a subrectangle of a large DIB, it sends the large DIB to the printer and then clips to the subrectangle. How stupid, but it apparently does on Win98 postscript. So this is the results of my test: 1000x1000 DIB (32bpp). I blitted two chunks: This is 200x200 source rectangle (part of a band): 04/27/2000 03:00p 22,198 nt5pcl 04/27/2000 03:02p 268,860 nt5ps // Level 1 ps 04/27/2000 02:47p 17,488 w98pcl 04/27/2000 02:47p 6,207,459 w98ps // Level 1 ps This is 1000x200 source rectangle (an entire band): 04/27/2000 03:06p 80,291 nt5pcl 04/27/2000 03:06p 1,266,123 nt5ps // Level 1 ps 04/27/2000 02:51p 60,210 w98pcl 04/27/2000 02:52p 6,207,457 w98ps // Level 1 ps Also compared 32bpp vs. 24bpp DIB. The results were contradictary: 04/27/2000 03:59p <DIR> .. 04/27/2000 03:06p 80,291 nt5pcl 04/27/2000 03:51p 122,881 nt5pcl24 04/27/2000 03:06p 1,266,123 nt5ps 04/27/2000 03:51p 1,262,332 nt5ps24 04/27/2000 02:51p 60,210 w98pcl 04/27/2000 03:39p 101,216 w98pcl24 04/27/2000 02:52p 6,207,457 w98ps 04/27/2000 03:39p 6,207,457 w98ps24 */ if (1) { BITMAPINFO bi; ZeroMemory(&bi, sizeof(BITMAPINFO)); bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = 0; bi.bmiHeader.biWidth = 1000; bi.bmiHeader.biHeight = 1000; bi.bmiHeader.biBitCount = 32; ARGB* Bits = (ARGB*)malloc(bi.bmiHeader.biWidth * bi.bmiHeader.biHeight * sizeof(ARGB)); ARGB* Ptr = Bits; // To eliminate RLE/ASCII85 encoding, set to random bits for (INT i=0; i<bi.bmiHeader.biHeight; i++) for (INT j=0; j<bi.bmiHeader.biWidth; j++) { *Ptr++ = (ARGB)(i | (j<<16)); } HDC hdc = g->GetHDC(); StretchDIBits(hdc, 0, 0, 1000, 200, 0, 700, 1000, 200, Bits, &bi, DIB_RGB_COLORS, SRCCOPY); g->ReleaseHDC(hdc); free(Bits); } } void CPrinting::Draw(Graphics *g) { // TestPerfPrinting(g); // TestTextPrinting(g); TestBug104604(g); if (0) { #if 1 HDC hdc = g->GetHDC(); HDC bufHdc = CreateCompatibleDC(hdc); HBITMAP BufDIB = NULL; ARGB* argb; struct { BITMAPINFO bitmapInfo; RGBQUAD rgbQuad[4]; } bmi; INT width=100; INT height=100; ZeroMemory(&bmi.bitmapInfo, sizeof(bmi.bitmapInfo)); bmi.bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bitmapInfo.bmiHeader.biWidth = width; bmi.bitmapInfo.bmiHeader.biHeight = -height; bmi.bitmapInfo.bmiHeader.biPlanes = 1; bmi.bitmapInfo.bmiHeader.biBitCount = 24; bmi.bitmapInfo.bmiHeader.biCompression = BI_RGB; RGBQUAD red = { 0, 0, 0xFF, 0}; // red RGBQUAD green = { 0, 0xFF, 0, 0}; // green RGBQUAD blue = { 0xFF, 0, 0, 0}; // blue bmi.bitmapInfo.bmiColors[0] = red; bmi.bitmapInfo.bmiColors[1] = green; bmi.bitmapInfo.bmiColors[2] = blue; // if assert fails, then we didn't clean up properly by calling End() // ASSERT(BufDIB == NULL); BufDIB = CreateDIBSection(bufHdc, &bmi.bitmapInfo, DIB_RGB_COLORS, (VOID**) &argb, NULL, 0); // ASSERT(BufDIB != NULL); memset(argb, 0, 3*width*height); INT i,j; BYTE* tempptr = (BYTE*)argb; for (i=0; i<height; i++) { for (j=0; j<width; j++) { if (i==j) { *tempptr++ = 0xFF; *tempptr++ = 0x80; *tempptr++ = 0x40; } else tempptr += 3; } if ((((ULONG_PTR)tempptr) % 4) != 0) tempptr += 4-(((ULONG_PTR)tempptr) % 4); } INT mode = GetMapMode(bufHdc); // WARNING(("MapMode printing = %08x\n", mode)); SelectObject(bufHdc, BufDIB); /* for (i=0; i<100; i++) { int result = StretchBlt(hdc, 0, i*2, 2*width, 2, bufHdc, 0, i, width, 0, SRCCOPY); INT joke = GetLastError(); joke++; } */ // int result = StretchBlt(hdc, 0, 0, 50, 50, bufHdc, 0, 0, 50, 50, SRCCOPY); for (i=0; i<50; i++) { int result = StretchBlt(hdc, 0, 100+i*2, 100, 1, bufHdc, 0, i*2, 100, 1, SRCCOPY); } // int result = StretchBlt(hdc, 0, 0, 200, 200, bufHdc, 0, 0, 100, 100, SRCCOPY); // ASSERT(result != 0); g->ReleaseHDC(hdc); DeleteDC(bufHdc); DeleteObject(BufDIB); #endif #if 1 REAL widthF = 4; // Pen width Color redColor(255, 0, 0); SolidBrush brush1(Color(0xFF,0xFF,0,0)); SolidBrush brush2(Color(0x80,0x80,0,0)); SolidBrush brush3(Color(0xFF,0xFF,0,0)); SolidBrush brush4(Color(0x80,0x80,0,0)); Color colors1[] = { Color(0xFF,0xFF,0,0), Color(0xFF,0,0xFF,0), Color(0xFF,0,0,0xFF), Color(0xFF,0x80,0x80,0x80) }; Color colors2[] = { Color(0x80,0xFF,0,0), Color(0x80,0,0xFF,0), Color(0x80,0,0,0xFF), Color(0x80,0x80,0x80,0x80) }; //SolidBrush brush3(colors1[2]); //SolidBrush brush4(colors2[2]); // Default Wrap: Clamp to small rectangle // RectangleGradientBrush brush3(Rect(125,275,50,50), // &colors1[0]);//, //WrapModeClamp); // Default Wrap: Clamp to // RectangleGradientBrush brush4(Rect(250,250,100,100), // &colors2[0]);//, //WrapModeClamp); g->SetPageScale(1.2f); // no path clip g->FillRectangle(&brush1, Rect(0,25,500,50)); // tests solid + opaque combinations + path clip only g->FillEllipse(&brush1, Rect(100,100,100,100)); g->FillEllipse(&brush2, Rect(300,100,100,100)); g->FillEllipse(&brush3, Rect(100,250,100,100)); g->FillEllipse(&brush4, Rect(300,250,100,100)); // tests visible clip + path clip Region origRegion; g->GetClip(&origRegion); Region *newRegion = new Region(); newRegion->MakeInfinite(); //Rect horzRect(150, 600, 500, 25); //Rect vertRect(150, 600, 25, 500); Rect horzRect(100, 400, 500, 25); Rect vertRect(100, 400, 25, 500); Region *horzRegion = new Region(horzRect); Region *vertRegion = new Region(vertRect); for (i = 0; i < 10; i++) { newRegion->Xor(horzRegion); newRegion->Xor(vertRegion); horzRegion->Translate(0, 50); vertRegion->Translate(50, 0); } delete horzRegion; delete vertRegion; // Set grid clipping g->SetClip(newRegion); // set wrap mode from Clamp to Tile // brush3.SetWrapMode(WrapModeTile); // brush4.SetWrapMode(WrapModeTile); // tests solid + opaque combinations + visible clip + path clip only g->FillEllipse(&brush1, Rect(100,400,100,100)); g->FillEllipse(&brush2, Rect(300,400,100,100)); g->FillEllipse(&brush3, Rect(100,550,100,100)); g->FillEllipse(&brush4, Rect(300,550,100,100)); // restore original clip region g->SetClip(&origRegion); delete newRegion; // Test case which stretches beyond GetTightBounds() DrawBounds API PointF pts[8]; pts[0].X = 2150.0f; pts[0].Y = 2928.03f; pts[1].X = 1950.0f; pts[1].Y = 3205.47f; pts[2].X = 1750.0f; pts[2].Y = 2650.58f; pts[3].X = 1550.0f; pts[3].Y = 2928.03f; pts[4].X = 1550.0f; pts[4].Y = 3371.97f; pts[5].X = 1750.0f; pts[5].Y = 3094.53f; pts[6].X = 1950.0f; pts[6].Y = 3649.42f; pts[7].X = 2150.0f; pts[7].Y = 3371.97f; BYTE types[8] = { 1, 3, 3, 3, 1, 3, 3, 0x83 }; Bitmap *bitmap = new Bitmap(L"winnt256.bmp"); // Test g->DrawImage if (bitmap && bitmap->GetLastStatus() == Ok) { int i; for (i=0; i<8; i++) { pts[i].X = pts[i].X / 8.0f; pts[i].Y = pts[i].Y / 8.0f; } TextureBrush textureBrush(bitmap, WrapModeTile); GraphicsPath path(&pts[0], &types[0], 8); g->FillPath(&textureBrush, &path); // Text using WrapModeClamp for (i=0; i<8; i++) pts[i].X += 200.0f; TextureBrush textureBrush2(bitmap, WrapModeClamp); GraphicsPath path2(&pts[0], &types[0], 8); g->FillPath(&textureBrush2, &path2); delete bitmap; } /* Font font(50.0f * g->GetDpiY() / 72.0f, // emSize FontFamily(L"Arial"), // faceName, 0, (Unit)g->GetPageUnit() ); // will fail on Win9x LPWSTR str = L"Printing Support is COOL"; GpRectF layoutRect1(200, 200, 300, 100); GpRectF layoutRect2(200, 400, 300, 100); GpRectF layoutRect3(200, 600, 300, 100); GpRectF layoutRect4(200, 800, 300, 100); INT len = 0; LPWSTR strPtr = str; while (*str != '\0') { len++; str++; } StringFormat format1 = StringFormatDirectionRightToLeft; StringFormat format2 = StringFormatDirectionVertical; StringFormat format3 = StringFormatDirectionRightToLeft; StringFormat format4 = StringFormatDirectionVertical; // Test DDI: SolidText (Brush 1 or 2) g->DrawString(strPtr, len, &font, &layoutRect1, &format1, &brush1); g->DrawString(strPtr, len, &font, &layoutRect2, &format2, &brush2); // Test DDI: BrushText (Brush 3 or 4) g->DrawString(strPtr, len, &font, &layoutRect3, &format3, &brush3); g->DrawString(strPtr, len, &font, &layoutRect4, &format4, &brush4); // Test DDI: StrokePath // Test DDI: FillRegion */ #endif } } // Try this from Nolan Lettelier VOID CPrinting::TestNolan1(Graphics *g) { /* TestInit(hdc); Graphics *pg = Graphics::FromHDC(hdc); if (pg == NULL) { assert(0); return false; } int sts; int alpha = 255, red = 255, green = 0, blue = 255; Color c1(alpha,red,green,blue); Point p1(150,150), p2(300,300); Color c2(255, 255-red, 255-green, 255-blue); LineGradientBrush gb(p1, p2, c1, c2); Pen p(&gb, 50.0); sts = pg->DrawLine(&p,0, 0, 500, 500); assert(sts == Ok); sts = pg->DrawLine(&p,0,100, 500, 100); assert(sts == Ok); sts = pg->DrawLine(&p,0,350, 500, 350); assert(sts == Ok); sts = pg->DrawLine(&p,0,500, 500, 0); assert(sts == Ok); delete pg; return true; */ } VOID CPrinting::TestNolan2(Graphics *g) { /* CString lineText("NolanRules"); Graphics *pg = g; if (pg == NULL) { assert(0); return false; } Unit origUnit = pg->GetPageUnit(); Matrix origXform; pg->GetTransform(&origXform); pg->SetPageUnit(UnitInch); pg->ScaleTransform(8.0f/1000.0f, 8.0f/1000.0f); Status sts; int alpha = 255, red = 255, green = 0, blue = 255; RectF rg(150,150,300,175); Color c1(alpha,red,green,blue); Color c2(255, 255-red, 255-green, 255-blue); LineGradientBrush gb(rg, c1, c2, LineGradientModeVertical); WCHAR *famName[] = { L"Comic Sans MS" , L"Courier New" , L"Times New Roman" , L"Tahoma" , L"Arial" , L"Lucida Console" , L"Garamond" , L"Palatino" , L"Univers" , L"Marigold" , L"Albertus" , L"Antique Olive" }; int famCount = sizeof(famName) / sizeof(WCHAR *); WCHAR *s = L"GDI+ GradientFill"; RectF r(30,30,0,0); StringFormat sf(0); FontFamily *pFontFamily; float lineHeight = 60; int i; for (i = 0, r.Y = 30 ; r.Y < 800 ; r.Y += lineHeight, ++i) { pFontFamily = new FontFamily(famName[i % famCount]); while (pFontFamily == NULL || pFontFamily->GetLastStatus() != Ok) { delete pFontFamily; ++i; pFontFamily = new FontFamily(famName[i % famCount]); } Font f(*pFontFamily, lineHeight * 5 / 6, 0, UnitPoint); sts = pg->DrawString(s, wcslen(s), &f, &r, &sf, &gb); // CHECK_RESULT(sts, "TestGradientLinearVertical2 DrawString"); delete pFontFamily; } delete pg; pg->SetPageUnit(origUnit); pg->SetTransform(&origXform); return true; */ } // TestGradientLinearVertical2 VOID CPrinting::TestBug104604(Graphics *g) { BYTE* memory = new BYTE[8*8*3]; // checkerboard pattern for (INT i=0; i<8*8; i += 3) { if (i%2) { memory[i] = 0xff; memory[i+1] = 0; memory[i+2] = 0; } else { memory[i] = 0; memory[i+1] = 0; memory[i+2] = 0xff; } } Bitmap bitmap(8,8, 8*3, PixelFormat24bppRGB, memory); TextureBrush brush(&bitmap); g->SetCompositingMode(CompositingModeSourceCopy); g->FillRectangle(&brush, 0, 0, 100, 100); }
/*---------------------------------------------------------------------------*\ Copyright (C) 2015 - 2016 Applied CCM ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Description A TVD property staisfying linear upwind scheme based on the UMIST limiter to prevent unwanted oscillations. The limiter corresponds to the symmetric QUICK limiter. References [1] "A Pressure-Velocity Solution Strategy for Compressible Flow and its Application to Shock-Boundary Layer interaction using 2nd-Moment Turbulence Closure", F.S, Lien, M.A. Leshziner, J. of Fluids Eng.-Tans. of ASME, 115, pp. 717-725, 1993 [2] "Analysis of Slope Limiter on Irregular Grids", M. Berger, M.J. Aftosmis and S.M. Murman, 43rd AIAA Aerospace Sciences Meeting, Jan. 10-13, 2005, Reno, NV Author Aleksandar Jemcov \*---------------------------------------------------------------------------*/ #ifndef umistSlopeLimiter_HPP_ #define umistSlopeLimiter_HPP_ #define makeUMISTSlopeLimiter(classType) \ template<class Type> \ CML::scalar \ CML::classType##UMIST<Type>::slopeLimiter(CML::scalar const r) const \ { \ return CML::scalar \ ( \ max \ ( \ 0, \ min \ ( \ min \ ( \ min \ ( \ 4*r/(r+1+VSMALL), \ (1+3*r)/(2*(r+1+VSMALL)) \ ), \ (3+r)/(2*(r+1+VSMALL)) \ ), \ 4/(r+1+VSMALL) \ ) \ ) \ ); \ } #endif
SFX_Cry10_3_Ch4: dutycycle 201 squarenote 8, 15, 7, 1664 squarenote 2, 15, 7, 1632 squarenote 1, 14, 7, 1600 squarenote 1, 14, 7, 1568 squarenote 15, 13, 1, 1536 squarenote 4, 12, 7, 1856 squarenote 4, 10, 7, 1840 squarenote 15, 9, 1, 1824 endchannel SFX_Cry10_3_Ch5: dutycycle 121 squarenote 10, 14, 7, 1666 squarenote 2, 14, 7, 1634 squarenote 1, 13, 7, 1602 squarenote 1, 13, 7, 1570 squarenote 15, 12, 1, 1538 squarenote 4, 11, 7, 1858 squarenote 2, 9, 7, 1842 squarenote 15, 8, 1, 1826 endchannel SFX_Cry10_3_Ch7: noisenote 4, 7, 4, 33 noisenote 4, 7, 4, 16 noisenote 4, 7, 1, 32 endchannel
#include "Platform.inc" #include "FarCalls.inc" #include "../Adc.inc" #include "States.inc" radix decimal defineLcdState LCD_STATE_ENABLE_SETCONTRAST setLcdState LCD_STATE_ENABLE_DISPLAYON fcall enableAdc returnFromLcdState end
; A166118: Fixed points of the mapping f(x) = (x + 2^x) mod (17 + x). ; 15,47,111,239,495,1007,2031,4079,8175,16367,32751,65519,131055,262127,524271,1048559,2097135,4194287,8388591,16777199,33554415,67108847,134217711,268435439,536870895,1073741807,2147483631,4294967279,8589934575,17179869167,34359738351,68719476719,137438953455,274877906927,549755813871,1099511627759,2199023255535,4398046511087,8796093022191,17592186044399,35184372088815,70368744177647,140737488355311,281474976710639,562949953421295,1125899906842607,2251799813685231,4503599627370479 add $0,5 mov $1,2 pow $1,$0 sub $1,17 mov $0,$1
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- // // PCR statistics analysis // //---------------------------------------------------------------------------- #include "tsPCRAnalyzer.h" #include "tsMemory.h" #include "tsUString.h" TSDUCK_SOURCE; //---------------------------------------------------------------------------- // Constructor // Specify the criteria for valid bitrate analysis: // Minimum number of PID's, each with a minimum number of PCR"s. //---------------------------------------------------------------------------- ts::PCRAnalyzer::PCRAnalyzer(size_t min_pid, size_t min_pcr) : _use_dts(false), _ignore_errors(false), _min_pid(std::max<size_t>(1, min_pid)), _min_pcr(std::max<size_t>(1, min_pcr)), _bitrate_valid(false), _ts_pkt_cnt(0), _ts_bitrate_188(0), _ts_bitrate_204(0), _ts_bitrate_cnt(0), _inst_ts_bitrate_188(0), _inst_ts_bitrate_204(0), _completed_pids(0), _pcr_pids(0), _discontinuities(0), _pid(), _packet_pcr_index_map() { TS_ZERO(_pid); } //---------------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------------- ts::PCRAnalyzer::~PCRAnalyzer() { reset(); } //---------------------------------------------------------------------------- // PIDAnalysis constructor //---------------------------------------------------------------------------- ts::PCRAnalyzer::PIDAnalysis::PIDAnalysis() : ts_pkt_cnt(0), cur_continuity(0), last_pcr_value(INVALID_PCR), last_pcr_packet(0), ts_bitrate_188(0), ts_bitrate_204(0), ts_bitrate_cnt(0) { } //---------------------------------------------------------------------------- // PCRAnalyzez::Status constructors //---------------------------------------------------------------------------- ts::PCRAnalyzer::Status::Status() : bitrate_valid(false), bitrate_188(0), bitrate_204(0), packet_count(0), pcr_count(0), pcr_pids(0), discontinuities(0), instantaneous_bitrate_188(0), instantaneous_bitrate_204(0) { } ts::PCRAnalyzer::Status::Status(const PCRAnalyzer& an) : Status() { an.getStatus(*this); } //---------------------------------------------------------------------------- // Implementation of StringifyInterface for PCRAnalyzez::Status. //---------------------------------------------------------------------------- ts::UString ts::PCRAnalyzer::Status::toString() const { return UString::Format(u"valid: %s, bitrate: %'d b/s, packets: %'d, PCRs: %'d, PIDs with PCR: %'d, discont: %'d, instantaneous bitrate: %'d b/s", {bitrate_valid, bitrate_188, packet_count, pcr_count, pcr_pids, discontinuities, instantaneous_bitrate_188}); } //---------------------------------------------------------------------------- // Reset all collected information //---------------------------------------------------------------------------- void ts::PCRAnalyzer::reset(size_t min_pid, size_t min_pcr) { _min_pid = std::max<size_t>(1, min_pid); _min_pcr = std::max<size_t>(1, min_pcr); reset(); } //---------------------------------------------------------------------------- // Reset all collected information //---------------------------------------------------------------------------- void ts::PCRAnalyzer::reset() { _bitrate_valid = false; _ts_pkt_cnt = 0; _ts_bitrate_188 = 0; _ts_bitrate_204 = 0; _ts_bitrate_cnt = 0; _completed_pids = 0; _pcr_pids = 0; _inst_ts_bitrate_188 = 0; _inst_ts_bitrate_204 = 0; for (size_t i = 0; i < PID_MAX; ++i) { if (_pid[i] != nullptr) { delete _pid[i]; _pid[i] = nullptr; } } _packet_pcr_index_map.clear(); } //---------------------------------------------------------------------------- // Reset all collected information and use DTS instead of PCR from now on. //---------------------------------------------------------------------------- void ts::PCRAnalyzer::resetAndUseDTS() { reset(); _use_dts = true; } void ts::PCRAnalyzer::resetAndUseDTS(size_t min_pid, size_t min_dts) { reset(min_pid, min_dts); _use_dts = true; } void ts::PCRAnalyzer::setIgnoreErrors(bool ignore) { _ignore_errors = ignore; } //---------------------------------------------------------------------------- // Process a discontinuity in the transport stream //---------------------------------------------------------------------------- void ts::PCRAnalyzer::processDiscontinuity() { _discontinuities++; // All collected PCR's become invalid since at least one packet is missing. for (size_t i = 0; i < PID_MAX; ++i) { if (_pid[i] != nullptr) { _pid[i]->last_pcr_value = INVALID_PCR; } } _packet_pcr_index_map.clear(); } //---------------------------------------------------------------------------- // Return the evaluated TS bitrate in bits/second // (based on 188-byte or 204-byte packets). //---------------------------------------------------------------------------- ts::BitRate ts::PCRAnalyzer::bitrate188() const { return _ts_bitrate_cnt == 0 ? 0 : BitRate(_ts_bitrate_188 / _ts_bitrate_cnt); } ts::BitRate ts::PCRAnalyzer::bitrate204() const { return _ts_bitrate_cnt == 0 ? 0 : BitRate(_ts_bitrate_204 / _ts_bitrate_cnt); } ts::BitRate ts::PCRAnalyzer::instantaneousBitrate188() const { return BitRate(_inst_ts_bitrate_188); } ts::BitRate ts::PCRAnalyzer::instantaneousBitrate204() const { return BitRate(_inst_ts_bitrate_204); } //---------------------------------------------------------------------------- // Return the evaluated PID bitrate in bits/second // (based on 188-byte or 204-byte packets). //---------------------------------------------------------------------------- ts::BitRate ts::PCRAnalyzer::bitrate188(PID pid) const { return (pid >= PID_MAX || _ts_bitrate_cnt == 0 || _ts_pkt_cnt == 0 || _pid[pid] == nullptr) ? 0 : BitRate((_ts_bitrate_188 * _pid[pid]->ts_pkt_cnt) / (_ts_bitrate_cnt * _ts_pkt_cnt)); } ts::BitRate ts::PCRAnalyzer::bitrate204(PID pid) const { return (pid >= PID_MAX || _ts_bitrate_cnt == 0 || _ts_pkt_cnt == 0 || _pid[pid] == nullptr) ? 0 : BitRate((_ts_bitrate_204 * _pid[pid]->ts_pkt_cnt) / (_ts_bitrate_cnt * _ts_pkt_cnt)); } //---------------------------------------------------------------------------- // Return the number of TS packets on a PID //---------------------------------------------------------------------------- ts::PacketCounter ts::PCRAnalyzer::packetCount(PID pid) const { return (pid >= PID_MAX || _pid[pid] == nullptr) ? 0 : _pid[pid]->ts_pkt_cnt; } //---------------------------------------------------------------------------- // Return all global results at once. //---------------------------------------------------------------------------- void ts::PCRAnalyzer::getStatus(Status& stat) const { stat.bitrate_valid = _bitrate_valid; stat.bitrate_188 = bitrate188(); stat.bitrate_204 = bitrate204(); stat.packet_count = _ts_pkt_cnt; stat.pcr_count = _ts_bitrate_cnt; stat.pcr_pids = _pcr_pids; stat.discontinuities = _discontinuities; stat.instantaneous_bitrate_188 = instantaneousBitrate188(); stat.instantaneous_bitrate_204 = instantaneousBitrate204(); } //---------------------------------------------------------------------------- // Feed the PCR analyzer with a new transport packet. // Return true if we have collected enough packet to evaluate TS bitrate. //---------------------------------------------------------------------------- bool ts::PCRAnalyzer::feedPacket(const TSPacket& pkt) { // Count one more packet in the TS _ts_pkt_cnt++; // Reject invalid packets, suspected TS corruption if (!_ignore_errors && !pkt.hasValidSync()) { processDiscontinuity(); return _bitrate_valid; } // Find PID context const PID pid = pkt.getPID(); assert(pid < PID_MAX); PIDAnalysis* ps = _pid[pid]; if (ps == nullptr) { ps = _pid[pid] = new PIDAnalysis; } // Count one more packet in the PID ps->ts_pkt_cnt++; // Null packets are ignored in PCR calculation (except for increment of _ts_pkt_cnt/ts_pkt_cnt). if (pid == PID_NULL) { return _bitrate_valid; } // Process discontinuities. If a discontinuity is discovered, // the PCR calculation across this packet is not valid. if (!_ignore_errors) { bool broken_rate = false; uint8_t continuity_cnt = pkt.getCC(); if (ps->ts_pkt_cnt == 1) { // First packet on this PID, initialize continuity ps->cur_continuity = continuity_cnt; } else if (pkt.getDiscontinuityIndicator()) { // Expected discontinuity broken_rate = true; } else if (pkt.hasPayload()) { // Packet has payload. Compute next continuity counter. uint8_t next_cont((ps->cur_continuity + 1) & 0x0F); // The countinuity counter must be either identical to previous one // (duplicated packet) or adjacent. broken_rate = continuity_cnt != ps->cur_continuity && continuity_cnt != next_cont; } else if (continuity_cnt != ps->cur_continuity) { // Packet has no payload -> should have same counter broken_rate = continuity_cnt != ps->cur_continuity; } ps->cur_continuity = continuity_cnt; // In case of suspected packet loss, reset calculations if (broken_rate) { processDiscontinuity(); } } // Process PCR (or DTS) if ((_use_dts && pkt.hasDTS()) || (!_use_dts && pkt.hasPCR())) { // Get PCR value (or DTS) const uint64_t pcr_dts = _use_dts ? pkt.getDTS() : pkt.getPCR(); // If last PCR/DTS valid, compute transport rate between the two if (ps->last_pcr_value != INVALID_PCR && ps->last_pcr_value != pcr_dts) { // Compute transport rate in b/s since last PCR/DTS uint64_t diff_values = _use_dts ? DiffPTS(ps->last_pcr_value, pcr_dts) * SYSTEM_CLOCK_SUBFACTOR : DiffPCR(ps->last_pcr_value, pcr_dts); uint64_t ts_bitrate_188 = diff_values == 0 ? 0 : ((_ts_pkt_cnt - ps->last_pcr_packet) * SYSTEM_CLOCK_FREQ * PKT_SIZE * 8) / diff_values; uint64_t ts_bitrate_204 = diff_values == 0 ? 0 : ((_ts_pkt_cnt - ps->last_pcr_packet) * SYSTEM_CLOCK_FREQ * PKT_RS_SIZE * 8) / diff_values; // Clear out values older than 1 second from _packet_pcr_index_map. // Note that this is a map that covers PCR/DTS packets across all PIDs // as long as the clocks used to generate the PCR/DTS values for different // programs is the same clock, there should be no issue, but if the PCR/DTS values // across the two programs are wildly different, then the following approach won't work. while (!_packet_pcr_index_map.empty()) { const uint64_t earliestPCR_DTS = _packet_pcr_index_map.begin()->first; diff_values = _use_dts ? DiffPTS(earliestPCR_DTS, pcr_dts) * SYSTEM_CLOCK_SUBFACTOR : DiffPCR(earliestPCR_DTS, pcr_dts); if (diff_values > SYSTEM_CLOCK_FREQ) { _packet_pcr_index_map.erase(_packet_pcr_index_map.begin()); } else { break; } } // Per-PID statistics: ps->ts_bitrate_188 += ts_bitrate_188; ps->ts_bitrate_204 += ts_bitrate_204; ps->ts_bitrate_cnt++; if (ps->ts_bitrate_cnt == 1) { // First PCR result on this PID _pcr_pids++; } // Transport stream statistics: _ts_bitrate_188 += ts_bitrate_188; _ts_bitrate_204 += ts_bitrate_204; _ts_bitrate_cnt++; // Transport stream instantaneous statistics. // For instantaneous bit rates, these are the actual bit rates, and it doesn't use the "count" approach. if (!_packet_pcr_index_map.empty()) { diff_values = _use_dts ? DiffPTS(_packet_pcr_index_map.begin()->first, pcr_dts) * SYSTEM_CLOCK_SUBFACTOR : DiffPCR(_packet_pcr_index_map.begin()->first, pcr_dts); _inst_ts_bitrate_188 = diff_values == 0 ? 0 : ((_ts_pkt_cnt - _packet_pcr_index_map.begin()->second) * SYSTEM_CLOCK_FREQ * PKT_SIZE * 8) / diff_values; _inst_ts_bitrate_204 = diff_values == 0 ? 0 : ((_ts_pkt_cnt - _packet_pcr_index_map.begin()->second) * SYSTEM_CLOCK_FREQ * PKT_RS_SIZE * 8) / diff_values; } // Check if we got enough values for this PID if (ps->ts_bitrate_cnt == _min_pcr) { _completed_pids++; _bitrate_valid = _completed_pids >= _min_pid; } } // Save PCR/DTS for next calculation, ignore duplicated values. if (ps->last_pcr_value != pcr_dts) { ps->last_pcr_value = pcr_dts; ps->last_pcr_packet = _ts_pkt_cnt; // Also add PCR (or DTS)/packet index combo to map for use in instantaneous bit rate calculations. _packet_pcr_index_map[pcr_dts] = _ts_pkt_cnt; // Make sure that some crazy TS does not accumulate thousands of PCR values in the same second range. while (_packet_pcr_index_map.size() > FOOLPROOF_MAP_LIMIT) { // Erase older entries. _packet_pcr_index_map.erase(_packet_pcr_index_map.begin()); } } } return _bitrate_valid; }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: spreadsheetMethodFocus.asm AUTHOR: John Wedgwood, Sep 4, 1991 METHODS: Name Description ---- ----------- MSG_META_GAINED_FOCUS_EXCL gain focus handler MSG_META_LOST_FOCUS_EXCL lost focus handler MSG_META_GAINED_TARGET_EXCL gain target handler MSG_META_LOST_TARGET_EXCL lost target handler MSG_META_GRAB_TARGET_EXCL grab target handler InvertSelection Invert selected cell and range REVISION HISTORY: Name Date Description ---- ---- ----------- John 9/ 4/91 Initial revision DESCRIPTION: Routines for recording when the spreadsheet gains/loses the focus. $Id: spreadsheetMethodFocus.asm,v 1.1 97/04/07 11:13:43 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CommonCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetGainedSysFocusExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Mark the spreadsheet to indicate that it has gained the SYSTEM focus exclusive. CALLED BY: via MSG_META_GAINED_SYS_FOCUS_EXCL PASS: *ds:si = Instance ptr ds:di = Instance ptr es = Class segment RETURN: nothing DESTROYED: everything (it's a method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/ 4/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetGainedSysFocusExcl method SpreadsheetClass, MSG_META_GAINED_SYS_FOCUS_EXCL ; ; Let our superclass do its thing ; mov di, offset SpreadsheetClass call ObjCallSuperNoLock mov di, ds:[si] add di, ds:[di].Spreadsheet_offset mov si, di ornf ds:[si].SSI_flags, mask SF_IS_SYS_FOCUS test ds:[si].SSI_flags, mask SF_IS_SYS_TARGET jnz done ;branch if already target call InvertSelection done: ; ; Tell the rulers about the change. ; mov ax, MSG_SPREADSHEET_RULER_SET_FLAGS mov dx, mask SRF_SSHEET_IS_FOCUS call SendToRuler ret SpreadsheetGainedSysFocusExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetGainedFocusExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calls SendTextFocusNotification to broadcast that spread- sheet object has gained the focus. CALLED BY: MSG_META_GAINED_FOCUS_EXCL PASS: *ds:si = SpreadsheetClass object ds:di = SpreadsheetClass instance data ds:bx = SpreadsheetClass object (same as *ds:si) es = segment of SpreadsheetClass ax = message # RETURN: nothing DESTROYED: ax, bx, cx, dx, di, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- HL 6/ 2/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetGainedFocusExcl method dynamic SpreadsheetClass, MSG_META_GAINED_FOCUS_EXCL ; ; Let our superclass do its thing ; mov di, offset SpreadsheetClass call ObjCallSuperNoLock mov bp, mask TFF_EDITABLE_TEXT_OBJECT_HAS_FOCUS call SendTextFocusNotification ret SpreadsheetGainedFocusExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetLostSysFocusExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Mark the spreadsheet to indicate that it has lost the SYSTEM focus exclusive. CALLED BY: via MSG_META_LOST_SYS_FOCUS_EXCL PASS: *ds:si = Instance ptr ds:di = Instance ptr es = Class segment RETURN: nothing DESTROYED: everything (it's a method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/ 4/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetLostSysFocusExcl method SpreadsheetClass, MSG_META_LOST_SYS_FOCUS_EXCL push si ; chunk handle mov si, di andnf ds:[si].SSI_flags, not mask SF_IS_SYS_FOCUS test ds:[si].SSI_flags, mask SF_IS_SYS_TARGET jnz done ;branch if still target call InvertSelection done: ; ; Tell the rulers about the change. ; mov ax, MSG_SPREADSHEET_RULER_SET_FLAGS mov dx, (mask SRF_SSHEET_IS_FOCUS shl 8) call SendToRuler ; ; Let our superclass do its thing ; pop si mov ax, MSG_META_LOST_SYS_FOCUS_EXCL mov di, offset SpreadsheetClass GOTO ObjCallSuperNoLock SpreadsheetLostSysFocusExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetLostFocusExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calls SendTextFocusNotification to broadcast that spread- sheet object has lost the focus. CALLED BY: MSG_META_LOST_FOCUS_EXCL PASS: *ds:si = SpreadsheetClass object ds:di = SpreadsheetClass instance data ds:bx = SpreadsheetClass object (same as *ds:si) es = segment of SpreadsheetClass ax = message # RETURN: nothing DESTROYED: ax, bx, cx, dx, di, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- HL 6/ 2/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetLostFocusExcl method dynamic SpreadsheetClass, MSG_META_LOST_FOCUS_EXCL clr bp call SendTextFocusNotification ; ; Let our superclass do its thing ; mov ax, MSG_META_LOST_FOCUS_EXCL mov di, offset SpreadsheetClass GOTO ObjCallSuperNoLock SpreadsheetLostFocusExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendTextFocusNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Sends the GWNT_EDITABLE_TEXT_OBJECT_HAS_FOCUS notification. CALLED BY: MSG_META_GAINED_FOCUS_EXCL handler MSG_META_LOST_FOCUS_EXCL handler PASS: bp = TextFocusFlags to send out RETURN: nothing DESTROYED: ax, bx, cx, dx, di SIDE EFFECTS: PSEUDO CODE/STRATEGY: code snarfed from procedure of same name in /s/p/Library/Text/ TextSelect/tslMethodFocus.asm REVISION HISTORY: Name Date Description ---- ---- ----------- HL 6/ 2/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendTextFocusNotification proc near ; ; Record event to send to ink controller. ; mov ax, MSG_META_NOTIFY mov cx, MANUFACTURER_ID_GEOWORKS mov dx, GWNT_EDITABLE_TEXT_OBJECT_HAS_FOCUS mov di, mask MF_RECORD call ObjMessage mov ax, mask GCNLSF_SET_STATUS test bp, mask TFF_EDITABLE_TEXT_OBJECT_HAS_FOCUS jnz 10$ ornf ax, mask GCNLSF_IGNORE_IF_STATUS_TRANSITIONING 10$: ; ; Send it to the appropriate gcn list. ; mov dx, size GCNListMessageParams sub sp, dx mov bp, sp mov ss:[bp].GCNLMP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS mov ss:[bp].GCNLMP_ID.GCNLT_type, GAGCNLT_NOTIFY_FOCUS_TEXT_OBJECT clr ss:[bp].GCNLMP_block mov ss:[bp].GCNLMP_event, di mov ss:[bp].GCNLMP_flags, ax mov ax, MSG_GEN_PROCESS_SEND_TO_APP_GCN_LIST call GeodeGetProcessHandle mov di, mask MF_FIXUP_DS or mask MF_STACK call ObjMessage add sp, dx ret SendTextFocusNotification endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% InvertSelection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Invert the entire selection CALLED BY: SpreadsheetLostFocusExcl(), SpreadsheetGainedFocusExcl() PASS: ds:si - ptr to Spreadsheet instance RETURN: none DESTROYED: ax, bx, cx, dx, di, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 11/15/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ InvertSelection proc near class SpreadsheetClass .enter EC < call ECCheckInstancePtr ;> ; ; If we're in engine mode, don't invert the selection ; test ds:[si].SSI_attributes, mask SA_ENGINE_MODE jnz done call CreateGStateFar mov ax, ds:[si].SSI_active.CR_row mov cx, ds:[si].SSI_active.CR_column call InvertActiveVisibleCellFar ;unactivate current cell call InvertSelectedVisibleCellFar ;invert to allow rectangle mov ax, ds:[si].SSI_selected.CR_start.CR_row mov cx, ds:[si].SSI_selected.CR_start.CR_column mov bp, ds:[si].SSI_selected.CR_end.CR_row mov dx, ds:[si].SSI_selected.CR_end.CR_column call InvertSelectedVisibleRangeFar ;deselect range call DestroyGStateFar done: .leave ret InvertSelection endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetGainedTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle gained APP target exclusive CALLED BY: MSG_META_GAINED_TARGET_EXCL PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 11/17/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetGainedTargetExcl method dynamic SpreadsheetClass, \ MSG_META_GAINED_TARGET_EXCL mov si, di ;ds:si <- ptr to instance data ornf ds:[si].SSI_flags, mask SF_IS_APP_TARGET ; ; Force all UI to update ; mov ax, SNFLAGS_DOCUMENT_CHANGED call SS_SendNotification ; ; disable paragraph attributes (besides Justification) ; test ds:[si].SSI_attributes, mask SA_ENGINE_MODE jnz noPara call SS_SendNullParaAttrNotification noPara: ; ; The the rulers about the change ; mov ax, MSG_SPREADSHEET_RULER_SET_FLAGS mov dx, mask SRF_SSHEET_IS_TARGET call SendToRuler ret SpreadsheetGainedTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetLostTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle loss of APP target exclusive CALLED BY: MSG_META_LOST_TARGET_EXCL PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 11/17/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetLostTargetExcl method dynamic SpreadsheetClass, \ MSG_META_LOST_TARGET_EXCL mov si, di ;ds:si <- ptr to instance data andnf ds:[si].SSI_flags, not (mask SF_IS_APP_TARGET) ; ; Force all UI to update ; clr ax ;ax <- force update call SS_SendNotification ; ; Tell the rulers about the change ; mov ax, MSG_SPREADSHEET_RULER_SET_FLAGS mov dx, (mask SRF_SSHEET_IS_TARGET shl 8) call SendToRuler ret SpreadsheetLostTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetGrabTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle 'grab target' if we're supposed to CALLED BY: MSG_META_GRAB_TARGET_EXCL PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the method RETURN: DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 11/19/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetGrabTargetExcl method dynamic SpreadsheetClass, \ MSG_META_GRAB_TARGET_EXCL ; ; If we aren't targetable, don't grab the target ; test ds:[di].SSI_attributes, mask SA_TARGETABLE jz done mov di, offset SpreadsheetClass call ObjCallSuperNoLock done: ret SpreadsheetGrabTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetGainedSysTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handling gaining the SYSTEM target exclusive CALLED BY: MSG_META_GAINED_TARGET_EXCL PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the message RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 9/11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetGainedSysTargetExcl method dynamic SpreadsheetClass, MSG_META_GAINED_SYS_TARGET_EXCL mov si, di ;ds:si <- ptr to spreadsheet ornf ds:[si].SSI_flags, mask SF_IS_SYS_TARGET ; ; If we don't already have the focus, invert the selection ; test ds:[si].SSI_flags, mask SF_IS_SYS_FOCUS jnz done ;branch if already focus call InvertSelection done: ret SpreadsheetGainedSysTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetLostSysTargetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle losing the SYSTEM target exclusive CALLED BY: MSG_META_LOST_TARGET_EXCL PASS: *ds:si - instance data ds:di - *ds:si es - seg addr of SpreadsheetClass ax - the message RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 9/11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetLostSysTargetExcl method dynamic SpreadsheetClass, MSG_META_LOST_SYS_TARGET_EXCL mov si, di ;ds:si <- ptr to spreadsheet andnf ds:[si].SSI_flags, not (mask SF_IS_SYS_TARGET) ; ; If we don't have the focus, either, invert the selection ; test ds:[si].SSI_flags, mask SF_IS_SYS_FOCUS jnz done ;branch if still focus call InvertSelection done: ret SpreadsheetLostSysTargetExcl endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetLostGadgetExcl %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle loss of gadget exclusive... CALLED BY: MSG_VIS_LOST_GADGET_EXCL PASS: ds:*si - ptr to instance data ds:di - ptr to instance data es - segment of SpreadsheetClass ax = MSG_VIS_LOST_GADGET_EXCL. RETURN: none DESTROYED: bx, si, di, ds, es (method handler) PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: NOTE: This message is send a lot when you are receiving mouse events. This is why it is in the DrawCode resource -- DrawCode isn't used (much, if at all) when the spreadsheet is in engine mode, and neither is this. REVISION HISTORY: Name Date Description ---- ---- ----------- eca 7/14/89 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetLostGadgetExcl method SpreadsheetClass, MSG_VIS_LOST_GADGET_EXCL andnf ds:[di].SSI_flags, not (mask SF_HAVE_GRAB) call VisReleaseMouse ret SpreadsheetLostGadgetExcl endm CommonCode ends
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; WriteMsr64.Asm ; ; Abstract: ; ; AsmWriteMsr64 function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; UINT64 ; EFIAPI ; AsmWriteMsr64 ( ; IN UINT32 Index, ; IN UINT64 Value ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmWriteMsr64) ASM_PFX(AsmWriteMsr64): mov edx, [esp + 12] mov eax, [esp + 8] mov ecx, [esp + 4] wrmsr ret
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .text .p2align 4, 0x90 .globl _PurgeBlock _PurgeBlock: movslq %esi, %rcx xor %rax, %rax sub $(8), %rcx jl .Ltest_purgegas_1 .Lpurge8gas_1: movq %rax, (%rdi) add $(8), %rdi sub $(8), %rcx jge .Lpurge8gas_1 .Ltest_purgegas_1: add $(8), %rcx jz .Lquitgas_1 .Lpurge1gas_1: movb %al, (%rdi) add $(1), %rdi sub $(1), %rcx jg .Lpurge1gas_1 .Lquitgas_1: ret
; A098260: Chebyshev polynomials S(n,627). ; Submitted by Jamie Morken(s2) ; 1,627,393128,246490629,154549231255,96902121506256,60757475635191257,38094840321143411883,23885404123881284059384,14976110290833243961821885,9389997266948320082778262511 add $0,1 mul $0,2 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 mul $2,25 lpe mov $0,$1 div $0,25
/************************************************************************* >>> Author: WindCry1 >>> Mail: lanceyu120@gmail.com >>> Website: https://windcry1.com >>> Date: 8/3/2019 6:13:35 PM *************************************************************************/ #include<cstring> #include<cmath> #include<cstdio> #include<cctype> #include<cstdlib> #include<ctime> #include<vector> #include<iostream> #include<string> #include<queue> #include<set> #include<map> #include<algorithm> #include<complex> #include<stack> #include<bitset> #include<iomanip> #include<list> #if __cplusplus >= 201103L #include<unordered_map> #include<unordered_set> #endif #define ll long long #define ull unsigned long long using namespace std; typedef pair<int,int> pii; const double clf=1e-8; const int MMAX=0x7fffffff; const int INF=0xfffffff; const int mod=1e9+7; ll dp[510][510]; ll del[510]; ll ans[510]; int n; void Floyd() { for(int k=1;k<=n;k++) { ll K=del[k]; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { ll I=del[i],J=del[j]; dp[I][J]=min(dp[I][J],dp[I][K]+dp[K][J]); if(i<=k&&j<=k) ans[k]+=dp[I][J]; } } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin); //freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout); cin>>n; for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) cin>>dp[i][j]; for(int i=n;i>=1;i--) cin>>del[i]; Floyd(); for(int i=n;i>=1;i--) cout<<ans[i]<<(i==1?"\n":" "); return 0; }
#include "x264_encoder.h" extern "C" { #include <libavformat/avformat.h> #include <libavutil/imgutils.h> } #include <ros/console.h> using namespace lmt::encoder; using namespace lmt::statistics; X264Encoder::~X264Encoder() { if (encoder_) { x264_picture_clean(&picIn_); } } X264Encoder::X264Encoder(uint16_t outWidth, uint16_t outHeight, uint8_t qp) : VideoEncoder(outWidth, outHeight) { auto param = getPresetParam(outWidth, outHeight); param.rc.i_rc_method = X264_RC_CQP; param.rc.i_qp_constant = qp; param.rc.f_rf_constant = qp; param.rc.f_rf_constant_max = qp; encoder_.reset(x264_encoder_open(&param)); x264_encoder_headers(encoder_.get(), &nals_, &nheader_); // Initialize X264 Picture x264_picture_alloc(&picIn_, param.i_csp, outWidth_, outHeight_); } FrameStats X264Encoder::encodeImpl(const cv_bridge::CvImageConstPtr& inputImg, std::unique_ptr<uint8_t[]>& encodedData) // NOLINT(modernize-avoid-c-arrays) { AVPixelFormat inPixelFormat = AV_PIX_FMT_BGR24; swsContext_.reset(sws_getContext(inputImg->image.cols, inputImg->image.rows, inPixelFormat, outWidth_, outHeight_, AV_PIX_FMT_YUV420P, SWS_FAST_BILINEAR, nullptr, nullptr, nullptr)); // Put raw image data to AV picture AVFrame picRaw; if (av_image_fill_arrays(picRaw.data, picRaw.linesize, inputImg->image.data, inPixelFormat, inputImg->image.cols, inputImg->image.rows, 1) < 0) { ROS_WARN("Cannot fill the raw input buffer"); return {}; } if (sws_scale(swsContext_.get(), picRaw.data, picRaw.linesize, 0, inputImg->image.rows, picIn_.img.plane, picIn_.img.i_stride) != outHeight_) { ROS_WARN("scale failed"); return {}; } // Encode picIn_.i_pts = frameCounter_; ++frameCounter_; const auto start = ros::Time::now(); uint32_t encodedFrameSize = x264_encoder_encode(encoder_.get(), &nals_, &numNals_, &picIn_, &picOut_); // encodedFrameSize [byte] const auto end = ros::Time::now(); const auto duration = end - start; std::copy(nals_[0].p_payload, nals_[0].p_payload + encodedFrameSize, encodedData.get()); return {start.toNSec(), frameCounter_, encodedFrameSize, duration.toNSec()}; } X264Encoder::X264Encoder(uint16_t outWidth, uint16_t outHeight, int bitrate) : VideoEncoder(outWidth, outHeight) { auto param = getPresetParam(outWidth, outHeight); param.rc.i_rc_method = X264_RC_CRF; param.rc.i_vbv_max_bitrate = bitrate; const auto bufferSizeRatioOfMaxBitrate = 0.1; param.rc.i_vbv_buffer_size = static_cast<int>(bufferSizeRatioOfMaxBitrate * param.rc.i_vbv_max_bitrate); encoder_.reset(x264_encoder_open(&param)); x264_encoder_headers(encoder_.get(), &nals_, &nheader_); // Initialize X264 Picture x264_picture_alloc(&picIn_, param.i_csp, outWidth_, outHeight_); } x264_param_t X264Encoder::getPresetParam(uint16_t outWidth, uint16_t outHeight) { x264_param_t param; x264_param_default_preset(&param, "ultrafast", "zerolatency,fastdecode"); x264_param_apply_profile(&param, "baseline"); param.i_width = outWidth; param.i_height = outHeight; const auto frameRate = 20; param.i_fps_num = frameRate; param.i_fps_den = 1; param.i_csp = X264_CSP_I420; return param; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r8 push %r9 push %rbp push %rdx lea addresses_D_ht+0x3b8c, %r13 nop nop nop cmp %r9, %r9 mov $0x6162636465666768, %r10 movq %r10, %xmm1 and $0xffffffffffffffc0, %r13 vmovntdq %ymm1, (%r13) nop nop nop dec %r8 lea addresses_D_ht+0xd8cc, %rdx nop xor %rbp, %rbp mov $0x6162636465666768, %r12 movq %r12, %xmm4 movups %xmm4, (%rdx) nop nop nop nop nop xor $23705, %rbp pop %rdx pop %rbp pop %r9 pop %r8 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %rbx push %rcx push %rdi // Faulty Load lea addresses_US+0x32cc, %rdi clflush (%rdi) nop nop add $6850, %rcx mov (%rdi), %r11d lea oracles, %r15 and $0xff, %r11 shlq $12, %r11 mov (%r15,%r11,1), %r11 pop %rdi pop %rcx pop %rbx pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': True, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 7, 'size': 16, 'same': True, 'NT': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("nerdcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
SFX_Pokeflute_Ch1: vibrato 16, 1, 4 notetype 12, 1, 0 octave 5 E_ 2 F_ 2 G_ 4 A_ 2 G_ 2 octave 6 C_ 4 C_ 2 D_ 2 C_ 2 octave 5 G_ 2 A_ 2 F_ 2 G_ 8 rest 12 endchannel
; A083196: a(n) = 8*n^4 + 9*n^2 + 2. ; 2,19,166,731,2194,5227,10694,19651,33346,53219,80902,118219,167186,230011,309094,407027,526594,670771,842726,1045819,1283602,1559819,1878406,2243491,2659394,3130627,3661894,4258091,4924306,5665819,6488102,7396819,8397826 mul $0,4 pow $0,2 add $0,9 pow $0,2 sub $0,81 div $0,32 add $0,2
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = {QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=tajcoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Tajcoin Alert\" admin@foo." "com\n"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Tajcoin will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: tajcoin.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: tajcoind.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database disk log size in megabytes (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 15714 or testnet: 25714)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Bind to given address. Use [host]:port notation for IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Always query for peer addresses via DNS lookup (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Sync time with other nodes. Disable if time on your system is precise e.g. " "syncing with NTP (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Sync checkpoints policy (default: strict)"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "" "When creating transactions, ignore inputs with value less than this " "(default: 0.01)"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Output debugging information (default: 0, supplying <category> is optional)"), QT_TRANSLATE_NOOP("bitcoin-core", "If <category> is not supplied, output all debugging information."), QT_TRANSLATE_NOOP("bitcoin-core", "<category> can be:"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Enter regression test mode, which uses a special chain in which blocks can " "be solved instantly. This is intended for regression testing tools and app " "development."), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Wait for RPC server to start"), QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "Require a confirmations for change (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Minimize weight consumption (experimental) (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 500, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-6, default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000?.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Keep at most <n> unconnectable blocks in memory (default: %u)"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: " "27000)"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!" "3DES:@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: Deprecated argument -debugnet ignored, use -debug=net"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: Unsupported argument -socks found. Setting SOCKS version isn't " "possible anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mininput=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Initialization sanity check failed. Tajcoin is shutting down."), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet %s resides outside data directory %s."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. Tajcoin is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying database integrity..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to sign checkpoint, wrong checkpointkey?\n"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Tajcoin"), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Tajcoin to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. Tajcoin is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Tajcoin version"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or tajcoind"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet unlocked for staking only, unable to create transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Transaction creation failed!"), QT_TRANSLATE_NOOP("bitcoin-core", "Sending..."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning"), QT_TRANSLATE_NOOP("bitcoin-core", "Information"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "WARNING: syncronized checkpoint violation detected, but skipped!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("bitcoin-core", "" "WARNING: Invalid checkpoint found! Displayed transactions may not be " "correct! You may need to upgrade, or notify developers."), };
// Copyright (c) 2020 The Connectal Project // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "funnel.h" template<int funnelWidth, int width> class FunnelBufferedBase __implements FunnelBaseIfc<funnelWidth, width> { FifoPBase<width> buffer [funnelWidth]; FunnelBase<funnelWidth, width> base; __connect base.out = this->out; __rule init { for (int i = 0; i < funnelWidth; i = i + 1) { __connect buffer[i].in = this->in[i]; __connect base.in[i] = buffer[i].out; } } }; FunnelBufferedBase<4, 32> dummy;
; CALLER linkage for long2ipstring() PUBLIC long2ipstring EXTERN long2ipstring_callee EXTERN ASMDISP_LONG2IPSTRING_CALLEE ; void long2ipstring(inet_addr_t *addr, char *str); .long2ipstring pop bc ; return address pop de ; char *str pop hl ; inet_addr_t *addr push hl push de push bc jp long2ipstring_callee + ASMDISP_LONG2IPSTRING_CALLEE
; A245599: Numbers m with A030101(m) XOR A030109(m) = m for the binary representation of m. ; 1,11,91,731,5851,46811,374491,2995931,23967451,191739611,1533916891,12271335131,98170681051,785365448411,6282923587291,50263388698331,402107109586651,3216856876693211,25734855013545691,205878840108365531,1647030720866924251,13176245766935394011,105409966135483152091,843279729083865216731,6746237832670921733851,53969902661367373870811,431759221290938990966491,3454073770327511927731931,27632590162620095421855451,221060721300960763374843611,1768485770407686106998748891,14147886163261488855989991131,113183089306091910847919929051,905464714448735286783359432411,7243717715589882294266875459291,57949741724719058354135003674331,463597933797752466833080029394651,3708783470382019734664640235157211,29670267763056157877317121881257691,237362142104449263018536975050061531 mov $1,8 pow $1,$0 div $1,7 mul $1,10 add $1,1 mov $0,$1
global check_cpuid global check_long_mode extern early_error section .init bits 32 check_cpuid: ;check if the cpuid instruction is available ;move flags register to eax pushfd pop eax ;copy eax and flip bit 21 mov ecx, eax xor eax, 1 << 21 ;move eax to flags register push eax popfd ;move flags register back to eax pushfd pop eax ;check if the value changed cmp eax, ecx je .no_cpuid ret .no_cpuid: mov eax, no_long_mode_error jmp early_error check_long_mode: ;check if long mode is supported ;check for extended processor information mov eax, 1 << 31 cpuid ;checks for the highest supported argument cmp eax, 1 << 31 | 1 << 0 ;if the argument is supported jb .no_long_mode ;the argument is not supported -> no long mode mov eax, 1 << 31 | 1 << 0 ;argument for extended information cpuid test edx, 1 << 29 ;if bit 29 is set, long mode is supported jz .no_long_mode ret .no_long_mode: mov eax, no_long_mode_error jmp early_error no_long_mode_error: db "Your CPU does not support 64 Bit mode. That means it's not possible to use this OS on your computer. Aborting...",0
; ; Placeholder for reading a key from the keyboard ; SECTION code_clib PUBLIC getk PUBLIC _getk getk: _getk: in a,($00) ;Key code ld l,a in a,($01) ;Flags ;bit 7 = shift ;bit 6 = function key ;bit 3 = not pressed/pressed bit 3,a jr z,key_pressed ld hl,0 ret key_pressed: ; TODO: Take account of shift/function key etc ld h,0 ret
%ifidn __OUTPUT_FORMAT__,elf32 %include "vpx_config_x86-linux-gcc.asm" %elifidn __OUTPUT_FORMAT__,elf64 %include "vpx_config_x86_64-linux-gcc.asm" %elifidn __OUTPUT_FORMAT__,macho32 %include "vpx_config_x86-darwin9-gcc.asm" %elifidn __OUTPUT_FORMAT__,macho64 %include "vpx_config_x86_64-darwin9-gcc.asm" %elifidn __OUTPUT_FORMAT__,win32 %include "vpx_config_x86-win32-vs8.asm" %elifidn __OUTPUT_FORMAT__,x64 %include "vpx_config_x86_64-win64-vs8.asm" %endif
@ This file was created from a .asm file @ using the ads2gas.pl script. .equ DO1STROUNDING, 0 .equ ARCH_ARM , 1 .equ ARCH_MIPS , 0 .equ ARCH_X86 , 0 .equ ARCH_X86_64 , 0 .equ HAVE_EDSP , 0 .equ HAVE_MEDIA , 0 .equ HAVE_NEON , 1 .equ HAVE_NEON_ASM , 0 .equ HAVE_MIPS32 , 0 .equ HAVE_DSPR2 , 0 .equ HAVE_MSA , 0 .equ HAVE_MIPS64 , 0 .equ HAVE_MMX , 0 .equ HAVE_SSE , 0 .equ HAVE_SSE2 , 0 .equ HAVE_SSE3 , 0 .equ HAVE_SSSE3 , 0 .equ HAVE_SSE4_1 , 0 .equ HAVE_AVX , 0 .equ HAVE_AVX2 , 0 .equ HAVE_VPX_PORTS , 1 .equ HAVE_STDINT_H , 1 .equ HAVE_PTHREAD_H , 1 .equ HAVE_SYS_MMAN_H , 1 .equ HAVE_UNISTD_H , 0 .equ CONFIG_DEPENDENCY_TRACKING , 1 .equ CONFIG_EXTERNAL_BUILD , 1 .equ CONFIG_INSTALL_DOCS , 0 .equ CONFIG_INSTALL_BINS , 1 .equ CONFIG_INSTALL_LIBS , 1 .equ CONFIG_INSTALL_SRCS , 0 .equ CONFIG_USE_X86INC , 0 .equ CONFIG_DEBUG , 0 .equ CONFIG_GPROF , 0 .equ CONFIG_GCOV , 0 .equ CONFIG_RVCT , 0 .equ CONFIG_GCC , 1 .equ CONFIG_MSVS , 0 .equ CONFIG_PIC , 1 .equ CONFIG_BIG_ENDIAN , 0 .equ CONFIG_CODEC_SRCS , 0 .equ CONFIG_DEBUG_LIBS , 0 .equ CONFIG_DEQUANT_TOKENS , 0 .equ CONFIG_DC_RECON , 0 .equ CONFIG_RUNTIME_CPU_DETECT , 0 .equ CONFIG_POSTPROC , 1 .equ CONFIG_VP9_POSTPROC , 1 .equ CONFIG_MULTITHREAD , 1 .equ CONFIG_INTERNAL_STATS , 0 .equ CONFIG_VP8_ENCODER , 1 .equ CONFIG_VP8_DECODER , 1 .equ CONFIG_VP9_ENCODER , 1 .equ CONFIG_VP9_DECODER , 1 .equ CONFIG_VP10_ENCODER , 0 .equ CONFIG_VP10_DECODER , 0 .equ CONFIG_VP8 , 1 .equ CONFIG_VP9 , 1 .equ CONFIG_VP10 , 0 .equ CONFIG_ENCODERS , 1 .equ CONFIG_DECODERS , 1 .equ CONFIG_STATIC_MSVCRT , 0 .equ CONFIG_SPATIAL_RESAMPLING , 1 .equ CONFIG_REALTIME_ONLY , 1 .equ CONFIG_ONTHEFLY_BITPACKING , 0 .equ CONFIG_ERROR_CONCEALMENT , 0 .equ CONFIG_SHARED , 0 .equ CONFIG_STATIC , 1 .equ CONFIG_SMALL , 0 .equ CONFIG_POSTPROC_VISUALIZER , 0 .equ CONFIG_OS_SUPPORT , 1 .equ CONFIG_UNIT_TESTS , 0 .equ CONFIG_WEBM_IO , 1 .equ CONFIG_LIBYUV , 1 .equ CONFIG_DECODE_PERF_TESTS , 0 .equ CONFIG_ENCODE_PERF_TESTS , 0 .equ CONFIG_MULTI_RES_ENCODING , 1 .equ CONFIG_TEMPORAL_DENOISING , 1 .equ CONFIG_VP9_TEMPORAL_DENOISING , 1 .equ CONFIG_COEFFICIENT_RANGE_CHECKING , 0 .equ CONFIG_VP9_HIGHBITDEPTH , 0 .equ CONFIG_EXPERIMENTAL , 0 .equ CONFIG_SIZE_LIMIT , 1 .equ CONFIG_SPATIAL_SVC , 0 .equ CONFIG_FP_MB_STATS , 0 .equ CONFIG_EMULATE_HARDWARE , 0 .equ DECODE_WIDTH_LIMIT , 16384 .equ DECODE_HEIGHT_LIMIT , 16384 .section .note.GNU-stack,"",%progbits
COMMENT @---------------------------------------------------------------------- Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Solitaire FILE: game.asm REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 9/90 Initial Version DESCRIPTION: This file contains method handlers for GameClass. RCS STAMP: $Id: game.asm,v 1.1 97/04/04 17:44:41 newdeal Exp $ ------------------------------------------------------------------------------@ CardsClassStructures segment resource GameClass CardsClassStructures ends ;--------------------------------------------------- CardsCodeResource segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSaveState %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Game method for MSG_GAME_SAVE_STATE Marks the game object dirty, and sends a message to the decks telling them to save state. Called by: MSG_GAME_SAVE_STATE Pass: *ds:si = Game object ds:di = Game instance Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 18, 1993 Initial version. PW March 23, 1993 modified. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSaveState method dynamic GameClass, MSG_GAME_SAVE_STATE .enter call ObjMarkDirty mov ax, MSG_DECK_SAVE_STATE call VisSendToChildren .leave ret GameSaveState endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameRestoreState %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Game method for MSG_GAME_RESTORE_STATE seeds the random number generator. Called by: MSG_GAME_RESTORE_STATE Pass: *ds:si = Game object ds:di = Game instance Return: nothing Destroyed: ax, dx Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 18, 1993 Initial version. PW March 23, 1993 modified. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameRestoreState method dynamic GameClass, MSG_GAME_RESTORE_STATE .enter call TimerGetCount mov_trash dx, ax mov ax, MSG_GAME_SEED_RANDOM call ObjCallInstanceNoLock .leave ret GameRestoreState endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSendToDecksNoSave %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Sends a message to all the decks, *not* saving registers between calls Pass: *ds:si - game ax,cx,dx,bp - message data Return: ax,cx,dx,bp - return values from message Destroyed: nothing Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 18, 1993 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if 0 GameSendToDecksNoSave proc near uses bx, di .enter clr bx ; initial child (first push bx ; child of push bx ; composite) mov bx, offset VI_link ; Pass offset to LinkPart push bx clr bx ; Use standard function push bx mov bx, OCCT_DONT_SAVE_PARAMS_DONT_TEST_ABORT push bx mov bx, offset Vis_offset mov di, offset VCI_comp call ObjCompProcessChildren .leave ret GameSendToDecksNoSave endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameGetVMFile %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Game method for MSG_GAME_GET_VM_FILE Called by: MSG_GAME_GET_VM_FILE Pass: *ds:si = Game object ds:di = Game instance Return: carry set if error, else cx - VM file handle of card bitmaps ax - map block to bitmaps Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Sep 2, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameGetVMFile method dynamic GameClass, MSG_GAME_GET_VM_FILE .enter mov cx, ds:[di].GI_vmFile mov ax, ds:[di].GI_mapBlock .leave ret GameGetVMFile endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameRestoreBitmaps %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Will read in the BitMap's of the cards CALLED BY: MSG_GEM_PROCESS_OPEN_APPLICATION handler PASS: *ds:si = GameClass object RETURN: nothing DESTROYED: di SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PW 3/17/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameRestoreBitmaps method dynamic GameClass, MSG_GAME_RESTORE_BITMAPS .enter ; ; find out our display scheme, determine which resolutio ; to use for the card deck, and setup our geometry ; mov ax, MSG_GEN_APPLICATION_GET_DISPLAY_SCHEME call GenCallApplication push ax ;save DisplayType Deref_DI Game_offset mov ds:[di].GI_displayScheme, ah NOFXIP< segmov es, dgroup, bx ;es = dgroup > FXIP < mov bx, handle dgroup > FXIP < call MemDerefES ;es = dgroup > mov bx, es:vmFileHandle mov ds:[di].GI_vmFile, bx call ObjMarkDirty call VMGetMapBlock call VMLock pop bx ;bh <- DisplayType push bp ;save handle mov es, ax ;ds <- segment of ;map block ;; now run through the map block and find the set of bitmaps ;; we want given the DisplayType. mov cx, es:[DDS_arrayLength] mov di, offset DDS_DRS - size DeckResStruct ; es:[di] -> first DRS minus one DRS ; to account for how the ; loop's written startLoop: add di, size DeckResStruct cmp bh, es:[di].DRS_displayType loopne startLoop ;es:di = DeckResStruct of resolution map to use. This means we ;default to the last entry in the array if nothing else matches. mov bp, ds:[si] add bp, ds:[bp].Game_offset mov ax, es:[di].DRS_mapBlock mov ds:[bp].GI_mapBlock, ax call ObjMarkDirty pop bp ;restore mapblock handle call VMUnlock mov ax, MSG_GAME_GET_VM_FILE call ObjCallInstanceNoLock mov_tr bx, cx ;bx <- vm file handle call VMLock push bp ;save block handle for ;unlocking push ax ;save block segment for later mov di, ds ;di <- game segment mov ds, ax ;ds <- bitmap segment push si mov si, ds:[0].DMS_interior ;*ds:si -> interior region call CopyRegionToChunk pop si Deref_DI Game_offset mov ds:[di].GI_interiorReg, ax call ObjMarkDirty pop ax ;restore block segment mov di, ds ;di <- game segment mov ds, ax ;ds <- bitmap segment push si mov si, ds:[DMS_frame] ;*ds:si -> frame reg call CopyRegionToChunk pop si Deref_DI Game_offset mov ds:[di].GI_frameReg, ax call ObjMarkDirty pop bp call VMUnlock push si mov al, mask OCF_IGNORE_DIRTY ;fade array don't go to state mov bx, size optr ;each element of the array ;will hold an optr clr cx, si call ChunkArrayCreate mov bp, si ;bp <- array offset pop si Deref_DI Game_offset mov ds:[di].GI_fadeArray, bp mov ax, MSG_GAME_SEND_CARD_BACK_NOTIFICATION call ObjCallInstanceNoLock .leave ret GameRestoreBitmaps endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetupStuff %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SETUP_STUFF handler for GameClass Sets up various sizes and defaults necessary when first loading the game in. CALLED BY: called by MSG_GEN_PROCESS_OPEN_APPLICATION handler PASS: *ds:si = game object CHANGES: initializes some data slots RETURN: nothing DESTROYED: di PSEUDO CODE/STRATEGY: sets size (currently height=width=600) tells geometry manager to not manage children KNOWN BUGS/IDEAS: could be moved to some ui file? REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetupStuff method GameClass,MSG_GAME_SETUP_STUFF call TimerGetCount mov_trash dx, ax mov ax, MSG_GAME_SEED_RANDOM call ObjCallInstanceNoLock ; ; find out our display scheme, determine which resolutio ; to use for the card deck, and setup our geometry ; mov ax, MSG_GEN_APPLICATION_GET_DISPLAY_SCHEME call GenCallApplication push ax ;save DisplayType Deref_DI Game_offset mov ds:[di].GI_displayScheme, ah NOFXIP< segmov es, dgroup, bx ;es = dgroup > FXIP < mov bx, handle dgroup > FXIP < call MemDerefES ;es = dgroup > mov bx, es:vmFileHandle mov ds:[di].GI_vmFile, bx call ObjMarkDirty call VMGetMapBlock call VMLock pop bx ;bh <- DisplayType push bp ;save handle mov es, ax ;ds <- segment of ;map block ;; now run through the map block and find the set of bitmaps ;; we want given the DisplayType. mov cx, es:[DDS_arrayLength] mov di, offset DDS_DRS - size DeckResStruct ; es:[di] -> first DRS minus one DRS ; to account for how the ; loop's written startLoop: add di, size DeckResStruct cmp bh, es:[di].DRS_displayType loopne startLoop ;es:di = DeckResStruct of resolution map to use. This means we ;default to the last entry in the array if nothing else matches. mov bp, ds:[si] add bp, ds:[bp].Game_offset mov ax, es:[di].DRS_mapBlock mov ds:[bp].GI_mapBlock, ax call ObjMarkDirty mov cx, es:[di].DRS_upSpreadX mov dx, es:[di].DRS_upSpreadY mov ax, MSG_GAME_SET_UP_SPREADS call ObjCallInstanceNoLock mov cx, es:[di].DRS_downSpreadX mov dx, es:[di].DRS_downSpreadY mov ax, MSG_GAME_SET_DOWN_SPREADS call ObjCallInstanceNoLock mov cx, es:[di].DRS_fontSize mov ax, MSG_GAME_SET_FONT_SIZE call ObjCallInstanceNoLock pop bp ;restore mapblock handle push es:[di].DRS_deckSpreadX push es:[di].DRS_deckSpreadY call VMUnlock mov ax, MSG_GAME_GET_VM_FILE call ObjCallInstanceNoLock mov_tr bx, cx ;bx <- vm file handle call VMLock push bp ;save block handle for ;unlocking push ax ;save block segment for later mov di, ds ;di <- game segment mov ds, ax ;ds <- bitmap segment push si mov si, ds:[0].DMS_interior ;*ds:si -> interior region call CopyRegionToChunk pop si Deref_DI Game_offset mov ds:[di].GI_interiorReg, ax call ObjMarkDirty pop ax ;restore block segment mov di, ds ;di <- game segment mov ds, ax ;ds <- bitmap segment push si mov si, ds:[DMS_frame] ;*ds:si -> frame reg call CopyRegionToChunk pop si Deref_DI Game_offset mov ds:[di].GI_frameReg, ax call ObjMarkDirty mov ax, MSG_GAME_SET_CARD_DIMENSIONS call ObjCallInstanceNoLock pop bp call VMUnlock push si mov al, mask OCF_IGNORE_DIRTY ;fade array don't go to state mov bx, size optr ;each element of the array ;will hold an optr clr cx, si call ChunkArrayCreate mov bp, si ;bp <- array offset pop si Deref_DI Game_offset mov ds:[di].GI_fadeArray, bp pop dx pop cx mov ax, MSG_GAME_SETUP_GEOMETRY call ObjCallInstanceNoLock mov ax, MSG_GAME_SEND_CARD_BACK_NOTIFICATION call ObjCallInstanceNoLock ret GameSetupStuff endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetCardDimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_CARD_DIMENSIONS handler for GameClass CALLED BY: PASS: *ds:si = game instance cx, dx = width, height of a card RETURN: nothing DESTROYED: nothing REVISION HISTORY: Name Date Description ---- ---- ----------- jon 27 nov 1992 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetCardDimensions method dynamic GameClass, MSG_GAME_SET_CARD_DIMENSIONS uses cx, dx, bp .enter mov ds:[di].GI_cardWidth, cx mov ds:[di].GI_cardHeight, dx call ObjMarkDirty mov ax, MSG_VIS_SET_SIZE call VisSendToChildren .leave ret GameSetCardDimensions endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetUpSpreads %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_UP_SPREADS handler for GameClass CALLED BY: PASS: *ds:si = game instance cx, dx = x,y spreads for face up cards RETURN: nothing DESTROYED: nothing REVISION HISTORY: Name Date Description ---- ---- ----------- jon 27 nov 1992 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetUpSpreads method dynamic GameClass, MSG_GAME_SET_UP_SPREADS .enter mov ds:[di].GI_upSpreadX, cx mov ds:[di].GI_upSpreadY, dx call ObjMarkDirty mov ax, MSG_DECK_SET_UP_SPREADS call VisSendToChildren .leave ret GameSetUpSpreads endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetDownSpreads %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_DOWN_SPREADS handler for GameClass CALLED BY: PASS: *ds:si = game instance cx, dx = x,y spreads for face down cards RETURN: nothing DESTROYED: nothing REVISION HISTORY: Name Date Description ---- ---- ----------- jon 27 nov 1992 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetDownSpreads method dynamic GameClass, MSG_GAME_SET_DOWN_SPREADS .enter mov ds:[di].GI_downSpreadX, cx mov ds:[di].GI_downSpreadY, dx call ObjMarkDirty mov ax, MSG_DECK_SET_DOWN_SPREADS call VisSendToChildren .leave ret GameSetDownSpreads endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSendCardBackNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: Game method for MSG_GAME_SEND_CARD_BACK_NOTIFICATION Called by: MSG_GAME_SEND_CARD_BACK_NOTIFICATION Pass: *ds:si = Game object ds:di = Game instance Return: nothing Destroyed: ax Comments: Revision History: Name Date Description ---- ------------ ----------- jon Oct 19, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSendCardBackNotification method dynamic GameClass, MSG_GAME_SEND_CARD_BACK_NOTIFICATION uses cx,dx,bp .enter mov bx, size NotifyCardBackChange call GameAllocNotifyBlock jc done call MemLock mov es, ax mov ax, MSG_GAME_GET_VM_FILE call ObjCallInstanceNoLock mov es:[NCBC_vmFile], cx mov es:[NCBC_mapBlock], ax mov di, ds:[si] add di, ds:[di].Game_offset mov ax, ds:[di].GI_cardWidth mov es:[NCBC_cardWidth], ax mov ax, ds:[di].GI_cardHeight mov es:[NCBC_cardHeight], ax call MemUnlock mov dx, GWNT_CARD_BACK_CHANGE mov cx, GAGCNLT_APP_TARGET_NOTIFY_CARD_BACK_CHANGE call GameUpdateControllerLow done: .leave ret GameSendCardBackNotification endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameAllocNotifyBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate the block of memory that will be used to update the UI. CALLED BY: PASS: bx - size to allocate RETURN: bx - block handle carry set if unable to allocate DESTROYED: nothing PSEUDO CODE/STRATEGY: Initialize to zero KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- CDB 1/ 2/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameAllocNotifyBlock proc near uses ax, cx .enter mov ax, bx ; size mov cx, ALLOC_DYNAMIC or mask HF_SHARABLE or \ (mask HAF_ZERO_INIT) shl 8 call MemAlloc jc done mov ax, 1 call MemInitRefCount clc done: .leave ret GameAllocNotifyBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameUpdateControllerLow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Low-level routine to update a UI controller CALLED BY: PASS: bx - Data block to send to controller, or 0 to send null data (on LOST_SELECTION) cx - GenAppGCNListType dx - NotifyStandardNotificationTypes RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- CDB 12/30/91 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameUpdateControllerLow proc far uses ax,bx,cx,dx,di,si,bp .enter ; create the event call MemIncRefCount ;one more reference push bx, cx, si mov ax, MSG_META_NOTIFY_WITH_DATA_BLOCK mov cx, MANUFACTURER_ID_GEOWORKS mov bp, bx ; data block clr bx, si mov di, mask MF_RECORD call ObjMessage ; di is event pop bx, cx, si ; Create messageParams structure on stack mov dx, size GCNListMessageParams ; create stack frame sub sp, dx mov bp, sp mov ss:[bp].GCNLMP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS mov ss:[bp].GCNLMP_ID.GCNLT_type, cx push bx ; data block mov ss:[bp].GCNLMP_block, bx mov ss:[bp].GCNLMP_event, di ; If data block is null, then set the IGNORE flag, otherwise ; just set the SET_STATUS_EVENT flag mov ax, mask GCNLSF_SET_STATUS tst bx jnz gotFlags ornf ax, mask GCNLSF_IGNORE_IF_STATUS_TRANSITIONING gotFlags: mov ss:[bp].GCNLMP_flags, ax mov ax, MSG_GEN_PROCESS_SEND_TO_APP_GCN_LIST mov bx, ds:[LMBH_handle] call MemOwner ; bx <- owner clr si mov di, mask MF_STACK or mask MF_FIXUP_DS call ObjMessage pop bx ; data block add sp, size GCNListMessageParams ; fix stack call MemDecRefCount ; we're done with it .leave ret GameUpdateControllerLow endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameUpdateFadeArray %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_UPDATE_FADE_ARRAY handler for GameClass Manages the chunkarray that keeps track of which cards are fading. Cards send this method to the game object, along with a request to add or remove it from the array. This method also controls the timer used to send fade methods (i.e., it starts and stops the timer when necessary). If a card that already appears in the array asks to be added, or if a card not in the array asks to be removed, no action is taken. CALLED BY: PASS: ds:di = game instance *ds:si = game object ^lcx:dx = card requesting an array change bp = PLEASE_ADD_ME_TO_THE_ARRAY if card wants its OD included in the array, PLEASE_REMOVE_ME_FROM_THE_ARRAY if card wants its OD out of the array CHANGES: If array initially has 0 items, and adds a card to itself, then a timer is started (which tells the game when to fade cards in) and a gstate is created (to fade the cards through). If the array has an item to begin with, and removes it, then the timer is stopped and the gstate destroyed. RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: if (card is already in the array) { if (card wants to be removed) { remove it; } } else { if (card wants to be added) { add it; } } if (array was empty to start with) { if (array is not empty now) { create gstate; start timer; } } else if (array had one element to start with) { if (array is now empty) { stop timer; destroy gstate; } } KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 11/29/90 Added to implement the chunkarray fading mechanism %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PLEASE_ADD_ME_TO_THE_ARRAY = 1 PLEASE_REMOVE_ME_FROM_THE_ARRAY = -1 ADDED_TO_THE_ARRAY = 100 REMOVED_FROM_THE_ARRAY = -100 CARD_FADE_PERIOD = 2 ;Timer ticks between fades GameUpdateFadeArray method GameClass, MSG_GAME_UPDATE_FADE_ARRAY push si mov si, ds:[di].GI_fadeArray ;*ds:si = array push cx call ChunkArrayGetCount ;get initial array pop ax ;length push cx mov cx, ax mov bx, cs mov di, offset FindElementInFadeArray clr ax call ChunkArrayEnum ;check to see whether tst ax ;the card is already jz didntFindCard ;in the array cmp bp, PLEASE_ADD_ME_TO_THE_ARRAY ;if card wants to fade and is je endGameUpdateFadeArray ;already on the list, then done mov di, ax call ChunkArrayDelete ;else get it off the list. mov bp, REMOVED_FROM_THE_ARRAY CallObjectCXDX MSG_CARD_CLEAR_FADING, MF_FIXUP_DS jmp endGameUpdateFadeArray didntFindCard: cmp bp, PLEASE_REMOVE_ME_FROM_THE_ARRAY ;if card wants to be je endGameUpdateFadeArray ;removed and already ;is, then done. call ChunkArrayAppend mov bp, ADDED_TO_THE_ARRAY mov ds:[di].handle, cx mov ds:[di].chunk, dx endGameUpdateFadeArray: pop ax pop si cmp ax, 1 jg done je hadOneCardToBeginWith ;didntHaveCardsToBeginWith: cmp bp, ADDED_TO_THE_ARRAY jne done ; ; we had no cards to begin with, and now we've added one, ; so we need to start a timer and a gstate ; mov ax, MSG_VIS_VUP_CREATE_GSTATE call ObjCallInstanceNoLock mov bx, ds:[LMBH_handle] mov al, TIMER_EVENT_ONE_SHOT mov cx, CARD_FADE_PERIOD mov dx, MSG_GAME_DISTRIBUTE_FADE call TimerStart Deref_DI Game_offset mov ds:[di].GI_gState, bp call ObjMarkDirty if 0 ;;; unnecessary for one shot mov ds:[di].GI_faderHandle, bx call ObjMarkDirty endif jmp done hadOneCardToBeginWith: cmp bp, REMOVED_FROM_THE_ARRAY jne done ; ; we had one card at the beginning, and removed it, so ; we need to stop our fade timer and destroy our gstate ; Deref_DI Game_offset if 0 ;;;changed to one-shot clr bx xchg bx, ds:[di].GI_faderHandle call ObjMarkDirty EC< tst bx > EC< ERROR_Z CANT_STOP_TIMER_WITH_NULL_HANDLE > clr ax ; 0 => continual call TimerStop endif clr bx xchg bx, ds:[di].GI_gState call ObjMarkDirty EC< tst bx > EC< ERROR_Z CANT_DESTROY_GSTATE_WITH_NULL_HANDLE > mov di, bx call GrDestroyState done: ret GameUpdateFadeArray endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindElementInArray %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Callback routine for chunk array to find an OD in the array CALLED BY: ChunkArrayEnum within GameUpdateFadeArray PASS: ds:di = array element ^lcx:dx = card to check CHANGES: RETURN: if card OD matches this element, then: carry set ds:ax = element if card OD doesn't match this element, then carry clear DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindElementInFadeArray proc far cmp ds:[di].chunk, dx jne noMatch cmp ds:[di].handle, cx jne noMatch mov ax, di stc jmp done noMatch: clc done: ret FindElementInFadeArray endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameRegisterDrag %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_REGISTER_DRAG handler for GameClass Stores the OD of the deck dragging cards so that we know to pass on MSG_META_EXPOSED to it. CALLED BY: PASS: ds:di = game instance *ds:si = game object ^lcx:dx = instance of DeckClass CHANGES: RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameRegisterDrag method GameClass, MSG_GAME_REGISTER_DRAG mov ds:[di].GI_dragger.handle, cx ;^lGI_dragger <- OD mov ds:[di].GI_dragger.chunk, dx ;of dragging deck call ObjMarkDirty ret GameRegisterDrag endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDeckSelected %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_DECK_SELECTED handler for GameClass CALLED BY: PASS: ^lcx:dx = selected deck bp = # of card in deck's composite that was selected CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: default action is to send deck a MSG_DECK_DRAG_OR_FLIP KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDeckSelected method GameClass, MSG_GAME_DECK_SELECTED mov bx, cx mov si, dx mov ax, MSG_DECK_DRAG_OR_FLIP mov di, mask MF_FIXUP_DS GOTO ObjMessage GameDeckSelected endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDraw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_VIS_DRAW handler for GameClass CALLED BY: PASS: *ds:si = game object bp = gstate to draw through cl = DrawFlags CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: call super class check to see if we have a dragging deck if so, and if this MSG_VIS_DRAW is an update, tell the deck to draw the dragged cards. KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDraw method GameClass, MSG_VIS_DRAW push cx ;save DrawFlags push bp mov di, offset GameClass CallSuper MSG_VIS_DRAW pop bp ;restore gstate Deref_DI Game_offset mov bx, ds:[di].GI_dragger.handle ;bx <- dragger handle pop cx ;restore DrawFlags tst bx jz dontDrawDragger ;if no dragger, end test cl, mask DF_EXPOSED ;is it an update? jz dontDrawDragger ;if not, end ;drawDragger: ; ; If we have a dragging deck and the call is an update, ; we want to draw the dragged cards in case they went off the ; edge of the screen and came back ; mov si, ds:[di].GI_dragger.chunk mov ax, MSG_DECK_DRAW_DRAGS mov di, mask MF_FIXUP_DS or mask MF_CALL call ObjMessage dontDrawDragger: ret GameDraw endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameUpdateScore %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Updates the score internally and on screen CALLED BY: PASS: ds:di = game instance *ds:si = game object if score is to be zeroed: cx = dx = 0 if score is to be set absolutely but not to 0: cx = value to set score to if score is to be incremented or decremented: cx = 0, dx = amount to add to current score CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: sets up score, time then calls ScoreToTextObject KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 7/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameUpdateScore method GameClass, MSG_GAME_UPDATE_SCORE tst cx ;set score absolutely? jnz continue ;if so, do it tst dx ;setting score to zero? jz continue ;if so, do it ;addToScore: ;otherwise we're adjusting mov cx, ds:[di].GI_score ;the score relatively add cx, dx continue: mov ax, MSG_GAME_CHECK_MINIMUM_SCORE call ObjCallInstanceNoLock ;setScore: mov ds:[di].GI_score, cx ;save the score call ObjMarkDirty mov si, ds:[di].GI_scoreOutput.chunk mov di, ds:[di].GI_scoreOutput.handle ; segmov es, ss call ScoreToTextObject ;write score out ;endGameUpdateScore: ret GameUpdateScore endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameGetBackBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_GET_BACK_BITMAP handler for GameClass Returns a pointer to the bitmap to be drawn as the backside of the deck. CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: nothing RETURN: ^lcx:dx = bitmap DESTROYED: bx, cx, dx PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameGetBackBitmap method GameClass, MSG_GAME_GET_BACK_BITMAP push ds:[di].GI_whichBack mov ax, MSG_GAME_GET_VM_FILE call ObjCallInstanceNoLock mov bx, cx ;bx <- vm file handle mov di, ds:[si] add di, ds:[di].Game_offset pop si ;si <- which back call VMLock push bp test ds:[di].GI_gameAttrs, mask GA_USE_WIN_BACK push ds mov ds, ax jz regularBack mov cx, ds:[DMS_winBack].handle mov dx, ds:[DMS_winBack].chunk jmp unlock regularBack: cmp si, ds:DMS_numBacks jb haveBack ; ; For some reason, the back doesn't exist anymore (most likely, ; there's a new deck file with fewer backs), so we'll just use ; the first one ; clr si haveBack: shl si shl si ;si <- fptr mov cx, ds:DMS_backs[si].handle mov dx, ds:DMS_backs[si].chunk unlock: pop ds pop bp call VMUnlock ret GameGetBackBitmap endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameGetFaceBitmap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_GET_FACE_BITMAP handler for GameClass Returns a pointer to the bitmap to be drawn given a set of card attributes (card must be face up) CALLED BY: PASS: ds:di = game instance *ds:si = game object bp - CardAttrs CHANGES: nothing RETURN: ^lcx:dx = bitmap DESTROYED: cx, dx, di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameGetFaceBitmap method GameClass, MSG_GAME_GET_FACE_BITMAP ;;calculate which card we want, ordered as follows: ;;Ace of Diamonds = 0 ;;2 of Diamonds = 1 ;;... ;;King of Diamonds = 12 ;;Ace of Hearts = 13 ;;... ;;Ace of Clubs = 26 ;;... ;;Ace of Spades = 39 ;;... ;;King of Spades = 51 ; ; ax <- suit * 13 ; diamonds = 0 ; hearts = 1 ; clubs = 2 ; spades = 3 ; mov ax, bp ANDNF ax, mask CA_SUIT rept offset CA_SUIT shr ax endm mov cx, 13 mul cx ; ; ax += rank - 1 ; cx = ax ; mov dx, bp ANDNF dx, mask CA_RANK mov cl, offset CA_RANK shr dx, cl dec dx add ax, dx shl ax shl ax push ax ; ; now that cx has the card number, get the bitmap ; mov ax, MSG_GAME_GET_VM_FILE call ObjCallInstanceNoLock pop di mov_tr bx, cx call VMLock mov ds, ax mov cx, ds:DMS_cards[di].handle mov dx, ds:DMS_cards[di].chunk call VMUnlock ret GameGetFaceBitmap endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDroppingDragCards %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_DROPPING_DRAG_CARDS handler for GameClass This method is called by the dragging deck when the user has released the cards. Game calls children asking for a deck to accept the dropped cards. CALLED BY: DeckEndSelect PASS: *ds:si = game object ^lcx:dx = dropping deck bp = drop card attributes CHANGES: RETURN: if cards are accepted elsewhere, carry is set else carry clear DESTROYED: PSEUDO CODE/STRATEGY: gets deck's drop card attributes, then calls children with drop deck OD and attributes KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDroppingDragCards method GameClass, MSG_GAME_DROPPING_DRAG_CARDS mov ax, MSG_DECK_TAKE_CARDS_IF_OK call VisSendToChildrenWithTest ret GameDroppingDragCards endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameBroadCastDoubleClick %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_BROADCAST_DOUBLE_CLICK handler for GameClass This method is called by a deck when the user double clicks one of its cards. Game calls children asking for a deck to accept the double-clicked card. CALLED BY: DeckCardDoubleClicked PASS: *ds:si = game object ^lcx:dx = double clicked deck bp = attributes of double-clicked card CHANGES: RETURN: if card was accepted elsewhere, carry is set else carry clear DESTROYED: ax PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameBroadcastDoubleClick method GameClass,MSG_GAME_BROADCAST_DOUBLE_CLICK mov ax, MSG_DECK_TAKE_DOUBLE_CLICK_IF_OK call VisSendToChildrenWithTest ret GameBroadcastDoubleClick endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameCheckHilites %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_CHECK_HILITES handler for GameClass Broadcasts to children to hilite themselves if they would be the destination if cards were dropped right now. CALLED BY: DeckOutlinePtr PASS: *ds:si = game object ^lcx:dx = dragging deck bp = card attributes of drop card CHANGES: RETURN: nothing DESTROYED: ax, bp, cx, dx PSEUDO CODE/STRATEGY: Broadcast MSG_DECK_CHECK_POTENTIAL_DROP to children, asking to abort after first potential drop. If no potential drop, send message to self clearing all hilites. KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameCheckHilites method GameClass, MSG_GAME_CHECK_HILITES mov ax, MSG_DECK_CHECK_POTENTIAL_DROP ;see if the current call VisSendToChildrenWithTest ;drag will go anywhere jc endGameCheckHilites ;if so, ok clr cx ;otherwise, clear clr dx ;the hilited slots mov ax, MSG_GAME_REGISTER_HILITED call ObjCallInstanceNoLock endGameCheckHilites: ret GameCheckHilites endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameInvertAcceptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_INVERT_ACCEPTORS handler for GameClass Asks all decks to hilite themselves if they would accept the current drag based on the drop card (not on the current position of the drag) CALLED BY: DeckDraggableCardSelected, DeckEndSelect PASS: *ds:si = game object ^lcx:dx = dragging deck bp = card attributes of drop card CHANGES: RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameInvertAcceptors method GameClass, MSG_GAME_INVERT_ACCEPTORS cmp ds:[di].GI_userMode, BEGINNER_MODE jne done mov ax, MSG_DECK_INVERT_IF_ACCEPT call VisSendToChildren done: ret GameInvertAcceptors endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameMarkAcceptors %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_MARK_ACCEPTORS handler for GameClass Asks all decks to set their DA_WANTS_DRAG bit if they would accept the current drag based on the drop card (not on the current position of the drag) CALLED BY: PASS: *ds:si = game object ^lcx:dx = dragging deck bp = card attributes of drop card CHANGES: RETURN: nothing DESTROYED: ax PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameMarkAcceptors method GameClass, MSG_GAME_MARK_ACCEPTORS push cx,dx ;save dragger OD mov ax, MSG_DECK_MARK_IF_ACCEPT ;tell decks to mark themselves call VisSendToChildren pop cx,dx ;restore dragger OD ;;now we want to unmark any special cases (for example, in ;;klondike, we want to unmark any 2's if we're dragging an ace) mov ax, MSG_GAME_UNMARK_ACCEPTORS call ObjCallInstanceNoLock ;endGameMarkAcceptors: ret GameMarkAcceptors endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameRegisterHilited %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_REGISTER_HILITED handler for GameClass Keeps track of the one (if any) deck that is currently hilited. Also issues a MSG_DECK_INVERT to this deck if it is just now getting hilited (vs. having been hilited for multiple calls already). Also re-inverts the used-to-be hlited deck (if any), to make it unhilited. CALLED BY: GameCheckHilites, DeckCheckPotentialDrop, DeckEndSelect PASS: ds:di = game instance *ds:si = game object ^lcx:dx = hilited deck (cx = dx = 0 for no hilited deck) CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, di PSEUDO CODE/STRATEGY: if (old hilited = new hilited) { don't do anything } else { if (handle != 0) { invert new hilited } GI_hilited = new hilited invert old hilited } KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameRegisterHilited method GameClass, MSG_GAME_REGISTER_HILITED cmp ds:[di].GI_hilited.chunk, dx ;old hilited = new? je endGameRegisterHilited ;if so, done jcxz swap ;new hilited = 0? ;if so, erase old CallObjectCXDX MSG_DECK_INVERT, MF_FIXUP_DS ;else invert new swap: Deref_DI Game_offset xchg ds:[di].GI_hilited.handle, cx ;GI_hilited <- new xchg ds:[di].GI_hilited.chunk, dx ;^lcx:dx <- old call ObjMarkDirty jcxz endGameRegisterHilited ; ; Forcing this to the queue is a hack that solved ; a visual bug in intermediate mode klondike... ; CallObjectCXDX MSG_DECK_CLEAR_INVERTED, MF_FORCE_QUEUE endGameRegisterHilited: ret GameRegisterHilited endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameCollectAllCards %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_COLLECT_ALL_CARDS handler for GameClass Takes all the cards from all the decks and gives them to the hand. CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: nothing DESTROYED: ax, cx, dx PSEUDO CODE/STRATEGY: tell all decks to give their cards to the hand object redraw the screen KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameCollectAllCards method GameClass, MSG_GAME_COLLECT_ALL_CARDS mov cx, ds:[di].GI_hand.handle ;^lcx:dx <- hand mov dx, ds:[di].GI_hand.chunk mov ax, MSG_DECK_GET_RID_OF_CARDS ;tell all decks to return ;cards to hand call VisSendToChildren mov ax, MSG_VIS_INVALIDATE ;redraw the screen call ObjCallInstanceNoLock ret GameCollectAllCards endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% VisSendToChildrenWithTest %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Calls children in order with a given method and data, and stops after the first one that returns carry set. (Just like VisSendToChildren, except tests abort on carry) CALLED BY: GameDroppingDragCards, GameBroadcastDoubleClick, GameCheckHilites PASS: *ds:si = game object ax = method to call children with cx, dx, bp = other data (if any) CHANGES: RETURN: if any child returned carry set, carry is returned set if no child returned carry set, carry is returned clear DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ VisSendToChildrenWithTest proc far class GameClass ; Indicate function is a friend ; of GameClass so it can play with ; instance data. clr bx ; initial child (first push bx ; child of composite) push bx mov bx, offset VI_link ; Pass offset to LinkPart push bx clr bx ; Use standard function push bx mov di, OCCT_SAVE_PARAMS_TEST_ABORT push di mov bx, offset Vis_offset mov di, offset VCI_comp ;DO NOT CHANGE THIS TO A GOTO! We are passing stuff on the stack. call ObjCompProcessChildren ;must use a call (no GOTO) since ;parameters are passed on the stack ret VisSendToChildrenWithTest endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ScoreToTextObject %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Creates a score string and sets the Text Object to display this string. CALLED BY: GameUpdateScore PASS: DS = Relocatable segment DI:SI = Block:chunk of TextObject CX = Score RETURN: Nothing DESTROYED: AX, BX, CX, DX, BP PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 8/6/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SCORE_BUFFER_SIZE = 14 ScoreToTextObject proc far uses di, es .enter mov bx, di ; BX:SI is the TextEditObject segmov es, ss, dx ; SS to ES and DX! sub sp, SCORE_BUFFER_SIZE ; allocate room on the stack mov di, sp ; ES:DI => buffer to fill mov bp, di ; buffer also in DX:BP call CreateScoreString ; create the string clr cx ; string is NULL terminated mov ax, MSG_VIS_TEXT_REPLACE_ALL_PTR mov di, mask MF_FIXUP_DS or mask MF_CALL call ObjMessage ; send the method add sp, SCORE_BUFFER_SIZE ; restore the stack .leave ret ScoreToTextObject endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateScoreString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create the score text string CALLED BY: ScoreToTextObject PASS: cx = score ES:DI = String buffer to fill RETURN: ES:DI = Points to end of string (NULL termination) DESTROYED: Nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 8/6/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CreateScoreString proc near uses ax, bx, cx, dx .enter ; Create the score ; mov ax, cx call WriteNum ;Done: SBCS < mov {char}es:[di], 0 ; NULL terminated > DBCS < mov {wchar}es:[di], 0 ; NULL terminated > .leave ret CreateScoreString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% WriteNum %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Converts a number to ASCII, and writes it into a buffer CALLED BY: CreateScoreString, WriteTime PASS: ES:DI = Start of string buffer AX = Value to write RETURN: ES:DI = Updated to next string position DESTROYED: AX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 8/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ WriteNum proc far push ax, bx, cx, dx ;save regs. necessary? clr bx ;# digits so far tst ax ;negative or positive? jge readValue ;negative: SBCS < mov {byte} es:[di],'-' ;if negative, add a '-' > DBCS < mov {wchar} es:[di],'-' ;if negative, add a '-' > LocalNextChar esdi ;advance pointer neg ax ;turn value positive readValue: mov cx, 10 ; put divisor in DL startReadLoop: clr dx ;we're dividing dx:ax, ;so we need to clear dx div cx ; do the division push dx ;here's our remainder inc bx ;one more digit... cmp ax, 0 ; check the quotient jg startReadLoop ;endReadLoop: mov cx, bx ;cx <- total # of digits DBCS < shl cx, 1 ;cx <- total # of bytes > clr bx ;bx <- # digits printed so far startWriteLoop: pop dx ;pop digit add dl, '0' ;make it a char SBCS < mov {byte} es:[di][bx], dl ;write it to string > DBCS < mov {wchar} es:[di][bx], dx ;write it to string > LocalNextChar esbx ;note we've written another cmp bx, cx ;done yet? jl startWriteLoop ;endWriteLoop: add di, cx ;point di after string pop ax, bx, cx, dx ;restore regs ret WriteNum endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% WriteTime %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Converts a time to ASCII, and writes it into a buffer CALLED BY: CreatetTimeString PASS: ES:BP = Start of string buffer AX = # of seconds RETURN: nothing DESTROYED: AX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Jon 8/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ WriteTime proc far uses ax, bx, cx, dx, si, di .enter ; ; ch <- hours ; dl <- minutes ; dh <- seconds mov cx, 3600 clr dx div cx ;ax <- hours, dx <- seconds mov ch, al mov ax, dx clr dx mov bx, 60 div bx ;ax <- minutes; dx <- seconds mov dh, dl mov dl, al mov si, DTF_HMS_24HOUR tst ch jnz callLocal mov si, DTF_MS callLocal: mov di, bp call LocalFormatDateTime .leave ret WriteTime endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetDonor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_DONOR handler for GameClass. Stores OD of the deck giving cards to another so we can undo if need be. CALLED BY: PASS: ds:di = game instance *ds:si = game object ^lcx:dx = donating deck CHANGES: GI_lastDonor <- ^lcx:dx Undo trigger is enabled RETURN: nothing DESTROYED: bp, di PSEUDO CODE/STRATEGY: store away info and enable undo button KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetDonor method GameClass, MSG_GAME_SET_DONOR mov ds:[di].GI_lastDonor.handle, cx mov ds:[di].GI_lastDonor.chunk, dx mov bp, ds:[di].GI_score ;preserve the score so mov ds:[di].GI_lastScore, bp ;we can undo that, too. call ObjMarkDirty mov ax, MSG_GAME_ENABLE_UNDO ;since we have the info call ObjCallInstanceNoLock ;to do an undo, let's ;allow it ret GameSetDonor endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameEnableUndo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_ENABLE_UNDO handler for GameClass Sends a MSG_GEN_SET_ENABLED to the undo trigger CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: nothing RETURN: nothing DESTROYED: ax, bx, dx, di, si PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameEnableUndo method GameClass, MSG_GAME_ENABLE_UNDO mov dl, VUM_NOW mov bx, ds:[di].GI_undoTrigger.handle mov si, ds:[di].GI_undoTrigger.chunk mov ax, MSG_GEN_SET_ENABLED mov di, mask MF_FIXUP_DS GOTO ObjMessage GameEnableUndo endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDisableUndo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_DISABLE_UNDO handler for GameClass Sends a MSG_GEN_SET_NOT_ENABLED to the undo trigger CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: nothing RETURN: nothing DESTROYED: ax, bx, dx, di, si PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDisableUndo method GameClass, MSG_GAME_DISABLE_UNDO mov dl, VUM_NOW mov bx, ds:[di].GI_undoTrigger.handle mov si, ds:[di].GI_undoTrigger.chunk mov ax, MSG_GEN_SET_NOT_ENABLED mov di, mask MF_FIXUP_DS GOTO ObjMessage GameDisableUndo endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameQueryDragCard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_QUERY_DRAG_CARD handler for GameClass This is the method that a deck calls when one of its cards is selected. This method determines whether a given card should be included in the drag or not, depending on the deck's attributes. For example, in the following scenario: +--------------------+ ! ! ! 6 Hearts ! ! ! +--------------------+ ! ! ! 5 Clubs ! ! ! +--------------------+ ! ! ! 4 Diamonds ! ! ! +--------------------+ ! ! ! 3 Clubs ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! +--------------------+ if the 4 is selected, and we are playing klondike with the windows-type extension, we want to drag the 3 and the 4; we would make three calls to this method; calls concering the 3 and 4 would indicate that the cards should be draggedf, whereas the 5 would be rejected. CALLED BY: PASS: ds:di = game instance *ds:si = game object ch = # of selected card ;(the 4 in the above example) cl = attrs of selected card ;(the 4 in the above example) dh = # of query card dl = attrs of query card bp = deck attrs CHANGES: RETURN: carry set if accept carry clear if no accept DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 9/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameQueryDragCard method GameClass, MSG_GAME_QUERY_DRAG_CARD ANDNF bp, mask DA_DDWC ;filter through ;the info on which ;cards to drag cmp bp, DDWC_NONE shl offset DA_DDWC ;check if this deck ;drags cards at all jne notNone ;none: clc ;if the deck doesn't jmp endGameQueryDragCard ;drag cards, then ;clear the carry and ;return notNone: cmp bp, DDWC_TOP_ONLY shl offset DA_DDWC jne notTopOnly ;topOnly: tst ch ;if we can only drag the top card, see jz selectedIsTop ;if the selected card is the top clc jmp endGameQueryDragCard selectedIsTop: tst dh ;if selected = query = top card, then accept jz nIsTop clc jmp endGameQueryDragCard nIsTop: stc jmp endGameQueryDragCard notTopOnly: cmp bp, DDWC_UNTIL_SELECTED shl offset DA_DDWC jne notUntilSelected ;untilSelected: ;if we're dragging all cards above and cmp dh, ch ;including the selected card, see if jg queryGreater ;query card is <= selected card ;queryNotGreater: stc jmp endGameQueryDragCard queryGreater: clc jmp endGameQueryDragCard notUntilSelected: ;must be DDWC_TOP_OR_UPS tst ch ;selected = top card? jnz ups ;if not, drag all up cards ;top: tst dh ;if so, see if query = top jnz topSelectedAndQueryNotTop stc jmp endGameQueryDragCard topSelectedAndQueryNotTop: clc jmp endGameQueryDragCard ups: test dl, mask CA_FACE_UP ;we want all up cards, so see jnz cardIsUp ;if query card is face up. clc jmp endGameQueryDragCard cardIsUp: stc endGameQueryDragCard: ret GameQueryDragCard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDistributeFade %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_DISTRIBUTE_FADE handler for GameClass Sends a MSG_CARD_FADE_DRAW to every card in the fade array. CALLED BY: A timer PASS: ds:di = game instance *ds:si = game object CHANGES: any fading cards fade in one more step RETURN: nothing DESTROYED: ax, bx, cx, bp, di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDistributeFade method GameClass, MSG_GAME_DISTRIBUTE_FADE push ds:[LMBH_handle], si mov bp, ds:[di].GI_gState mov cl, ds:[di].GI_incrementalFadeMask mov si, ds:[di].GI_fadeArray mov bx, cs mov di, offset SendCardMethodFade call ChunkArrayEnum ; ; If there're still cards in the array, we need to start another timer ; call ChunkArrayGetCount ;get initial array pop bx, si jcxz done mov al, TIMER_EVENT_ONE_SHOT mov cx, CARD_FADE_PERIOD mov dx, MSG_GAME_DISTRIBUTE_FADE call TimerStart done: ret GameDistributeFade endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendCardMethodFade %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Callback routine for fading that sends a MSG_CARD_FADE_DRAW to a card CALLED BY: ChunkArrayEnum in GameDistributeFade PASS: ds:di = array element bp = gstate to draw through cl = incremental fade mask CHANGES: RETURN: nothing DESTROYED: ax, bx, di, si PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 11/29/90 This callback routine was added when the fade mechanism was rewritten to incorporate the chunkarray %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendCardMethodFade proc far mov bx, ds:[di].handle mov si, ds:[di].chunk mov di, mask MF_FIXUP_DS mov ax, MSG_CARD_FADE_DRAW call ObjMessage clc ;continue the enumeration ret SendCardMethodFade endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameZeroFadeArray %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_ZERO_FADE_ARRAY handler for GameClass Informs all the cards in the fade array that they are done fading (like it or not), then clears the array and stops the timer (if any) and destroys the gstate (if any). CALLED BY: PASS: ds:di = game instance CHANGES: clears the fade array, tells any cards that were there that they're done fading, kills the timer and gstate RETURN: nothing DESTROYED: ax, bx, cx, dx, PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 11/29/90 Added to implement chunkarray fading %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameZeroFadeArray method GameClass, MSG_GAME_ZERO_FADE_ARRAY push si ;save offset mov si, ds:[di].GI_fadeArray call ChunkArrayGetCount jcxz done if 0 ;;;unnecessary for one shot timer clr bx xchg bx, ds:[di].GI_faderHandle EC< tst bx > EC< ERROR_Z CANT_STOP_TIMER_WITH_NULL_HANDLE > clr ax ; 0 => continual call TimerStop endif clr bx xchg bx, ds:[di].GI_gState EC< tst bx > EC< ERROR_Z CANT_DESTROY_GSTATE_WITH_NULL_HANDLE > mov di, bx call GrDestroyState mov bx, cs mov di, offset SendCardMethodClearFading call ChunkArrayEnum call ChunkArrayZero done: pop si ;restore offset call ObjMarkDirty ret GameZeroFadeArray endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendCardMethodClearFading %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Callback routine that sends a card a method informing it that it should mark itself as done fading, CALLED BY: ChunkArrayEnum in GameZeroFadeArray PASS: ds:di = array element CHANGES: card in array element gets its CA_FADING bit cleared RETURN: nothing DESTROYED: ax, bx, di, si PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 11/29/90 Added to implement chunkarray fading %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendCardMethodClearFading proc far mov bx, ds:[di].handle mov si, ds:[di].chunk mov di, mask MF_FIXUP_DS mov ax, MSG_CARD_CLEAR_FADING call ObjMessage clc ret SendCardMethodClearFading endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSeedRandom %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SEED_RANDOM CALLED BY: PASS: ds:di = game instance *ds:si = game object dx = seed CHANGES: nothing RETURN: nothing DESTROYED: di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSeedRandom method GameClass, MSG_GAME_SEED_RANDOM mov ds:[di].GI_randomSeed, dx call ObjMarkDirty ret GameSeedRandom endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameRandom %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return a random number between 0 and DL CALLED BY: PASS: ds:di = game instance *ds:si = game object DL = max for returned number RETURN: DX = number between 0 and DL DESTROYED: AX PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: This random number generator is not a very good one; it is sufficient for a wide range of tasks requiring random numbers (it will work fine for shuffling, etc.), but if either the "randomness" or the distribution of the random numbers is crucial, you may want to look elsewhere. REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 1/11/89 Initial version jon 10/90 Customized for GameClass %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameRandom method GameClass, MSG_GAME_RANDOM mov cx, dx mov ax, ds:[di].GI_randomSeed mov dx, 4e6dh mul dx mov ds:[di].GI_randomSeed, ax call ObjMarkDirty sar dx, 1 ror ax, 1 sar dx, 1 ror ax, 1 sar dx, 1 ror ax, 1 sar dx, 1 ror ax, 1 push ax mov al, 255 mul cl mov dx, ax pop ax Random2: sub ax, dx ja Random2 add ax, dx div cl clr dx mov dl, ah ret GameRandom endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDrawBlankCard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_DRAW_BLANK_CARD handler for GameClass CALLED BY: PASS: ds:di = game instance *ds:si = game object bp = gstate to draw through cx,dx = left,top of card CHANGES: nothing RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDrawBlankCard method GameClass, MSG_GAME_DRAW_BLANK_CARD push ds:[di].GI_frameReg mov si, ds:[di].GI_interiorReg mov si, ds:[si] mov di, bp mov ax, cx mov bx, dx call GrDrawRegion push ax mov ax, C_BLACK call GrSetAreaColor pop ax pop si mov si, ds:[si] call GrDrawRegion ret GameDrawBlankCard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameDrawFrame %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: CALLED BY: PASS: CHANGES: RETURN: DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 12/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameDrawFrame method GameClass, MSG_GAME_DRAW_FRAME push ds:[di].GI_frameReg mov di, bp mov ax, C_BLACK call GrSetAreaColor mov ax, cx mov bx, dx pop si mov si, ds:[si] call GrDrawRegion ret GameDrawFrame endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameFakeBlankCard %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_FAKE_BLANK_CARD handler for GameClass Draws a faked blank card (a black-bordered write rectangle the size of a card) at the specified place CALLED BY: PASS: ds:di = game instance *ds:si = game object cx,dx = left,top of fake blank card bp = gstate to draw through CHANGES: RETURN: nothing DESTROYED: ax, bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameFakeBlankCard method GameClass, MSG_GAME_FAKE_BLANK_CARD mov ax, cx mov bx, dx mov cx, ds:[di].GI_cardWidth mov dx, ds:[di].GI_cardHeight dec cx dec dx add cx, ax add dx, bx mov di, bp call GrFillRect push ax mov ax, C_BLACK call GrSetAreaColor pop ax call GrDrawRect ret GameFakeBlankCard endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameShutdown %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SHUTDOWN handler for GameClass Takes care of things that need to be taken care of before exiting the application (e.g., turn off the fade timer, etc.) CALLED BY: PASS: *ds:si = game object CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameShutdown method GameClass, MSG_GAME_SHUTDOWN ; ; Stop any fading ; mov ax, MSG_GAME_ZERO_FADE_ARRAY call ObjCallInstanceNoLock ret GameShutdown endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CopyRegionToChunk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copies a passed region into a passed lmem chunk CALLED BY: GameSetupStuff PASS: ds:si = region di = object block segment CHANGES: RETURN: *di:ax = newly copied region (suitable for drawing) cx = region width dx = region height DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CopyRegionToChunk proc near push si call GrGetPtrRegBounds ;si <- end reg, ;ax,bx <- left, top ;cx,dx <- right, bottom sub cx, ax inc cx ;cx <- width sub dx, bx inc dx ;dx <- height pop bx push ds mov ds, di ;di <- bitmap segment pop di ;ds <- game segment push cx, dx ;save width, height mov cx, bx xchg cx, si ;cx <- end, si <- start sub cx, si ;cx <- size of region add cx, size Rectangle mov al, mask OCF_IGNORE_DIRTY ; ObjChunkFlags for new ; chunk call LMemAlloc ;get space to store our ;region push es ;save dgroup segmov es, ds ;es <- game segment mov ds, di ;ds <- bitmap segment mov di, ax mov di, es:[di] ; *es:di = clear space push ax, cx, si call GrGetPtrRegBounds stosw mov ax, bx stosw mov ax, cx stosw mov ax, dx stosw pop ax, cx, si sub cx, size Rectangle ;;at this point, cx = size of region, ;; *ds:si = original region ;; *es:di = empty space for us to copy region into rep movsb ; copy region in segmov ds, es pop es ; restore dgroup pop cx, dx ;region width, height ret CopyRegionToChunk endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameVupQuery %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_VIS_VUP_QUERY handler for GameClass. CALLED BY: PASS: *ds:si = game object cx = VisUpwardQueryType CHANGES: RETURN: depends on a lot of things... DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameVupQuery method GameClass, MSG_VIS_VUP_QUERY cmp cx, VUQ_GAME_OD jne checkAttrs mov cx, ds:[LMBH_handle] mov dx, si jmp markQueryHandled checkAttrs: cmp cx, VUQ_GAME_ATTRIBUTES jne checkFadeMask mov cl, ds:[di].GI_gameAttrs jmp markQueryHandled checkFadeMask: cmp cx, VUQ_INITIAL_FADE_MASK jne checkBitmaps mov cl, ds:[di].GI_initialFadeMask jmp markQueryHandled checkBitmaps: cmp cx, VUQ_CARD_BITMAP jne checkDimensionQuery mov ax, MSG_GAME_GET_BACK_BITMAP test bp, mask CA_FACE_UP ;see if card is face down jz getBitmap mov ax, MSG_GAME_GET_FACE_BITMAP getBitmap: call ObjCallInstanceNoLock jmp markQueryHandled checkDimensionQuery: cmp cx, VUQ_CARD_DIMENSIONS jne passItOnUp mov cx, ds:[di].GI_cardWidth mov dx, ds:[di].GI_cardHeight markQueryHandled: stc jmp endGameVupQuery passItOnUp: clc endGameVupQuery: ret GameVupQuery endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameVisOpen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_VIS_OPEN handler for GameClass game marks itself as visually open, then calls superclass CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameVisOpen method GameClass, MSG_VIS_OPEN RESET ds:[di].GI_gameAttrs, GA_ICONIFIED call ObjMarkDirty mov di, offset GameClass CallSuper MSG_VIS_OPEN ret GameVisOpen endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameVisClose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_VIS_CLOSE handler for GameClass Makes sure that all fading cards are stopped here, then calls superclass CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameVisClose method GameClass, MSG_VIS_CLOSE SET ds:[di].GI_gameAttrs, GA_ICONIFIED call ObjMarkDirty ; ; Stop any fading ; mov ax, MSG_GAME_ZERO_FADE_ARRAY call ObjCallInstanceNoLock mov di, offset GameClass mov ax, MSG_VIS_CLOSE CallSuper MSG_VIS_CLOSE ret GameVisClose endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameReloc %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Clear out the optr of the cardback-selection summons when we're first brought in from the resource or state. CALLED BY: MSG_META_RELOCATE/MSG_META_UNRELOCATE PASS: *ds:si = game object ds:di = GameInstance ax = MSG_META_RELOCATE/MSG_META_UNRELOCATE RETURN: carry set on error DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: c REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 11/ 1/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameReloc method GameClass, reloc .enter cmp ax, MSG_META_RELOCATE jne done mov ds:[di].GI_faderHandle, 0 mov ds:[di].GI_gState, 0 mov ds:[di].GI_vmFile, 0 call ObjMarkDirty done: clc .leave mov di, offset GameClass call ObjRelocOrUnRelocSuper ret GameReloc endp if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameChangeBack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Gives user a summons through which she can select among possible card backs CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameChangeBack method GameClass, MSG_GAME_CHANGE_BACK mov cx, ds:[di].GI_backSummons.handle mov dx, ds:[di].GI_backSummons.chunk jcxz createSummons haveSummons: CallObjectCXDX MSG_GEN_INTERACTION_INITIATE, MF_FIXUP_DS ret createSummons: mov ax, MSG_GAME_CREATE_BACK_SUMMONS call ObjCallInstanceNoLock Deref_DI Game_offset mov ds:[di].GI_backSummons.handle, cx mov ds:[di].GI_backSummons.chunk, dx call ObjMarkDirty jmp haveSummons GameChangeBack endm endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameChooseBack %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Change the backs of all the cards to match the one the user has chosen. CALLED BY: MSG_GAME_CHOOSE_BACK PASS: ds:di = game instance *ds:si = game object cx - which back RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jon 11/ 1/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameChooseBack method GameClass, MSG_GAME_CHOOSE_BACK ;; user has the right to get rid of the win back, if ;; he so chooses... RESET ds:[di].GI_gameAttrs, GA_USE_WIN_BACK mov ds:[di].GI_whichBack, cx call ObjMarkDirty mov ax, MSG_DECK_CHANGE_KIDS_BACKS call VisSendToChildren mov ax, MSG_DECK_REDRAW call VisSendToChildren ret GameChooseBack endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetFadeParameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_FADE_PARAMETERS handler for GameClass Sets the value of the initial and incremental area masks to use while fading cards in. CALLED BY: PASS: ds:di = game instance *ds:si = game object dl = initial area mask (e.g., SDM_0 for full-fledged fading, SDM_100 for no fading). cl = incremental area mask (e.g., SDM_25 - SDM_0) CHANGES: RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 10/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetFadeParameters method GameClass, MSG_GAME_SET_FADE_PARAMETERS mov ds:[di].GI_incrementalFadeMask, cl mov ds:[di].GI_initialFadeMask, dl call ObjMarkDirty ret GameSetFadeParameters endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameGetDragType %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_GET_DRAG_TYPE handler for GameClass Returns the drag mode we're in (i.e., full or outline drag) CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: nothing RETURN: cl = DragType DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameGetDragType method GameClass, MSG_GAME_GET_DRAG_TYPE mov cl, ds:[di].GI_dragType ret GameGetDragType endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetDragType %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_DRAG_TYPE handler for GameClass Sets the drag mode to the passed value CALLED BY: PASS: ds:di = game instance *ds:si = game object cl = DragType CHANGES: RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetDragType method GameClass, MSG_GAME_SET_DRAG_TYPE mov ds:[di].GI_dragType, cl call ObjMarkDirty ret GameSetDragType endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameGetUserMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_GET_USER_MODE handler for GameClass Returns UserMode (Beginner, Intermediate, Advanced) CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: cl = UserMode DESTROYED: cl PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameGetUserMode method GameClass, MSG_GAME_GET_USER_MODE mov cl, ds:[di].GI_userMode ret GameGetUserMode endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameSetUserMode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_SET_USER_MODE handler for GameClass Sets the user mode to the passed value CALLED BY: PASS: ds:di = game instance *ds:si = game object cl = desired UserMode CHANGES: RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameSetUserMode method GameClass, MSG_GAME_SET_USER_MODE mov ds:[di].GI_userMode, cl call ObjMarkDirty ret GameSetUserMode endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameHandSelected %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_HAND_SELECTED handler for GameClass This is actually a method that will be widely subclassed, but I'm putting in this default handler 'cause I get off on these things. CALLED BY: PASS: ds:di = game instance *ds:si = game object CHANGES: RETURN: nothing DESTROYED: PSEUDO CODE/STRATEGY: default is to send self MSG_GAME_DECK_SELECTED with the deck = the hand and the selected card = the top card KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 12/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameHandSelected method GameClass, MSG_GAME_HAND_SELECTED mov cx, ds:[di].GI_hand.handle mov dx, ds:[di].GI_hand.offset clr bp mov ax, MSG_GAME_DECK_SELECTED call ObjCallInstanceNoLock ret GameHandSelected endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CBLESetup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set up a CardBackListEntry object CALLED BY: MSG_CBLE_SETUP PASS: ds:di = game instance *ds:si = CardBackListEntry object ds:di = CardBackListEntryInstance cx:dx = VM handle and offset of bitmap to show bp = VM File handle of deck RETURN: nothing DESTROYED: ax, bx, cx, dx, si, di, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 11/ 1/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if 0 CBLESetup method CardBackListEntryClass, MSG_CBLE_SETUP .enter ; ; Record the handle and offset of our color-with-bitmap thingummy ; mov ds:[di].CBLE_bitmap.handle, cx mov ds:[di].CBLE_bitmap.offset, dx mov ds:[di].CBLE_file, bp push cx mov cx, size VisMoniker + size OpEndString mov ax, mask OCF_IGNORE_DIRTY call LMemAlloc mov di, ax mov di, ds:[di] ; ; Initialize the visual moniker we're going to give ourselves. The ; thing is an empty string with the height and width of the bitmap ; we're displaying (so our entry is the right size on-screen). ; mov ds:[di].VM_type, VisMonikerType < 0, ; not a list 1, ; is a gstring VMAR_NORMAL, ; regular aspect DC_COLOR_4 ; color type (no one cares) > pop cx push ax xchg ax, cx mov bx, bp call VMLock mov es, ax mov bx, dx mov cx, es:[bx+2].B_width mov dx, es:[bx+2].B_height call VMUnlock mov ds:[di].VM_size.XYS_width, cx mov ds:[di].VM_size.XYS_height, dx mov ({OpEndString}ds:[di].VM_data).OES_opcode, GR_END_STRING ; ; Now set the chunk as our moniker. ; mov di, ds:[si] add di, ds:[di].Gen_offset pop ds:[di].GI_visMoniker call ObjMarkDirty .leave ret CBLESetup endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CBLEDraw %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a CardBackListEntry properly CALLED BY: MSG_VIS_DRAW PASS: *ds:si = CardBackListEntry object bp = gstate to use RETURN: nothing DESTROYED: ? PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ardeb 11/ 1/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CBLEDraw method CardBackListEntryClass, MSG_VIS_DRAW .enter ; ; Let our superclass do its list-entry thing. ; push bp mov di, offset CardBackListEntryClass CallSuper MSG_VIS_DRAW pop di ; ; Now figure our actual width and height and save our origin. ; mov bx, ds:[si] add bx, ds:[bx].Vis_offset push ds:[bx].VI_bounds.R_left push ds:[bx].VI_bounds.R_top mov cx, ds:[bx].VI_bounds.R_right sub cx, ds:[bx].VI_bounds.R_left inc cx mov dx, ds:[bx].VI_bounds.R_bottom sub dx, ds:[bx].VI_bounds.R_top inc dx ; ; Lock down our bitmap. ; mov bx, ds:[si] add bx, ds:[bx].Gen_offset mov ax, ds:[bx].CBLE_bitmap.handle mov si, ds:[bx].CBLE_bitmap.offset mov bx, ds:[bx].CBLE_file call VMLock mov ds, ax ; ; Set the area color properly. ; lodsw call GrSetAreaColor ; ; Figure where to position the bitmap by taking the difference of our ; actual width/height and the bitmap's width/height, dividing it by ; two and adding it to our origin. ; sub cx, ds:[si].B_width sub dx, ds:[si].B_height shr cx shr dx pop ax add ax, dx xchg bx, ax pop ax add ax, cx ; ; Draw the bitmap itself. ; clr dx ; no callback... call GrDrawBitmap ; ; Unlock the bitmap. ; call VMUnlock ; ; Return gstate in bp, in case it's needed there... ; mov bp, di .leave ret CBLEDraw endp endif GameGetWhichBack method GameClass, MSG_GAME_GET_WHICH_BACK mov cx, ds:[di].GI_whichBack ret GameGetWhichBack endm GameSetWhichBack method GameClass, MSG_GAME_SET_WHICH_BACK mov ds:[di].GI_whichBack, cx call ObjMarkDirty ret GameSetWhichBack endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameTransferringCards %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_TRANSFERRING_CARDS handler for GameClass This is called by the donor deck when cards are dropped and transferred to another deck. Makes a good message to intercept for generating sound. CALLED BY: Donor deck object PASS: ds:di = game instance *ds:si = game object ^lcx:dx = deck to which cards will be transferred CHANGES: nothing RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameTransferringCards method GameClass, MSG_GAME_TRANSFERRING_CARDS ret GameTransferringCards endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GameTransferFailed %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: MSG_GAME_TRANSFER_FAILED handler for GameClass This is called by the source deck when cards are dropped and no deck accepts them, just prior to animating the failed transfer. Makes a good message to intercept for generating sound. CALLED BY: Source deck object PASS: ds:di = game instance *ds:si = game object ^lcx:dx = source deck CHANGES: nothing RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- jon 8/90 initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GameTransferFailed method GameClass, MSG_GAME_TRANSFER_FAILED ret GameTransferFailed endm CardsCodeResource ends
; A129362: a(n) = Sum_{k=floor((n+1)/2)..n} J(k+1), J(k) = A001045(k). ; 1,1,4,8,19,37,80,160,331,661,1344,2688,5419,10837,21760,43520,87211,174421,349184,698368,1397419,2794837,5591040,11182080,22366891,44733781,89473024,178946048,357903019,715806037,1431633920,2863267840,5726579371,11453158741,22906404864,45812809728,91625794219,183251588437,366503526400,733007052800,1466014804651,2932029609301,5864060616704,11728121233408,23456245263019,46912490526037,93824986644480,187649973288960,375299957762731,750599915525461,1501199853420544,3002399706841088,6004799458421419,12009598916842837,24019197923164160,48038395846328320,96076791871613611,192153583743227221,384307167844368384,768614335688736768,1537228672093301419,3074457344186602837,6148914689804861440,12297829379609722880,24595658762082757291,49191317524165514581,98382635054057652224,196765270108115304448,393530540227683855019,787061080455367710037,1574122160933641912320,3148244321867283824640,6296488643780380633771,12592977287560761267541,25185954575213148504064,50371909150426297008128,100743818301035845954219,201487636602071691908437,402975273204509887692800,805950546409019775385600,1611901092818772558523051,3223802185637545117046101,6447604371276556249595904,12895208742553112499191808,25790417485109157029391019,51580834970218314058782037,103161669940442492179578880,206323339880884984359157760,412646679761781696842345131,825293359523563393684690261,1650586719047150243617439744,3301173438094300487234879488,6602346876188647886965877419,13204693752377295773931754837,26409387504754685372855746560,52818775009509370745711493120,105637550019018929141407460011,211275100038037858282814920021,422550200076076091865598787584,845100400152152183731197575168 add $0,2 seq $0,297619 ; a(n) = 2*a(n-1) + 2*a(n-2) - 4*a(n-3), a(1) = 0, a(2) = 0, a(3) = 8. sub $0,8 div $0,12 add $0,1
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r9 push %rbp push %rdx lea addresses_WT_ht+0x18693, %r9 nop nop sub %rdx, %rdx movb $0x61, (%r9) and $19235, %r12 pop %rdx pop %rbp pop %r9 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r15 push %rax push %rcx push %rdi push %rsi // Load lea addresses_normal+0x19f39, %r13 nop add %rdi, %rdi mov (%r13), %r15 nop nop dec %rax // Store lea addresses_A+0x1089, %r15 nop nop nop nop sub $32651, %r10 mov $0x5152535455565758, %r13 movq %r13, %xmm0 and $0xffffffffffffffc0, %r15 movntdq %xmm0, (%r15) nop nop nop nop nop sub %r13, %r13 // REPMOV lea addresses_RW+0x7689, %rsi lea addresses_PSE+0x16e69, %rdi nop nop and %r15, %r15 mov $26, %rcx rep movsq nop nop nop mfence // Faulty Load lea addresses_WC+0x1c289, %r12 nop nop nop nop nop add %r15, %r15 mov (%r12), %di lea oracles, %r10 and $0xff, %rdi shlq $12, %rdi mov (%r10,%rdi,1), %rdi pop %rsi pop %rdi pop %rcx pop %rax pop %r15 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_A', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 5}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_RW'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_PSE'}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1}} {'38': 21829} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
MonsterNames: db "RHYDON@@@@" db "KANGASKHAN" db "NIDORAN♂@@" db "CLEFAIRY@@" db "SPEAROW@@@" db "VOLTORB@@@" db "NIDOKING@@" db "SLOWBRO@@@" db "IVYSAUR@@@" db "EXEGGUTOR@" db "LICKITUNG@" db "EXEGGCUTE@" db "GRIMER@@@@" db "GENGAR@@@@" db "NIDORAN♀@@" db "NIDOQUEEN@" db "CUBONE@@@@" db "RHYHORN@@@" db "LAPRAS@@@@" db "ARCANINE@@" db "MEW@@@@@@@" db "GYARADOS@@" db "SHELLDER@@" db "TENTACOOL@" db "GASTLY@@@@" db "SCYTHER@@@" db "STARYU@@@@" db "BLASTOISE@" db "PINSIR@@@@" db "TANGELA@@@" db "MISSINGNO." db "MISSINGNO." db "GROWLITHE@" db "ONIX@@@@@@" db "FEAROW@@@@" db "PIDGEY@@@@" db "SLOWPOKE@@" db "KADABRA@@@" db "GRAVELER@@" db "CHANSEY@@@" db "MACHOKE@@@" db "MR.MIME@@@" db "HITMONLEE@" db "HITMONCHAN" db "ARBOK@@@@@" db "PARASECT@@" db "PSYDUCK@@@" db "DROWZEE@@@" db "GOLEM@@@@@" db "MISSINGNO." db "MAGMAR@@@@" db "MISSINGNO." db "ELECTABUZZ" db "MAGNETON@@" db "KOFFING@@@" db "MISSINGNO." db "MANKEY@@@@" db "SEEL@@@@@@" db "DIGLETT@@@" db "TAUROS@@@@" db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "FARFETCH'D" db "VENONAT@@@" db "DRAGONITE@" db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "DODUO@@@@@" db "POLIWAG@@@" db "JYNX@@@@@@" db "MOLTRES@@@" db "ARTICUNO@@" db "ZAPDOS@@@@" db "DITTO@@@@@" db "MEOWTH@@@@" db "KRABBY@@@@" db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "VULPIX@@@@" db "NINETALES@" db "PIKACHU@@@" db "RAICHU@@@@" db "MISSINGNO." db "MISSINGNO." db "DRATINI@@@" db "DRAGONAIR@" db "KABUTO@@@@" db "KABUTOPS@@" db "HORSEA@@@@" db "SEADRA@@@@" db "MISSINGNO." db "MISSINGNO." db "SANDSHREW@" db "SANDSLASH@" db "OMANYTE@@@" db "OMASTAR@@@" db "JIGGLYPUFF" db "WIGGLYTUFF" db "EEVEE@@@@@" db "FLAREON@@@" db "JOLTEON@@@" db "VAPOREON@@" db "MACHOP@@@@" db "ZUBAT@@@@@" db "EKANS@@@@@" db "PARAS@@@@@" db "POLIWHIRL@" db "POLIWRATH@" db "WEEDLE@@@@" db "KAKUNA@@@@" db "BEEDRILL@@" db "MISSINGNO." db "DODRIO@@@@" db "PRIMEAPE@@" db "DUGTRIO@@@" db "VENOMOTH@@" db "DEWGONG@@@" db "MISSINGNO." db "MISSINGNO." db "CATERPIE@@" db "METAPOD@@@" db "BUTTERFREE" db "MACHAMP@@@" db "MISSINGNO." db "GOLDUCK@@@" db "HYPNO@@@@@" db "GOLBAT@@@@" db "MEWTWO@@@@" db "SNORLAX@@@" db "MAGIKARP@@" db "MISSINGNO." db "MISSINGNO." db "MUK@@@@@@@" db "MISSINGNO." db "KINGLER@@@" db "CLOYSTER@@" db "MISSINGNO." db "ELECTRODE@" db "CLEFABLE@@" db "WEEZING@@@" db "PERSIAN@@@" db "MAROWAK@@@" db "MISSINGNO." db "HAUNTER@@@" db "ABRA@@@@@@" db "ALAKAZAM@@" db "PIDGEOTTO@" db "PIDGEOT@@@" db "STARMIE@@@" db "BULBASAUR@" db "VENUSAUR@@" db "TENTACRUEL" db "MISSINGNO." db "GOLDEEN@@@" db "SEAKING@@@" db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "PONYTA@@@@" db "RAPIDASH@@" db "RATTATA@@@" db "RATICATE@@" db "NIDORINO@@" db "NIDORINA@@" db "GEODUDE@@@" db "PORYGON@@@" db "AERODACTYL" db "MISSINGNO." db "MAGNEMITE@" db "MISSINGNO." db "MISSINGNO." db "CHARMANDER" db "SQUIRTLE@@" db "CHARMELEON" db "WARTORTLE@" db "CHARIZARD@" db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "MISSINGNO." db "ODDISH@@@@" db "GLOOM@@@@@" db "VILEPLUME@" db "BELLSPROUT" db "WEEPINBELL" db "VICTREEBEL"
;--- this is a test app which calls functions Export1 and Export2 in ;--- Win32_4d.dll. The link step needs import library Win32_4d.lib to find ;--- the externals used in the source. Some linkers (MS link, PoLink) ;--- will always generate such an import lib when the dll is written. ;--- To get one with JWlink, OPTION IMPLIB must be set; it will make JWlink ;--- launch JWlib internally. ;--- To assembly, use JWasm: ;--- JWasm -coff Win32_4a.asm ; ;--- 1. To link with MS link: ;--- Link /subsystem:console Win32_4a.obj Win32_4d.lib ;--- 2. To link with JWlink ;--- JWlink format win pe file Win32_4a.obj lib Win32_4d.lib ;--- 3. To link with PoLink: ;--- PoLink /subsystem:console Win32_4a.obj Win32_4d.lib .386 .model flat, stdcall includelib kernel32.lib includelib user32.lib ;--- prototypes for functions exported by Window4d. Export1 proto stdcall Export2 proto stdcall :ptr DWORD ;--- standard Win32 prototypes STD_OUTPUT_HANDLE equ -11 WriteConsoleA proto :dword, :dword, :dword, :dword, :dword GetStdHandle proto :dword ExitProcess proto :dword wvsprintfA proto :ptr, :ptr, :ptr .data value2 dd 0 szFormat1 db "Export1() returned %X",13,10,0 szFormat2 db "Export2() returned %X",13,10,0 .code ;--- simple printf() emulation printf proc c uses ebx pszFormat:dword, args:VARARG local dwWritten:DWORD local buffer[256]:byte invoke GetStdHandle, STD_OUTPUT_HANDLE mov ebx, eax invoke wvsprintfA, addr buffer, pszFormat, addr args lea ecx, dwWritten invoke WriteConsoleA, ebx, addr buffer, eax, ecx, 0 ret printf endp start: invoke Export1 invoke printf, addr szFormat1, eax invoke Export2, addr value2 invoke printf, addr szFormat2, value2 invoke ExitProcess, 0 end start
CheckPlayerMoveTypeMatchups: ; Check how well the moves you've already used ; fare against the enemy's Pokemon. Used to ; score a potential switch. push hl push de push bc ld a, 10 ld [wEnemyAISwitchScore], a ld hl, wPlayerUsedMoves ld a, [hl] and a jr z, .unknown_moves ld d, NUM_MOVES ld e, 0 .loop ld a, [hli] and a jr z, .exit push hl dec a ld hl, Moves + MOVE_POWER call GetMoveAttr and a jr z, .next inc hl call GetMoveByte ld hl, wEnemyMonType call CheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 ; 1.0 + 0.1 jr nc, .super_effective and a jr z, .next cp EFFECTIVE ; 1.0 jr nc, .neutral .not_very_effective ld a, e cp 1 ; 0.1 jr nc, .next ld e, 1 jr .next .neutral ld e, 2 jr .next .super_effective call .DecreaseScore pop hl jr .done .next pop hl dec d jr nz, .loop .exit ld a, e cp 2 jr z, .done call .IncreaseScore ld a, e and a jr nz, .done call .IncreaseScore jr .done .unknown_moves ld a, [wBattleMonType1] ld b, a ld hl, wEnemyMonType1 call CheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 ; 1.0 + 0.1 jr c, .ok call .DecreaseScore .ok ld a, [wBattleMonType2] cp b jr z, .ok2 call CheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 ; 1.0 + 0.1 jr c, .ok2 call .DecreaseScore .ok2 .done call .CheckEnemyMoveMatchups pop bc pop de pop hl ret .CheckEnemyMoveMatchups: ld de, wEnemyMonMoves ld b, NUM_MOVES + 1 ld c, 0 ld a, [wTypeMatchup] push af .loop2 dec b jr z, .exit2 ld a, [de] and a jr z, .exit2 inc de dec a ld hl, Moves + MOVE_POWER call GetMoveAttr and a jr z, .loop2 inc hl call GetMoveByte ld hl, wBattleMonType1 call CheckTypeMatchup ld a, [wTypeMatchup] ; immune and a jr z, .loop2 ; not very effective inc c cp EFFECTIVE jr c, .loop2 ; neutral inc c inc c inc c inc c inc c cp EFFECTIVE jr z, .loop2 ; super effective ld c, 100 jr .loop2 .exit2 pop af ld [wTypeMatchup], a ld a, c and a jr z, .doubledown ; double down cp 5 jr c, .DecreaseScore ; down cp 100 ret c jr .IncreaseScore ; up .doubledown call .DecreaseScore .DecreaseScore: ld a, [wEnemyAISwitchScore] dec a ld [wEnemyAISwitchScore], a ret .IncreaseScore: ld a, [wEnemyAISwitchScore] inc a ld [wEnemyAISwitchScore], a ret CheckAbleToSwitch: xor a ld [wEnemySwitchMonParam], a call FindAliveEnemyMons ret c ld a, [wEnemySubStatus1] bit SUBSTATUS_PERISH, a jr z, .no_perish ld a, [wEnemyPerishCount] cp 1 jr nz, .no_perish ; Perish count is 1 call FindAliveEnemyMons call FindEnemyMonsWithAtLeastQuarterMaxHP call FindEnemyMonsThatResistPlayer call FindAliveEnemyMonsWithASuperEffectiveMove ld a, e cp 2 jr nz, .not_2 ld a, [wEnemyAISwitchScore] add $30 ; maximum chance ld [wEnemySwitchMonParam], a ret .not_2 call FindAliveEnemyMons sla c sla c ld b, $ff .loop1 inc b sla c jr nc, .loop1 ld a, b add $30 ; maximum chance ld [wEnemySwitchMonParam], a ret .no_perish call CheckPlayerMoveTypeMatchups ld a, [wEnemyAISwitchScore] cp 11 ret nc ld a, [wLastPlayerCounterMove] and a jr z, .no_last_counter_move call FindEnemyMonsImmuneToLastCounterMove ld a, [wEnemyAISwitchScore] and a jr z, .no_last_counter_move ld c, a call FindEnemyMonsWithASuperEffectiveMove ld a, [wEnemyAISwitchScore] cp $ff ret z ld b, a ld a, e cp 2 jr z, .not_2_again call CheckPlayerMoveTypeMatchups ld a, [wEnemyAISwitchScore] cp 10 ret nc ld a, b add $10 ld [wEnemySwitchMonParam], a ret .not_2_again ld c, $10 call CheckPlayerMoveTypeMatchups ld a, [wEnemyAISwitchScore] cp 10 jr nc, .okay ld c, $20 .okay ld a, b add c ld [wEnemySwitchMonParam], a ret .no_last_counter_move call CheckPlayerMoveTypeMatchups ld a, [wEnemyAISwitchScore] cp 10 ret nc call FindAliveEnemyMons call FindEnemyMonsWithAtLeastQuarterMaxHP call FindEnemyMonsThatResistPlayer call FindAliveEnemyMonsWithASuperEffectiveMove ld a, e cp $2 ret nz ld a, [wEnemyAISwitchScore] add $10 ld [wEnemySwitchMonParam], a ret FindAliveEnemyMons: ld a, [wOTPartyCount] cp 2 jr c, .only_one ld d, a ld e, 0 ld b, 1 << (PARTY_LENGTH - 1) ld c, 0 ld hl, wOTPartyMon1HP .loop ld a, [wCurOTMon] cp e jr z, .next push bc ld b, [hl] inc hl ld a, [hld] or b pop bc jr z, .next ld a, c or b ld c, a .next srl b push bc ld bc, PARTYMON_STRUCT_LENGTH add hl, bc pop bc inc e dec d jr nz, .loop ld a, c and a jr nz, .more_than_one .only_one scf ret .more_than_one and a ret FindEnemyMonsImmuneToLastCounterMove: ld hl, wOTPartyMon1 ld a, [wOTPartyCount] ld b, a ld c, 1 << (PARTY_LENGTH - 1) ld d, 0 xor a ld [wEnemyAISwitchScore], a .loop ld a, [wCurOTMon] cp d push hl jr z, .next push hl push bc ; If the Pokemon has at least 1 HP... ld bc, MON_HP add hl, bc pop bc ld a, [hli] or [hl] pop hl jr z, .next ld a, [hl] ld [wCurSpecies], a call GetBaseData ; the player's last move is damaging... ld a, [wLastPlayerCounterMove] dec a ld hl, Moves + MOVE_POWER call GetMoveAttr and a jr z, .next ; and the Pokemon is immune to it... inc hl call GetMoveByte ld hl, wBaseType call CheckTypeMatchup ld a, [wTypeMatchup] and a jr nz, .next ; ... encourage that Pokemon. ld a, [wEnemyAISwitchScore] or c ld [wEnemyAISwitchScore], a .next pop hl dec b ret z push bc ld bc, PARTYMON_STRUCT_LENGTH add hl, bc pop bc inc d srl c jr .loop FindAliveEnemyMonsWithASuperEffectiveMove: push bc ld a, [wOTPartyCount] ld e, a ld hl, wOTPartyMon1HP ld b, 1 << (PARTY_LENGTH - 1) ld c, 0 .loop ld a, [hli] or [hl] jr z, .next ld a, b or c ld c, a .next srl b push bc ld bc, wPartyMon2HP - (wPartyMon1HP + 1) add hl, bc pop bc dec e jr nz, .loop ld a, c pop bc and c ld c, a ; fallthrough FindEnemyMonsWithASuperEffectiveMove: ld a, -1 ld [wEnemyAISwitchScore], a ld hl, wOTPartyMon1Moves ld b, 1 << (PARTY_LENGTH - 1) ld d, 0 ld e, 0 .loop ld a, b and c jr z, .next push hl push bc ; for move on mon: ld b, NUM_MOVES ld c, 0 .loop3 ; if move is None: break ld a, [hli] and a push hl jr z, .break3 ; if move has no power: continue dec a ld hl, Moves + MOVE_POWER call GetMoveAttr and a jr z, .nope ; check type matchups inc hl call GetMoveByte ld hl, wBattleMonType1 call CheckTypeMatchup ; if immune or not very effective: continue ld a, [wTypeMatchup] cp 10 jr c, .nope ; if neutral: load 1 and continue ld e, 1 cp EFFECTIVE + 1 jr c, .nope ; if super-effective: load 2 and break ld e, 2 jr .break3 .nope pop hl dec b jr nz, .loop3 jr .done .break3 pop hl .done ld a, e pop bc pop hl cp 2 jr z, .done2 ; at least one move is super-effective cp 1 jr nz, .next ; no move does more than half damage ; encourage this pokemon ld a, d or b ld d, a jr .next ; such a long jump .next ; next pokemon? push bc ld bc, PARTYMON_STRUCT_LENGTH add hl, bc pop bc srl b jr nc, .loop ; if no pokemon has a super-effective move: return ld a, d ld b, a and a ret z .done2 ; convert the bit flag to an int and return push bc sla b sla b ld c, $ff .loop2 inc c sla b jr nc, .loop2 ld a, c ld [wEnemyAISwitchScore], a pop bc ret FindEnemyMonsThatResistPlayer: push bc ld hl, wOTPartySpecies ld b, 1 << (PARTY_LENGTH - 1) ld c, 0 .loop ld a, [hli] cp $ff jr z, .done push hl ld [wCurSpecies], a call GetBaseData ld a, [wLastPlayerCounterMove] and a jr z, .skip_move dec a ld hl, Moves + MOVE_POWER call GetMoveAttr and a jr z, .skip_move inc hl call GetMoveByte jr .check_type .skip_move ld a, [wBattleMonType1] ld hl, wBaseType call CheckTypeMatchup ld a, [wTypeMatchup] cp 10 + 1 jr nc, .dont_choose_mon ld a, [wBattleMonType2] .check_type ld hl, wBaseType call CheckTypeMatchup ld a, [wTypeMatchup] cp EFFECTIVE + 1 jr nc, .dont_choose_mon ld a, b or c ld c, a .dont_choose_mon srl b pop hl jr .loop .done ld a, c pop bc and c ld c, a ret FindEnemyMonsWithAtLeastQuarterMaxHP: push bc ld de, wOTPartySpecies ld b, 1 << (PARTY_LENGTH - 1) ld c, 0 ld hl, wOTPartyMon1HP .loop ld a, [de] inc de cp $ff jr z, .done push hl push bc ld b, [hl] inc hl ld c, [hl] inc hl inc hl ; hl = MaxHP + 1 ; bc = [CurHP] * 4 srl c rl b srl c rl b ; if bc >= [hl], encourage ld a, [hld] cp c ld a, [hl] sbc b pop bc jr nc, .next ld a, b or c ld c, a .next srl b pop hl push bc ld bc, PARTYMON_STRUCT_LENGTH add hl, bc pop bc jr .loop .done ld a, c pop bc and c ld c, a ret
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <chrono> // class weekday_last; #include <chrono> #include <type_traits> #include <cassert> #include "test_macros.h" int main(int, char**) { using weekday_last = std::chrono::weekday_last; static_assert(std::is_trivially_copyable_v<weekday_last>, ""); static_assert(std::is_standard_layout_v<weekday_last>, ""); return 0; }
db 0 ; species ID placeholder db 83, 80, 75, 91, 70, 70 ; hp atk def spd sat sdf db NORMAL, FLYING ; type db 45 ; catch rate db 172 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 15 ; step cycles to hatch INCBIN "gfx/pokemon/pidgeot/front.dimensions" db GROWTH_MEDIUM_SLOW ; growth rate dn EGG_FLYING, EGG_FLYING ; egg groups db 70 ; happiness ; tm/hm learnset tmhm TOXIC, HIDDEN_POWER, SUNNY_DAY, HYPER_BEAM, PROTECT, RAIN_DANCE, FRUSTRATION, RETURN, DOUBLE_TEAM, AERIAL_ACE, FACADE, SECRET_POWER, REST, ATTRACT, THIEF, STEEL_WING, ROOST, ENDURE, GIGA_IMPACT, CAPTIVATE, SLEEP_TALK, NATURAL_GIFT, SWAGGER, PLUCK, U_TURN, SUBSTITUTE, FLY, DEFOG, AIR_CUTTER, HEAT_WAVE, MUD_SLAP, OMINOUS_WIND, SNORE, SWIFT, TWISTER, UPROAR ; end
; screen update routines !ifndef ACORN { ; SF init_screen_colours_invisible lda zcolours + BGCOL bpl + ; Always branch init_screen_colours jsr s_init lda zcolours + FGCOL !if BORDERCOL_FINAL = 1 { sta reg_bordercolour } + jsr s_set_text_colour lda zcolours + BGCOL sta reg_backgroundcolour !if BORDERCOL_FINAL = 0 { sta reg_bordercolour } else { !if BORDERCOL_FINAL != 1 { lda zcolours + BORDERCOL_FINAL sta reg_bordercolour } } lda zcolours + CURSORCOL sta current_cursor_colour !ifdef Z5PLUS { ; store default colours in header lda #BGCOL ; blue sta story_start + header_default_bg_colour lda #FGCOL ; white sta story_start + header_default_fg_colour } lda #147 ; clear screen jmp s_printchar } !ifdef Z4PLUS { z_ins_erase_window ; erase_window window ldx z_operand_value_low_arr ; jmp erase_window ; Not needed, since erase_window follows } erase_window ; x = 0: clear lower window ; 1: clear upper window ; -1: clear screen and unsplit ; -2: clear screen and keep split lda zp_screenrow pha ; lda z_operand_value_low_arr cpx #0 beq .window_0 cpx #1 beq .window_1 lda #0 sta current_window cpx #$ff ; clear screen, then; -1 unsplit, -2 keep as is bne .keep_split jsr clear_num_rows ldx #0 ; unsplit jsr split_window .keep_split !ifdef Z3 { lda #1 bne .clear_from_a ; Always branch } else { lda #0 beq .clear_from_a ; Always branch } ; SF: ENHANCEMENT: This could be rewritten to clear the whole area in one go ; using a text window, but since it would introduce a divergence from ; upstream with potential for bugs I'd want a decent performance improvement ; in a real game to make it worthwhile. .window_0 lda window_start_row + 1 .clear_from_a sta zp_screenrow - jsr s_erase_line inc zp_screenrow lda zp_screenrow +cmp_screen_height bne - jsr clear_num_rows ; set cursor to top left (or, if Z4, bottom left) pla ldx #0 stx cursor_column + 1 !ifdef Z3 { inx } !ifdef Z5PLUS { lda window_start_row + 1 } else { +lda_screen_height_minus_1 } stx cursor_row + 1 pha jmp .end_erase ; SF: ENHANCEMENT: As above. .window_1 lda window_start_row + 1 cmp window_start_row + 2 beq .end_erase lda window_start_row + 2 sta zp_screenrow - jsr s_erase_line inc zp_screenrow lda zp_screenrow cmp window_start_row + 1 bne - .end_erase !ifdef ACORN { lda #1 sta s_cursors_inconsistent } pla sta zp_screenrow .return rts !ifdef Z4PLUS { z_ins_erase_line ; erase_line value ; clear current line (where the cursor is) lda z_operand_value_low_arr cmp #1 bne .return jmp s_erase_line_from_cursor !ifdef Z5PLUS { .pt_cursor = z_temp; !byte 0,0 .pt_width = z_temp + 2 ; !byte 0 .pt_height = z_temp + 3; !byte 0 .pt_skip = z_temp + 4; !byte 0,0 .current_col = z_temp + 6; !byte 0 z_ins_print_table ; print_table zscii-text width [height = 1] [skip] ; ; defaults lda #1 sta .pt_height lda #0 sta .pt_skip sta .pt_skip + 1 ; Read args lda z_operand_value_low_arr + 1 beq .print_table_done sta .pt_width ldy z_operand_count cpy #3 bcc ++ lda z_operand_value_low_arr + 2 beq .print_table_done sta .pt_height + cpy #4 bcc ++ lda z_operand_value_low_arr + 3 sta .pt_skip lda z_operand_value_high_arr + 3 sta .pt_skip + 1 ++ lda .pt_height cmp #1 beq .print_table_oneline ; start printing multi-line table jsr printchar_flush jsr get_cursor ; x=row, y=column stx .pt_cursor sty .pt_cursor + 1 lda z_operand_value_high_arr ; Start address ldx z_operand_value_low_arr -- jsr set_z_address ldx .pt_cursor + 1 stx .current_col ldy .pt_width - jsr read_next_byte ldx .current_col +cpx_screen_width bcs + jsr streams_print_output + inc .current_col dey bne - dec .pt_height beq .print_table_done ; Move cursor to start of next line to print inc .pt_cursor ldx .pt_cursor ldy .pt_cursor + 1 jsr set_cursor ; Skip the number of bytes requested jsr get_z_address pha txa clc adc .pt_skip tax pla adc .pt_skip + 1 bcc -- ; Always jump .print_table_done rts .print_table_oneline lda z_operand_value_high_arr ; Start address ldx z_operand_value_low_arr jsr set_z_address ldy .pt_width - jsr read_next_byte jsr translate_zscii_to_petscii bcs + ; Illegal char jsr printchar_buffered + dey bne - rts } z_ins_buffer_mode ; buffer_mode flag ; If buffer mode goes from 0 to 1, remember the start column ; If buffer mode goes from 1 to 0, flush the buffer lda z_operand_value_low_arr beq + lda #1 + cmp is_buffered_window beq .buffer_mode_done ; Buffer mode changes sta is_buffered_window ; set lower window to buffered or unbuffered mode cmp #0 bne start_buffering jsr printchar_flush .buffer_mode_done rts } start_buffering jsr get_cursor sty first_buffered_column sty buffer_index ldy #0 sty last_break_char_buffer_pos rts +make_acorn_screen_hole z_ins_split_window ; split_window lines ldx z_operand_value_low_arr ; jmp split_window ; Not needed since split_window follows split_window ; split if <x> > 0, unsplit if <x> = 0 cpx #0 bne .split_window ; unsplit ldx window_start_row + 2 stx window_start_row + 1 !ifdef MODE_7_STATUS { !ifdef Z4PLUS { jsr check_and_add_mode_7_colour_code } } rts .split_window +cpx_max_lines bcc + +ldx_max_lines + txa clc adc window_start_row + 2 sta window_start_row + 1 !ifdef Z3 { ldx #1 jsr erase_window } !ifdef MODE_7_STATUS { !ifdef Z4PLUS { jsr check_and_add_mode_7_colour_code } } lda current_window beq .ensure_cursor_in_window ; Window 1 was already selected => Reset cursor if outside window jsr get_cursor cpx window_start_row + 1 bcs .reset_cursor .do_nothing rts .ensure_cursor_in_window jsr get_cursor cpx window_start_row + 1 bcs .do_nothing ldx window_start_row + 1 jmp set_cursor z_ins_set_window ; set_window window lda z_operand_value_low_arr bne select_upper_window ; Selecting lower window select_lower_window ldx current_window beq .do_nothing jsr save_cursor lda #0 sta current_window ; this is the main text screen, restore cursor position jmp restore_cursor select_upper_window ; this is the status line window ; store cursor position so it can be restored later ; when set_window 0 is called ldx current_window bne .reset_cursor ; Upper window was already selected jsr save_cursor ldx #1 stx current_window .reset_cursor !ifdef Z3 { ; Since Z3 has a separate statusline ldx #1 } else { ldx #0 } ldy #0 jmp set_cursor !ifdef Z4PLUS { z_ins_set_text_style lda z_operand_value_low_arr bne .t0 ; roman !ifndef ACORN { lda #146 ; reverse off jmp s_printchar } else { ; A is zero sta s_reverse rts } .t0 cmp #1 bne .do_nothing !ifndef ACORN { lda #18 ; reverse on jmp s_printchar } else { lda #$80 sta s_reverse rts } +make_acorn_screen_hole z_ins_get_cursor ; get_cursor array ldx z_operand_value_low_arr stx string_array lda z_operand_value_high_arr clc adc #>story_start sta string_array + 1 lda #0 ldy #0 sta (string_array),y ldy #2 sta (string_array),y ldx current_window beq + ; We are in lower window, jump to read last cursor pos in upper window jsr get_cursor ; x=row, y=column - inx ; In Z-machine, cursor has position 1+ iny ; In Z-machine, cursor has position 1+ tya pha ldy #1 txa ; row sta (string_array),y pla ; column ldy #3 sta (string_array),y .do_nothing_2 rts + ldx cursor_row + 1 ldy cursor_column + 1 jmp - z_ins_set_cursor ; set_cursor line column ldy current_window beq .do_nothing_2 ldx z_operand_value_low_arr ; line 1.. dex ; line 0.. ldy z_operand_value_low_arr + 1 ; column dey jmp set_cursor } clear_num_rows lda #0 sta num_rows rts +make_acorn_screen_hole increase_num_rows lda current_window bne .increase_num_rows_done ; Upper window is never buffered inc num_rows lda is_buffered_window beq .increase_num_rows_done lda window_start_row sec sbc window_start_row + 1 sbc #1 cmp num_rows bcs .increase_num_rows_done show_more_prompt ; time to show [More] jsr clear_num_rows !ifndef ACORN { lda $07e7 sta .more_text_char lda #128 + $2a ; screen code for reversed "*" sta $07e7 ; wait for ENTER .printchar_pressanykey !ifndef BENCHMARK { -- ldx s_colour iny tya and #1 beq + ldx $d021 + stx $d800 + 999 ldx #40 --- lda $a2 - cmp $a2 beq - jsr getchar_and_maybe_toggle_darkmode cmp #0 bne + dex bne --- beq -- ; Always branch + } lda .more_text_char sta $07e7 } else { !ifndef BENCHMARK { ; We mimic the OS paged mode behaviour here: we flicker the keyboard LEDs ; and wait until SHIFT is pressed. It would be difficult (impossible using ; portable OS routines?) to display a "more" prompt in the bottom right ; character without causing a scroll. We could maybe define a text window ; covering that single character and repeatedly print (say) "X" and " " over ; and over again but that might look a bit ugly, although I haven't tried ; it. ; SF: ENHANCEMENT: Just possibly we could enable OS paged mode, define a ; single cell text window at the bottom right, print a single-character ; "more" prompt and let the OS block until SHIFT is pressed. I haven't tried ; this and it strikes me as a corner-ish case that may behave differently on ; different OS versions so would need to test carefully. To be honest it ; feels more Acorn-y to not display a "more" prompt character anyway, but ; maybe users will disagree and by noting possibilities to implement this I ; can try to convince myself I'm not adopting a sour grapes attitude. :-) ; SF: ENHANCEMENT: I'm not sure it's a good idea, but I *could* turn the ; cursor on and fiddle with the CRTC registers to give it a flashing block ; appearance at the bottom right position as a kind of "more" prompt. ; SFTODO: Should we also allow RETURN to scroll? And/or SPACE? And/or any ; key? ; SFTODO: Would it save code if we actually used OS page mode (without trying ; the tricks described above to generate a single character "more" prompt) ; instead of emulating it ourselves? *Probably* not given how short this code ; is, but maybe worth thinking about it. - lda #osbyte_reflect_keyboard_status jsr osbyte lda #osbyte_read_key ldx #$ff ldy #$ff jsr osbyte tya beq - } } .increase_num_rows_done rts !ifndef ACORN { .more_text_char !byte 0 } printchar_flush ; flush the printchar buffer ldx current_window stx z_temp + 11 jsr select_lower_window lda s_reverse pha ldx first_buffered_column - cpx buffer_index bcs + lda print_buffer2,x sta s_reverse lda print_buffer,x jsr s_printchar inx bne - + pla sta s_reverse jsr start_buffering ldx z_temp + 11 beq .increase_num_rows_done jsr save_cursor lda #1 sta current_window ; We have re-selected the upper window, restore cursor position jmp restore_cursor +make_acorn_screen_hole printchar_buffered ; a is PETSCII character to print sta .buffer_char ; need to save x,y txa pha tya pha ; is this a buffered window? lda current_window bne .is_not_buffered lda is_buffered_window bne .buffered_window .is_not_buffered lda .buffer_char jsr s_printchar jmp .printchar_done ; update the buffer .buffered_window lda .buffer_char ; add this char to the buffer cmp #$0d bne .check_break_char jsr printchar_flush ; more on the same line jsr increase_num_rows lda #$0d jsr s_printchar jsr start_buffering jmp .printchar_done .check_break_char ldy buffer_index +cpy_screen_width bcs .add_char ; Don't register break chars on last position of buffer. cmp #$20 ; Space beq .break_char cmp #$2d ; - bne .add_char .break_char ; update index to last break character sty last_break_char_buffer_pos .add_char ldy buffer_index sta print_buffer,y lda s_reverse sta print_buffer2,y iny sty buffer_index +cpy_screen_width_plus_1 beq + jmp .printchar_done + ; print the line until last space ; First calculate max# of characters on line !ifndef ACORN { ldx #40 } else { +ldx_screen_width } lda window_start_row sec sbc window_start_row + 1 sbc #2 cmp num_rows bcs + ; SF: Note that we only allow 39 characters on the last line of the screen; ; this may be useful information if I ever want to implement a "more" prompt ; character. However, I note the C64 "more" code saves and restores the ; contents of the bottom right character and I suspect a game could output ; text in other ways which would use the rightmost column on the bottom ; line. dex ; Max 39 chars on last line on screen. + stx max_chars_on_line ; Check if we have a "perfect space" - a space after 40 characters lda print_buffer,x cmp #$20 beq .print_40_2 ; Print all in buffer, regardless of which column buffering started in ; Now find the character to break on ldy last_break_char_buffer_pos beq .print_40 ; If there are no break characters on the line, print all 40 characters ; Check if the break character is a space lda print_buffer,y cmp #$20 beq .print_buffer iny bne .store_break_pos ; Always branch .print_40 ; If we can't find a place to break, and buffered output started in column > 0, print a line break and move the text in the buffer to the next line. ldx first_buffered_column bne .move_remaining_chars_to_buffer_start .print_40_2 ldy max_chars_on_line .store_break_pos sty last_break_char_buffer_pos .print_buffer ldx first_buffered_column lda s_reverse pha - cpx last_break_char_buffer_pos beq + txa ; kernal_printchar destroys x,y pha lda print_buffer2,x sta s_reverse lda print_buffer,x jsr s_printchar pla tax inx bne - ; Always branch + pla sta s_reverse .move_remaining_chars_to_buffer_start ; Skip initial spaces, move the rest of the line back to the beginning and update indices ldy #0 cpx buffer_index beq .after_copy_loop lda print_buffer,x cmp #$20 bne .copy_loop inx .copy_loop cpx buffer_index beq .after_copy_loop lda print_buffer,x sta print_buffer,y lda print_buffer2,x sta print_buffer2,y iny inx bne .copy_loop ; Always branch .after_copy_loop +make_acorn_screen_hole_jmp sty buffer_index lda #0 sta first_buffered_column ; more on the same line jsr increase_num_rows lda last_break_char_buffer_pos +cmp_screen_width bcs + lda #$0d jsr s_printchar + ldy #0 sty last_break_char_buffer_pos .printchar_done pla tay pla tax rts .buffer_char !byte 0 ; print_buffer !fill 41, 0 .save_x !byte 0 .save_y !byte 0 first_buffered_column !byte 0 !ifndef ACORN { clear_screen_raw lda #147 jsr s_printchar rts } printchar_raw php stx .save_x sty .save_y jsr s_printchar ldy .save_y ldx .save_x plp rts printstring_raw ; Parameters: Address in a,x to 0-terminated string stx .read_byte + 1 sta .read_byte + 2 ldx #0 .read_byte lda $8000,x beq + jsr printchar_raw inx bne .read_byte + rts set_cursor ; input: y=column (0-39) ; x=row (0-24) clc jmp s_plot get_cursor ; output: y=column (0-39) ; x=row (0-24) sec jmp s_plot save_cursor jsr get_cursor tya ldy current_window stx cursor_row,y sta cursor_column,y rts restore_cursor ldy current_window ldx cursor_row,y lda cursor_column,y tay jmp set_cursor !ifdef Z3 { +make_acorn_screen_hole z_ins_show_status ; show_status (hardcoded size) ; jmp draw_status_line draw_status_line lda current_window pha jsr save_cursor lda #2 sta current_window ldx #0 ldy #0 jsr set_cursor !ifndef ACORN { lda #18 ; reverse on jsr s_printchar ldx darkmode ldy statuslinecol,x lda zcolours,y jsr s_set_text_colour } else { lda #$80 sta s_reverse !ifdef MODE_7_STATUS { lda screen_mode cmp #7 bne + ; SF: This used to output the colour code via s_printchar, but a recent ; change (to stop Beyond Zork - probably any other game using function keys ; as terminating characters as well - printing the function key codes) ; stopped that working. I can't help thinking the right fix would be to not ; send these valid-for-input-only codes to s_printchar at the end of ; .char_is_ok when they occur as terminating characters and then allow ; s_printchar to print these colour codes, but I may be missing something ; and I don't want to risk causing subtle breakage. As a not-too-bad ; workaround, output using oswrch instead. lda #vdu_home sta s_cursors_inconsistent jsr oswrch clc lda fg_colour adc #mode_7_text_colour_base jsr oswrch inc zp_screencolumn + } } ; ; Room name ; ; name of the object whose number is in the first global variable lda #16 jsr z_get_low_global_variable_value jsr print_obj ; ; fill the rest of the line with spaces ; - lda zp_screencolumn +cmp_screen_width bcs + lda #$20 jsr s_printchar jmp - ; ; score or time game? ; + lda story_start + header_flags_1 and #$02 bne .timegame ; score game lda z_operand_value_low_arr pha lda z_operand_value_high_arr pha lda z_operand_value_low_arr + 1 pha lda z_operand_value_high_arr + 1 pha ldx #0 !ifndef ACORN { ldy #25 } else { sec +lda_screen_width sbc #(40-25) tay } jsr set_cursor ldy #0 - lda .score_str,y beq + jsr s_printchar iny bne - + lda #17 jsr z_get_low_global_variable_value stx z_operand_value_low_arr sta z_operand_value_high_arr jsr z_ins_print_num lda #47 jsr s_printchar lda #18 jsr z_get_low_global_variable_value stx z_operand_value_low_arr sta z_operand_value_high_arr jsr z_ins_print_num pla sta z_operand_value_high_arr + 1 pla sta z_operand_value_low_arr + 1 pla sta z_operand_value_high_arr pla sta z_operand_value_low_arr jmp .statusline_done .timegame ; time game ldx #0 !ifndef ACORN { ldy #25 } else { sec +lda_screen_width sbc #(40-25) tay } jsr set_cursor lda #>.time_str ldx #<.time_str jsr printstring_raw ; Print hours lda #65 + 32 sta .ampm_str + 1 lda #17 ; hour jsr z_get_low_global_variable_value ; Change AM to PM if hour >= 12 cpx #12 bcc + lda #80 + 32 sta .ampm_str + 1 + cpx #0 bne + ldx #12 ; Subtract 12 from hours if hours >= 13, so 15 becomes 3 etc + cpx #13 bcc + txa sbc #12 tax + ldy #$20 ; " " before if < 10 jsr .print_clock_number lda #58 ; : jsr s_printchar ; Print minutes lda #18 ; minute jsr z_get_low_global_variable_value ldy #$30 ; "0" before if < 10 jsr .print_clock_number ; Print AM/PM lda #>.ampm_str ldx #<.ampm_str jsr printstring_raw .statusline_done !ifndef ACORN { ldx darkmode ldy fgcol,x lda zcolours,y jsr s_set_text_colour lda #146 ; reverse off jsr s_printchar } else { lda #0 sta s_reverse } pla sta current_window jmp restore_cursor .print_clock_number sty z_temp + 11 txa ldy #0 - cmp #10 bcc .print_tens sbc #10 ; C is already set iny bne - ; Always branch .print_tens tax tya bne + lda z_temp + 11 bne ++ + ora #$30 ++ jsr s_printchar txa ora #$30 jmp s_printchar +make_acorn_screen_hole !ifndef ACORN { .score_str !pet "Score: ",0 .time_str !pet "Time: ",0 .ampm_str !pet " AM",0 } else { .score_str !text "Score: ",0 .time_str !text "Time: ",0 .ampm_str !text " AM",0 } } !ifdef ACORN { ; We keep the hardware cursor off most of the time; this way the user can't ; see it flitting round the screen doing various updates. (The C64 doesn't ; have this issue, as it uses direct screen writes and in fact its cursor ; is a software creation.) We allow it to remain in "illogical" positions ; while it's invisible and only position it where it belongs when it's turned ; on, as it is during user input. init_cursor_control lda #$ff sta cursor_status bne .cursor_control ; Always branch ; turn_off_cursor and turn_on_cursor adjust the value in cursor_status ; rather than setting a flag so they can be nested safely; the cursor should ; be turned on iff cursor_status is non-negative. Because we wait for VSYNC ; when telling the OS to turn the cursor on or off to try to avoid visual ; artefacts from doing so, we want to avoid this unless cursor_status has ; just transitioned from negative to non-negative or vice versa. turn_on_cursor inc cursor_status beq .really_turn_on_cursor .cursor_control_rts rts turn_off_cursor lda cursor_status dec cursor_status tax bne .cursor_control_rts ; We're turning the OS cursor off. lda #osbyte_read_vdu_status jsr osbyte txa and #vdu_status_cursor_editing beq .cursor_control ; We're in cursor editing mode, so we need to output a carriage return to ; turn it off. This will turn the cursor back on, so we must output it ; before we turn the cursor off. (We could turn the cursor off before ; outputting the carriage return as well, in order to try to minimise the ; chances of the user seeing it flick briefly into the leftmost column, but ; in practice this doesn't seem to help much.) lda #vdu_cr sta s_cursors_inconsistent jsr oswrch jmp .cursor_control .really_turn_on_cursor ; Just before we turn the OS cursor on, it's forced into the location ; corresponding to zp_screen{column,row}, which is where it "should" have ; been all along. jsr s_cursor_to_screenrowcolumn .cursor_control lda #vdu_miscellaneous jsr oswrch lda #1 jsr oswrch clc adc cursor_status ; we know A=1 and cursor_status=-1 for off or 0 for on jsr oswrch ldx #6 lda #0 - jsr oswrch dex bne - ; The VDU 23 command now lacks one byte to be complete, so let's wait for ; VSYNC now at the last possible minute before outputting that last byte ; and actioning the VDU 23 command. ; SFTODO: This VSYNC hits the benchmark quite hard but will be imperceptible ; normally, it might be worth conditionally omitting the next two lines in ; a benchmark build. lda #osbyte_wait_for_vsync jsr osbyte lda #0 jmp oswrch }
// Original test: ./atessmer/hw4/problem6/slt_1.asm // Author: atessmer // Test source code follows lbi r1, 255 lbi r2, 0 slt r3, r2, r1 halt
;; xOS32 ;; Copyright (C) 2016-2017 by Omar Mohammad. use32 KERNEL_HEAP = VBE_BACK_BUFFER + VBE_BUFFER_SIZE + 0x1000000 USER_HEAP = KERNEL_HEAP + 0x4000000 ; 64 MB KMALLOC_FLAGS = PAGE_PRESENT OR PAGE_WRITEABLE MALLOC_FLAGS = PAGE_PRESENT OR PAGE_WRITEABLE OR PAGE_USER ; kmalloc: ; Allocates memory in the kernel's heap ; In\ ECX = Bytes to allocate ; Out\ EAX = SSE-aligned pointer to allocated memory ; Note: ; kmalloc() NEVER returns NULL, because it never fails. ; When kmalloc() fails, it fires up a kernel panic. kmalloc: add ecx, 16 ; force sse-alignment add ecx, 4095 shr ecx, 12 ; to pages mov [.pages], ecx mov eax, KERNEL_HEAP mov ecx, [.pages] call vmm_alloc_pages cmp eax, USER_HEAP jge .no mov eax, KERNEL_HEAP mov ecx, [.pages] mov dl, KMALLOC_FLAGS call vmm_alloc cmp eax, 0 je .no mov [.return], eax mov edi, [.return] mov eax, [.pages] stosd mov eax, [.return] add eax, 16 ret .no: mov eax, 0 ret .pages dd 0 .return dd 0 ; kfree: ; Frees kernel memory ; In\ EAX = Pointer to memory ; Out\ Nothing kfree: mov ecx, [eax-16] ;sub ecx, 16 call vmm_free ret ; malloc: ; Allocates user heap memory ; In\ ECX = Bytes to allocate ; Out\ EAX = SSE-aligned pointer, 0 on error malloc: add ecx, 16 ; force sse-alignment add ecx, 4095 shr ecx, 12 ; to pages mov [.pages], ecx mov eax, USER_HEAP mov ecx, [.pages] mov dl, MALLOC_FLAGS call vmm_alloc cmp eax, 0 je .no mov [.return], eax mov edi, [.return] mov eax, [.pages] stosd mov eax, [.return] add eax, 16 ret .no: mov eax, 0 ret .pages dd 0 .return dd 0 ; free: ; Frees user memory ; In\ EAX = Pointer to memory ; Out\ Nothing free: mov ecx, [eax-16] ;sub ecx, 16 call vmm_free ret
.386p descr struc ; декскриптор сегмента limit dw 0 base_l dw 0 base_m db 0 attr_1 db 0 attr_2 db 0 base_h db 0 descr ends int_descr struc ; декскриптор прерывания offs_l dw 0 sel dw 0 rsrv db 0 iattr db 0 offs_h dw 0 int_descr ends protected_seg SEGMENT PARA PUBLIC 'CODE' USE32 ASSUME CS:protected_seg gdt label byte ; глобальная таблица дескрипторов gdt_null descr <0,0,0,0,0,0> ; нулевой дескриптор gdt_ds descr <0FFFFh,0,0,92h,11001111b,0> ; для защищенного режима, 92h = 10010010b gdt_cs16 descr <real_seg_size-1,0,0,98h,0,0> ; для кода реального режима, 98h = 10011010b gdt_cs32 descr <protected_seg_size-1,0,0,98h,01000000b,0> ; для защищенного режима gdt_ds32 descr <protected_seg_size-1,0,0,92h,01000000b,0> gdt_ss32 descr <stack_size-1,0,0, 92h, 01000000b,0> gdt_size = $-gdt gdtr df 0 idt label byte ; таблица дескрипторов прерываний int_descr 32 dup (<0, 24, 0, 8Eh, 0>) int08h int_descr <0, 24, 0, 8Eh, 0> int09h int_descr <0, 24, 0, 8Eh, 0> idt_size = $-idt idtr df 0 idtr_r dw 3FFh,0,0 ; регистр таблицы дескрипторов прерываний master db 0 ; маски прерываний ведущего и ведомого контроллеров slave db 0 s db ? exit_flag db 0 time_08h dd 0 mes_protected db 'PROTECTED MODE ' mes_real db 'REAL MODE$' string db '**** ****-**** ****-**** ****' ASCII_table db 0, 0, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 45, 61, 32, 0 ; ESC, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -, =, db 113, 119, 101, 114, 116, 121, 117, 105, 111, 112, 91, 93, 0, 0, 97, 115 ; q, w, e, r, t, y, u, i, o, p, [, ], a, s db 100, 102, 103, 104, 106, 107, 108, 59, 39, 96, 0, 92, 122, 120, 99 ; d, f, g, h, j, k, l, ;, ', \, z, x, c db 118, 98, 110, 109, 44, 46, 47, 0, 0, 0, 32 ; v, b, n, m, ,, ., /, space pos dd 2h protected_mode: mov ax, 32 mov ds, ax mov ax, 8 mov es, ax mov ax, 40 mov ss, ax mov ebx, stack_size mov esp, ebx sti mov ebp, 160 * 18 + 2 * 37 ; печатаем PROTECTED MODE mov ecx, 0 add ebp, 0B8000h print_protected: mov al, mes_protected[ecx] mov es:[ebp], al add ebp, 2 inc ecx cmp ecx, 23 jne print_protected push ds ; объем доступной физ. памяти mov ax, 8 mov ds, ax mov ebx, 100001h mov dl, 00010111b mov ecx, 0FFEFFFFEh try_write: mov dh, ds:[ebx] mov ds:[ebx], dl cmp ds:[ebx], dl jnz memory_end mov ds:[ebx], dh inc ebx loop try_write memory_end: pop ds xor edx, edx ; печать результата mov eax, ebx mov ebx, 160 * 18 + 2 * 68 add ebx, 0B8000h mov ECX, 10 print_digit: div ECX add DX, '0' mov s, DL mov DX, word ptr s mov ES:[EBX], Dl sub EBX, 2 mov EDX, 0 cmp EAX, 0 jnz print_digit wait_for_exit: test exit_flag, 1 ; ждем команду пользователя на выход jz wait_for_exit home: cli db 0EAh ; Дальний переход для того, чтобы заново загрузить селектор в регистр CS dd offset real_end dw 16 new_int08h: ; обработчик прерывания от системного таймера push eax push ebp mov ebp, 160 * 19 + 2 * 61 add ebp, 0B8000h test time_08h, 01h jnz skip_1 mov al, 2Ah jmp skip_2 skip_1: mov al, 20h skip_2: mov es:[ebp], al mov es:[ebp + 2], al mov es:[ebp + 4], al inc time_08h mov al, 20h ; EoI ведущему контроллеру прерываний out 20h, al pop ebp pop eax iretd new_int09h: ; обработчик прерывания клавиатуры push eax push ebx push ebp push edx in al, 60h xor ah, ah xor ebp, ebp mov bp, ax mov dh, 5h cmp al, 0Eh je delete_key cmp al, 1Ch jne print_key mov exit_flag, 1 jmp continue print_key: cmp al, 80h jnbe continue mov dl, ASCII_table[ebp] mov ebp, 0B8000h + 160 * 24 add ebp, pos mov es:[ebp], dl add pos, 2 jmp continue delete_key: mov dl, ASCII_table[ebp] mov ebp, 0B8000h + 160 * 24 sub pos, 2 add ebp, pos mov es:[ebp], dl continue: in al, 61h or al, 80h out 61h, al mov al, 20h ; EoI ведущему контроллеру прерываний out 20h, al pop edx pop ebp pop ebx pop eax iretd protected_seg_size = $-GDT protected_seg ENDS stack_seg SEGMENT PARA STACK 'STACK' stack_start db 100h dup(?) stack_size = $-stack_start stack_seg ENDS real_seg SEGMENT PARA PUBLIC 'CODE' USE16 ASSUME CS:real_seg, DS:protected_seg, SS:stack_seg begin: mov ax, protected_seg mov ds, ax mov ah, 09h mov edx, offset mes_real int 21h mov ax, protected_seg mov ds, ax xor eax, eax ; вычислим линейный адрес сегмента и загрузим его дескриптор в ГТД mov ax, real_seg shl eax, 4 mov word ptr gdt_cs16.base_l, ax shr eax, 16 mov byte ptr gdt_cs16.base_m, al mov ax, protected_seg shl eax, 4 push eax mov word ptr GDT_cs32.base_l, ax mov word ptr GDT_ss32.base_l, ax mov word ptr GDT_ds32.base_l, ax shr eax, 16 mov byte ptr GDT_cs32.base_m, al mov byte ptr GDT_ss32.base_m, al mov byte ptr GDT_ds32.base_m, al pop eax push eax add eax, offset GDT mov dword ptr gdtr + 2, eax ; полный линейный адрес в младшие 4 байта gdtr mov word ptr gdtr, gdt_size - 1 ; размер gdt в старшие 2 байта lgdt fword ptr gdtr ; загрузка gdt pop eax add eax, offset IDT mov dword ptr idtr + 2, eax mov word ptr idtr, idt_size - 1 mov eax, offset new_int08h mov int08h.offs_l, ax shr eax, 16 mov int08h.offs_h, ax mov eax, offset new_int09h mov int09h.offs_l, ax shr eax, 16 mov int09h.offs_h, ax in al, 21h ; сохранение масок прерываний контроллеров mov master, al in al, 0A1h mov slave, al mov al, 11h ; перепрограммирование ведущего контроллера out 20h, al mov al, 20h out 21h, al mov al, 4 out 21h, al mov al, 1 out 21h, al mov al, 0FCh ; запрет прерываний ведущего контр., кроме таймера и клав. out 21h, al mov al, 0FFh ; запрет всех в ведомом out 0A1h, al lidt fword ptr idtr ; загрузка idtr mov al, 0D1h ; открыть линию А20 out 64, al mov al, 0DFh out 60h, al cli in al, 70h ; запрет немаскируемых прерываний or al, 80h out 70h, al mov eax, cr0 or al, 1 mov cr0, eax db 66h ; дальний переход db 0EAh dd offset protected_mode dw 24 real_end: mov eax, cr0 ; сброс флага and al, 0FEh mov cr0, eax db 0EAh ; Дальний переход для того, чтобы заново загрузить селектор в регистр CS dw offset return dw real_seg return: mov ax, protected_seg mov ds, ax mov es, ax mov ax, stack_seg mov ss, ax mov bx, stack_size mov sp, bx mov al, 11h ; перепрограммируем ведущий контроллер out 20h, al mov al, 8 out 21h, al mov al, 4 out 21h, al mov al, 1 out 21h, al mov al, master ; восстановление масок контроллеров прерываний out 21h, al mov al, slave out 0A1h, al lidt fword ptr idtr_r ; восстанавливаем idt sti mov AL, 0 out 70h, AL mov ah, 09h mov edx, offset mes_real int 21h mov ah, 4Ch int 21h real_seg_size = $-begin real_seg ENDS END begin
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x517e, %rsi lea addresses_WT_ht+0xa0e, %rdi clflush (%rsi) clflush (%rdi) nop nop nop xor $10286, %r14 mov $74, %rcx rep movsl nop nop nop and %rsi, %rsi lea addresses_normal_ht+0x12cee, %rsi lea addresses_D_ht+0x428e, %rdi nop nop nop nop nop add %rbx, %rbx mov $115, %rcx rep movsb nop nop nop nop xor $6485, %rdi lea addresses_UC_ht+0xd17e, %rdi nop add $6728, %r8 mov (%rdi), %rsi nop nop cmp $30989, %r14 lea addresses_D_ht+0x8bbe, %r8 nop nop nop nop xor %r9, %r9 mov $0x6162636465666768, %rdi movq %rdi, %xmm7 vmovups %ymm7, (%r8) nop nop nop sub $10033, %rcx lea addresses_WC_ht+0x166c6, %r8 nop nop nop nop and %rbx, %rbx movw $0x6162, (%r8) nop nop cmp %rbx, %rbx lea addresses_D_ht+0xb37e, %rbx nop nop nop nop sub $46055, %r8 movw $0x6162, (%rbx) nop nop nop nop xor %rsi, %rsi lea addresses_WC_ht+0x1197e, %rdi nop nop nop nop and %r8, %r8 mov $0x6162636465666768, %r14 movq %r14, %xmm5 movups %xmm5, (%rdi) nop nop nop nop xor %rsi, %rsi lea addresses_D_ht+0x907e, %rsi lea addresses_normal_ht+0x537e, %rdi nop nop nop nop nop inc %r9 mov $61, %rcx rep movsw nop nop nop nop add %rdi, %rdi lea addresses_UC_ht+0x7f7e, %rsi lea addresses_normal_ht+0x14956, %rdi nop nop nop nop nop inc %r10 mov $80, %rcx rep movsw nop nop nop nop nop dec %rdi lea addresses_WT_ht+0x1b37e, %rcx nop nop nop nop add %rdi, %rdi mov (%rcx), %rsi nop nop nop xor $52688, %rdi lea addresses_WT_ht+0x1d8fe, %rsi lea addresses_WT_ht+0xe97e, %rdi nop nop nop add $44306, %r10 mov $96, %rcx rep movsq nop inc %r10 lea addresses_UC_ht+0xb97e, %rsi lea addresses_A_ht+0xc98e, %rdi nop nop dec %r10 mov $28, %rcx rep movsw nop nop sub %rsi, %rsi lea addresses_WT_ht+0x1d57e, %rdi and %rsi, %rsi movw $0x6162, (%rdi) nop nop add $11896, %r10 lea addresses_D_ht+0xe674, %rdi nop nop nop nop add %rsi, %rsi mov (%rdi), %r9d nop nop nop nop nop xor $38871, %rsi lea addresses_D_ht+0x150fe, %rsi lea addresses_WT_ht+0x13356, %rdi cmp $769, %r8 mov $27, %rcx rep movsb nop and %r10, %r10 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r15 push %rbp push %rdi // Faulty Load lea addresses_A+0x1d97e, %r11 and %r15, %r15 mov (%r11), %edi lea oracles, %r11 and $0xff, %rdi shlq $12, %rdi mov (%r11,%rdi,1), %rdi pop %rdi pop %rbp pop %r15 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}} {'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 11}} {'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': True}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 7}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': True, 'same': True, 'congruent': 1}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
; A142078: Primes congruent to 3 mod 35. ; Submitted by Jamie Morken(w1) ; 3,73,283,353,563,773,983,1123,1193,1543,1613,1753,1823,2243,2383,2593,2663,2803,3083,3433,3643,3853,3923,4133,4273,4483,4903,4973,5113,5323,5393,5743,5813,5953,6163,6373,6653,6793,6863,7213,7283,7703,8053,8123,8263,8543,8753,8893,8963,9103,9173,9733,9803,10223,10433,10853,10993,11273,11483,11833,11903,12043,12113,12253,12323,12743,12953,13093,13163,13513,13723,13933,14143,14423,14563,14633,14843,14983,15053,15193,15263,15473,15683,15823,16033,16103,16453,16943,17293,17573,17713,17783,17923 mov $1,25 mov $2,$0 add $2,2 pow $2,2 lpb $2 sub $1,24 sub $2,1 mov $3,$1 mul $3,2 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,59 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe mov $0,$1 mul $0,2 sub $0,117
; void *sp1_PreShiftSpr(uchar flag, uchar height, uchar width, void *srcframe, void *destframe, uchar rshift) ; CALLER linkage for function pointers XLIB sp1_PreShiftSpr LIB sp1_PreShiftSpr_callee XREF ASMDISP_SP1_PRESHIFTSPR_CALLEE .sp1_PreShiftSpr ld hl,2 add hl,sp ld c,(hl) inc hl inc hl ld e,(hl) inc hl ld d,(hl) inc hl ld iyl,e ld iyh,d ld e,(hl) inc hl ld d,(hl) inc hl ld b,(hl) inc hl inc hl ld a,(hl) inc hl inc hl ld h,(hl) ld l,a ld a,c jp sp1_PreShiftSpr_callee + ASMDISP_SP1_PRESHIFTSPR_CALLEE
%include "include/u7bg-all-includes.asm" %assign SpellbookDialog_ibo 0x1D %assign SpellbookDialog_containingIbo 0xAB defineAddress 348, 0x0428, SpellbookDialog_update_printReagentCount defineAddress 348, 0x04A1, SpellbookDialog_update_printReagentCount_end defineAddress 348, 0x0C32, SpellbookDialog_updateReagentCounts defineAddress 348, 0x0CD0, SpellbookDialog_updateReagentCounts_end %include "../u7-common/patch-printRuneTextOnSpellbook.asm"
; ; jfdctflt.asm - floating-point FDCT (SSE) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; ; Based on ; x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; This file contains a floating-point implementation of the forward DCT ; (Discrete Cosine Transform). The following code is based directly on ; the IJG's original jfdctflt.c; see the jfdctflt.c for more details. ; ; [TAB8] %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- %macro unpcklps2 2 ; %1=(0 1 2 3) / %2=(4 5 6 7) => %1=(0 1 4 5) shufps %1,%2,0x44 %endmacro %macro unpckhps2 2 ; %1=(0 1 2 3) / %2=(4 5 6 7) => %1=(2 3 6 7) shufps %1,%2,0xEE %endmacro ; -------------------------------------------------------------------------- SECTION SEG_CONST alignz 16 global EXTN(jconst_fdct_float_sse) EXTN(jconst_fdct_float_sse): PD_0_382 times 4 dd 0.382683432365089771728460 PD_0_707 times 4 dd 0.707106781186547524400844 PD_0_541 times 4 dd 0.541196100146196984399723 PD_1_306 times 4 dd 1.306562964876376527856643 alignz 16 ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 32 ; ; Perform the forward DCT on one block of samples. ; ; GLOBAL(void) ; jsimd_fdct_float_sse (FAST_FLOAT * data) ; %define data(b) (b)+8 ; FAST_FLOAT * data %define original_ebp ebp+0 %define wk(i) ebp-(WK_NUM-(i))*SIZEOF_XMMWORD ; xmmword wk[WK_NUM] %define WK_NUM 2 align 16 global EXTN(jsimd_fdct_float_sse) EXTN(jsimd_fdct_float_sse): push ebp mov eax,esp ; eax = original ebp sub esp, byte 4 and esp, byte (-SIZEOF_XMMWORD) ; align to 128 bits mov [esp],eax mov ebp,esp ; ebp = aligned ebp lea esp, [wk(0)] pushpic ebx ; push ecx ; need not be preserved ; push edx ; need not be preserved ; push esi ; unused ; push edi ; unused get_GOT ebx ; get GOT address ; ---- Pass 1: process rows. mov edx, POINTER [data(eax)] ; (FAST_FLOAT *) mov ecx, DCTSIZE/4 alignx 16,7 .rowloop: movaps xmm0, XMMWORD [XMMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm1, XMMWORD [XMMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm2, XMMWORD [XMMBLOCK(2,1,edx,SIZEOF_FAST_FLOAT)] movaps xmm3, XMMWORD [XMMBLOCK(3,1,edx,SIZEOF_FAST_FLOAT)] ; xmm0=(20 21 22 23), xmm2=(24 25 26 27) ; xmm1=(30 31 32 33), xmm3=(34 35 36 37) movaps xmm4,xmm0 ; transpose coefficients(phase 1) unpcklps xmm0,xmm1 ; xmm0=(20 30 21 31) unpckhps xmm4,xmm1 ; xmm4=(22 32 23 33) movaps xmm5,xmm2 ; transpose coefficients(phase 1) unpcklps xmm2,xmm3 ; xmm2=(24 34 25 35) unpckhps xmm5,xmm3 ; xmm5=(26 36 27 37) movaps xmm6, XMMWORD [XMMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm7, XMMWORD [XMMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm1, XMMWORD [XMMBLOCK(0,1,edx,SIZEOF_FAST_FLOAT)] movaps xmm3, XMMWORD [XMMBLOCK(1,1,edx,SIZEOF_FAST_FLOAT)] ; xmm6=(00 01 02 03), xmm1=(04 05 06 07) ; xmm7=(10 11 12 13), xmm3=(14 15 16 17) movaps XMMWORD [wk(0)], xmm4 ; wk(0)=(22 32 23 33) movaps XMMWORD [wk(1)], xmm2 ; wk(1)=(24 34 25 35) movaps xmm4,xmm6 ; transpose coefficients(phase 1) unpcklps xmm6,xmm7 ; xmm6=(00 10 01 11) unpckhps xmm4,xmm7 ; xmm4=(02 12 03 13) movaps xmm2,xmm1 ; transpose coefficients(phase 1) unpcklps xmm1,xmm3 ; xmm1=(04 14 05 15) unpckhps xmm2,xmm3 ; xmm2=(06 16 07 17) movaps xmm7,xmm6 ; transpose coefficients(phase 2) unpcklps2 xmm6,xmm0 ; xmm6=(00 10 20 30)=data0 unpckhps2 xmm7,xmm0 ; xmm7=(01 11 21 31)=data1 movaps xmm3,xmm2 ; transpose coefficients(phase 2) unpcklps2 xmm2,xmm5 ; xmm2=(06 16 26 36)=data6 unpckhps2 xmm3,xmm5 ; xmm3=(07 17 27 37)=data7 movaps xmm0,xmm7 movaps xmm5,xmm6 subps xmm7,xmm2 ; xmm7=data1-data6=tmp6 subps xmm6,xmm3 ; xmm6=data0-data7=tmp7 addps xmm0,xmm2 ; xmm0=data1+data6=tmp1 addps xmm5,xmm3 ; xmm5=data0+data7=tmp0 movaps xmm2, XMMWORD [wk(0)] ; xmm2=(22 32 23 33) movaps xmm3, XMMWORD [wk(1)] ; xmm3=(24 34 25 35) movaps XMMWORD [wk(0)], xmm7 ; wk(0)=tmp6 movaps XMMWORD [wk(1)], xmm6 ; wk(1)=tmp7 movaps xmm7,xmm4 ; transpose coefficients(phase 2) unpcklps2 xmm4,xmm2 ; xmm4=(02 12 22 32)=data2 unpckhps2 xmm7,xmm2 ; xmm7=(03 13 23 33)=data3 movaps xmm6,xmm1 ; transpose coefficients(phase 2) unpcklps2 xmm1,xmm3 ; xmm1=(04 14 24 34)=data4 unpckhps2 xmm6,xmm3 ; xmm6=(05 15 25 35)=data5 movaps xmm2,xmm7 movaps xmm3,xmm4 addps xmm7,xmm1 ; xmm7=data3+data4=tmp3 addps xmm4,xmm6 ; xmm4=data2+data5=tmp2 subps xmm2,xmm1 ; xmm2=data3-data4=tmp4 subps xmm3,xmm6 ; xmm3=data2-data5=tmp5 ; -- Even part movaps xmm1,xmm5 movaps xmm6,xmm0 subps xmm5,xmm7 ; xmm5=tmp13 subps xmm0,xmm4 ; xmm0=tmp12 addps xmm1,xmm7 ; xmm1=tmp10 addps xmm6,xmm4 ; xmm6=tmp11 addps xmm0,xmm5 mulps xmm0,[GOTOFF(ebx,PD_0_707)] ; xmm0=z1 movaps xmm7,xmm1 movaps xmm4,xmm5 subps xmm1,xmm6 ; xmm1=data4 subps xmm5,xmm0 ; xmm5=data6 addps xmm7,xmm6 ; xmm7=data0 addps xmm4,xmm0 ; xmm4=data2 movaps XMMWORD [XMMBLOCK(0,1,edx,SIZEOF_FAST_FLOAT)], xmm1 movaps XMMWORD [XMMBLOCK(2,1,edx,SIZEOF_FAST_FLOAT)], xmm5 movaps XMMWORD [XMMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)], xmm7 movaps XMMWORD [XMMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)], xmm4 ; -- Odd part movaps xmm6, XMMWORD [wk(0)] ; xmm6=tmp6 movaps xmm0, XMMWORD [wk(1)] ; xmm0=tmp7 addps xmm2,xmm3 ; xmm2=tmp10 addps xmm3,xmm6 ; xmm3=tmp11 addps xmm6,xmm0 ; xmm6=tmp12, xmm0=tmp7 mulps xmm3,[GOTOFF(ebx,PD_0_707)] ; xmm3=z3 movaps xmm1,xmm2 ; xmm1=tmp10 subps xmm2,xmm6 mulps xmm2,[GOTOFF(ebx,PD_0_382)] ; xmm2=z5 mulps xmm1,[GOTOFF(ebx,PD_0_541)] ; xmm1=MULTIPLY(tmp10,FIX_0_541196) mulps xmm6,[GOTOFF(ebx,PD_1_306)] ; xmm6=MULTIPLY(tmp12,FIX_1_306562) addps xmm1,xmm2 ; xmm1=z2 addps xmm6,xmm2 ; xmm6=z4 movaps xmm5,xmm0 subps xmm0,xmm3 ; xmm0=z13 addps xmm5,xmm3 ; xmm5=z11 movaps xmm7,xmm0 movaps xmm4,xmm5 subps xmm0,xmm1 ; xmm0=data3 subps xmm5,xmm6 ; xmm5=data7 addps xmm7,xmm1 ; xmm7=data5 addps xmm4,xmm6 ; xmm4=data1 movaps XMMWORD [XMMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)], xmm0 movaps XMMWORD [XMMBLOCK(3,1,edx,SIZEOF_FAST_FLOAT)], xmm5 movaps XMMWORD [XMMBLOCK(1,1,edx,SIZEOF_FAST_FLOAT)], xmm7 movaps XMMWORD [XMMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)], xmm4 add edx, 4*DCTSIZE*SIZEOF_FAST_FLOAT dec ecx jnz near .rowloop ; ---- Pass 2: process columns. mov edx, POINTER [data(eax)] ; (FAST_FLOAT *) mov ecx, DCTSIZE/4 alignx 16,7 .columnloop: movaps xmm0, XMMWORD [XMMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm1, XMMWORD [XMMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm2, XMMWORD [XMMBLOCK(6,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm3, XMMWORD [XMMBLOCK(7,0,edx,SIZEOF_FAST_FLOAT)] ; xmm0=(02 12 22 32), xmm2=(42 52 62 72) ; xmm1=(03 13 23 33), xmm3=(43 53 63 73) movaps xmm4,xmm0 ; transpose coefficients(phase 1) unpcklps xmm0,xmm1 ; xmm0=(02 03 12 13) unpckhps xmm4,xmm1 ; xmm4=(22 23 32 33) movaps xmm5,xmm2 ; transpose coefficients(phase 1) unpcklps xmm2,xmm3 ; xmm2=(42 43 52 53) unpckhps xmm5,xmm3 ; xmm5=(62 63 72 73) movaps xmm6, XMMWORD [XMMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm7, XMMWORD [XMMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm1, XMMWORD [XMMBLOCK(4,0,edx,SIZEOF_FAST_FLOAT)] movaps xmm3, XMMWORD [XMMBLOCK(5,0,edx,SIZEOF_FAST_FLOAT)] ; xmm6=(00 10 20 30), xmm1=(40 50 60 70) ; xmm7=(01 11 21 31), xmm3=(41 51 61 71) movaps XMMWORD [wk(0)], xmm4 ; wk(0)=(22 23 32 33) movaps XMMWORD [wk(1)], xmm2 ; wk(1)=(42 43 52 53) movaps xmm4,xmm6 ; transpose coefficients(phase 1) unpcklps xmm6,xmm7 ; xmm6=(00 01 10 11) unpckhps xmm4,xmm7 ; xmm4=(20 21 30 31) movaps xmm2,xmm1 ; transpose coefficients(phase 1) unpcklps xmm1,xmm3 ; xmm1=(40 41 50 51) unpckhps xmm2,xmm3 ; xmm2=(60 61 70 71) movaps xmm7,xmm6 ; transpose coefficients(phase 2) unpcklps2 xmm6,xmm0 ; xmm6=(00 01 02 03)=data0 unpckhps2 xmm7,xmm0 ; xmm7=(10 11 12 13)=data1 movaps xmm3,xmm2 ; transpose coefficients(phase 2) unpcklps2 xmm2,xmm5 ; xmm2=(60 61 62 63)=data6 unpckhps2 xmm3,xmm5 ; xmm3=(70 71 72 73)=data7 movaps xmm0,xmm7 movaps xmm5,xmm6 subps xmm7,xmm2 ; xmm7=data1-data6=tmp6 subps xmm6,xmm3 ; xmm6=data0-data7=tmp7 addps xmm0,xmm2 ; xmm0=data1+data6=tmp1 addps xmm5,xmm3 ; xmm5=data0+data7=tmp0 movaps xmm2, XMMWORD [wk(0)] ; xmm2=(22 23 32 33) movaps xmm3, XMMWORD [wk(1)] ; xmm3=(42 43 52 53) movaps XMMWORD [wk(0)], xmm7 ; wk(0)=tmp6 movaps XMMWORD [wk(1)], xmm6 ; wk(1)=tmp7 movaps xmm7,xmm4 ; transpose coefficients(phase 2) unpcklps2 xmm4,xmm2 ; xmm4=(20 21 22 23)=data2 unpckhps2 xmm7,xmm2 ; xmm7=(30 31 32 33)=data3 movaps xmm6,xmm1 ; transpose coefficients(phase 2) unpcklps2 xmm1,xmm3 ; xmm1=(40 41 42 43)=data4 unpckhps2 xmm6,xmm3 ; xmm6=(50 51 52 53)=data5 movaps xmm2,xmm7 movaps xmm3,xmm4 addps xmm7,xmm1 ; xmm7=data3+data4=tmp3 addps xmm4,xmm6 ; xmm4=data2+data5=tmp2 subps xmm2,xmm1 ; xmm2=data3-data4=tmp4 subps xmm3,xmm6 ; xmm3=data2-data5=tmp5 ; -- Even part movaps xmm1,xmm5 movaps xmm6,xmm0 subps xmm5,xmm7 ; xmm5=tmp13 subps xmm0,xmm4 ; xmm0=tmp12 addps xmm1,xmm7 ; xmm1=tmp10 addps xmm6,xmm4 ; xmm6=tmp11 addps xmm0,xmm5 mulps xmm0,[GOTOFF(ebx,PD_0_707)] ; xmm0=z1 movaps xmm7,xmm1 movaps xmm4,xmm5 subps xmm1,xmm6 ; xmm1=data4 subps xmm5,xmm0 ; xmm5=data6 addps xmm7,xmm6 ; xmm7=data0 addps xmm4,xmm0 ; xmm4=data2 movaps XMMWORD [XMMBLOCK(4,0,edx,SIZEOF_FAST_FLOAT)], xmm1 movaps XMMWORD [XMMBLOCK(6,0,edx,SIZEOF_FAST_FLOAT)], xmm5 movaps XMMWORD [XMMBLOCK(0,0,edx,SIZEOF_FAST_FLOAT)], xmm7 movaps XMMWORD [XMMBLOCK(2,0,edx,SIZEOF_FAST_FLOAT)], xmm4 ; -- Odd part movaps xmm6, XMMWORD [wk(0)] ; xmm6=tmp6 movaps xmm0, XMMWORD [wk(1)] ; xmm0=tmp7 addps xmm2,xmm3 ; xmm2=tmp10 addps xmm3,xmm6 ; xmm3=tmp11 addps xmm6,xmm0 ; xmm6=tmp12, xmm0=tmp7 mulps xmm3,[GOTOFF(ebx,PD_0_707)] ; xmm3=z3 movaps xmm1,xmm2 ; xmm1=tmp10 subps xmm2,xmm6 mulps xmm2,[GOTOFF(ebx,PD_0_382)] ; xmm2=z5 mulps xmm1,[GOTOFF(ebx,PD_0_541)] ; xmm1=MULTIPLY(tmp10,FIX_0_541196) mulps xmm6,[GOTOFF(ebx,PD_1_306)] ; xmm6=MULTIPLY(tmp12,FIX_1_306562) addps xmm1,xmm2 ; xmm1=z2 addps xmm6,xmm2 ; xmm6=z4 movaps xmm5,xmm0 subps xmm0,xmm3 ; xmm0=z13 addps xmm5,xmm3 ; xmm5=z11 movaps xmm7,xmm0 movaps xmm4,xmm5 subps xmm0,xmm1 ; xmm0=data3 subps xmm5,xmm6 ; xmm5=data7 addps xmm7,xmm1 ; xmm7=data5 addps xmm4,xmm6 ; xmm4=data1 movaps XMMWORD [XMMBLOCK(3,0,edx,SIZEOF_FAST_FLOAT)], xmm0 movaps XMMWORD [XMMBLOCK(7,0,edx,SIZEOF_FAST_FLOAT)], xmm5 movaps XMMWORD [XMMBLOCK(5,0,edx,SIZEOF_FAST_FLOAT)], xmm7 movaps XMMWORD [XMMBLOCK(1,0,edx,SIZEOF_FAST_FLOAT)], xmm4 add edx, byte 4*SIZEOF_FAST_FLOAT dec ecx jnz near .columnloop ; pop edi ; unused ; pop esi ; unused ; pop edx ; need not be preserved ; pop ecx ; need not be preserved poppic ebx mov esp,ebp ; esp <- aligned ebp pop esp ; esp <- original ebp pop ebp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
; ; Basic video handling for the PHC-25 ; ; (HL)=char to display ; ;---------------------------------------------------------------- ; ; $Id: fputc_cons.asm $ ; ;---------------------------------------------------------------- ; SECTION code_clib PUBLIC fputc_cons_native .fputc_cons_native ld hl,2 add hl,sp ld a,(hl) ; chr$(12) is CLS already IF STANDARDESCAPECHARS cp 10 ELSE cp 13 ENDIF jr nz,nocr call doputc IF STANDARDESCAPECHARS ld a,13 ELSE ld a,10 ENDIF .nocr ; cp 8 ; BS ; jr nz,nobs ; ld a,$---- ;.nobs .doputc ld e,a ld a,(1) cp $af ld a,e jp z,$108C ; Western ROM jp $1089 ; Japanese ROM
// // Created by John Kindem on 2021/4/24. // #include <Explosion/Driver/ImageView.h> #include <Explosion/Driver/Driver.h> #include <Explosion/Driver/Image.h> #include <Explosion/Driver/VkAdapater.h> namespace { VkImageAspectFlags GetImageAspect(Explosion::Image* image) { if (dynamic_cast<Explosion::ColorAttachment*>(image) != nullptr) { return VK_IMAGE_ASPECT_COLOR_BIT; } else if (dynamic_cast<Explosion::DepthStencilAttachment*>(image) != nullptr) { return VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; } else { return 0; } } } namespace Explosion { ImageView::ImageView(Driver& driver, const ImageView::Config& config) : GpuRes(driver), device(*driver.GetDevice()), config(config) {} ImageView::~ImageView() = default; void ImageView::OnCreate() { GpuRes::OnCreate(); CreateImageView(); } void ImageView::OnDestroy() { GpuRes::OnDestroy(); DestroyImageView(); } Image* ImageView::GetImage() const { return config.image; } const VkImageView& ImageView::GetVkImageView() { return vkImageView; } void ImageView::CreateImageView() { VkImageViewCreateInfo createInfo {}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.pNext = nullptr; createInfo.flags = 0; createInfo.image = config.image->GetVkImage(); createInfo.viewType = VkConvert<ImageViewType, VkImageViewType>(config.type); createInfo.format = VkConvert<Format, VkFormat>(config.image->GetConfig().format); createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = GetImageAspect(config.image); createInfo.subresourceRange.levelCount = config.mipLevelCount; createInfo.subresourceRange.baseMipLevel = config.baseMipLevel; createInfo.subresourceRange.layerCount = config.layerCount; createInfo.subresourceRange.baseArrayLayer = config.baseLayer; if (vkCreateImageView(device.GetVkDevice(), &createInfo, nullptr, &vkImageView) != VK_SUCCESS) { throw std::runtime_error("failed to create vulkan image view"); } } void ImageView::DestroyImageView() { vkDestroyImageView(device.GetVkDevice(), vkImageView, nullptr); } }
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: w_unplot_callee.asm $ ; ; CALLER LINKAGE FOR FUNCTION POINTERS ; ----- void unplot(int x, int y) SECTION code_graphics PUBLIC unplot_callee PUBLIC _unplot_callee PUBLIC ASMDISP_UNPLOT_CALLEE EXTERN swapgfxbk EXTERN __graphics_end EXTERN w_respixel .unplot_callee ._unplot_callee pop af pop de ; y pop hl ; x push af .asmentry push ix call swapgfxbk call w_respixel jp __graphics_end DEFC ASMDISP_UNPLOT_CALLEE = # asmentry - unplot_callee
; A162316: a(n) = 5n^2 + 20n + 1. ; Submitted by Christian Krause ; 1,26,61,106,161,226,301,386,481,586,701,826,961,1106,1261,1426,1601,1786,1981,2186,2401,2626,2861,3106,3361,3626,3901,4186,4481,4786,5101,5426,5761,6106,6461,6826,7201,7586,7981,8386,8801,9226,9661,10106,10561,11026,11501,11986,12481,12986,13501,14026,14561,15106,15661,16226,16801,17386,17981,18586,19201,19826,20461,21106,21761,22426,23101,23786,24481,25186,25901,26626,27361,28106,28861,29626,30401,31186,31981,32786,33601,34426,35261,36106,36961,37826,38701,39586,40481,41386,42301,43226,44161 add $0,2 pow $0,2 sub $0,4 mul $0,5 add $0,1
_sh: file format elf32-i386 Disassembly of section .text: 00000000 <main>: return 0; } int main(void) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp static char buf[100]; int fd; // Ensure that three file descriptors are open. while((fd = open("console", O_RDWR)) >= 0){ 11: eb 0e jmp 21 <main+0x21> 13: 90 nop 14: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if(fd >= 3){ 18: 83 f8 02 cmp $0x2,%eax 1b: 0f 8f c3 00 00 00 jg e4 <main+0xe4> { static char buf[100]; int fd; // Ensure that three file descriptors are open. while((fd = open("console", O_RDWR)) >= 0){ 21: 83 ec 08 sub $0x8,%esp 24: 6a 02 push $0x2 26: 68 51 12 00 00 push $0x1251 2b: e8 32 0d 00 00 call d62 <open> 30: 83 c4 10 add $0x10,%esp 33: 85 c0 test %eax,%eax 35: 79 e1 jns 18 <main+0x18> 37: eb 2e jmp 67 <main+0x67> 39: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi } } // Read and run input commands. while(getcmd(buf, sizeof(buf)) >= 0){ if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ 40: 80 3d 62 18 00 00 20 cmpb $0x20,0x1862 47: 74 5d je a6 <main+0xa6> 49: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi int fork1(void) { int pid; pid = fork(); 50: e8 c5 0c 00 00 call d1a <fork> if(pid == -1) 55: 83 f8 ff cmp $0xffffffff,%eax 58: 74 3f je 99 <main+0x99> buf[strlen(buf)-1] = 0; // chop \n if(chdir(buf+3) < 0) printf(2, "cannot cd %s\n", buf+3); continue; } if(fork1() == 0) 5a: 85 c0 test %eax,%eax 5c: 0f 84 98 00 00 00 je fa <main+0xfa> runcmd(parsecmd(buf)); wait(); 62: e8 c3 0c 00 00 call d2a <wait> break; } } // Read and run input commands. while(getcmd(buf, sizeof(buf)) >= 0){ 67: 83 ec 08 sub $0x8,%esp 6a: 6a 64 push $0x64 6c: 68 60 18 00 00 push $0x1860 71: e8 9a 00 00 00 call 110 <getcmd> 76: 83 c4 10 add $0x10,%esp 79: 85 c0 test %eax,%eax 7b: 78 78 js f5 <main+0xf5> if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ 7d: 80 3d 60 18 00 00 63 cmpb $0x63,0x1860 84: 75 ca jne 50 <main+0x50> 86: 80 3d 61 18 00 00 64 cmpb $0x64,0x1861 8d: 74 b1 je 40 <main+0x40> int fork1(void) { int pid; pid = fork(); 8f: e8 86 0c 00 00 call d1a <fork> if(pid == -1) 94: 83 f8 ff cmp $0xffffffff,%eax 97: 75 c1 jne 5a <main+0x5a> panic("fork"); 99: 83 ec 0c sub $0xc,%esp 9c: 68 da 11 00 00 push $0x11da a1: e8 ba 00 00 00 call 160 <panic> // Read and run input commands. while(getcmd(buf, sizeof(buf)) >= 0){ if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ // Chdir must be called by the parent, not the child. buf[strlen(buf)-1] = 0; // chop \n a6: 83 ec 0c sub $0xc,%esp a9: 68 60 18 00 00 push $0x1860 ae: e8 ad 0a 00 00 call b60 <strlen> if(chdir(buf+3) < 0) b3: c7 04 24 63 18 00 00 movl $0x1863,(%esp) // Read and run input commands. while(getcmd(buf, sizeof(buf)) >= 0){ if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ // Chdir must be called by the parent, not the child. buf[strlen(buf)-1] = 0; // chop \n ba: c6 80 5f 18 00 00 00 movb $0x0,0x185f(%eax) if(chdir(buf+3) < 0) c1: e8 cc 0c 00 00 call d92 <chdir> c6: 83 c4 10 add $0x10,%esp c9: 85 c0 test %eax,%eax cb: 79 9a jns 67 <main+0x67> printf(2, "cannot cd %s\n", buf+3); cd: 50 push %eax ce: 68 63 18 00 00 push $0x1863 d3: 68 59 12 00 00 push $0x1259 d8: 6a 02 push $0x2 da: e8 b1 0d 00 00 call e90 <printf> df: 83 c4 10 add $0x10,%esp e2: eb 83 jmp 67 <main+0x67> int fd; // Ensure that three file descriptors are open. while((fd = open("console", O_RDWR)) >= 0){ if(fd >= 3){ close(fd); e4: 83 ec 0c sub $0xc,%esp e7: 50 push %eax e8: e8 5d 0c 00 00 call d4a <close> break; ed: 83 c4 10 add $0x10,%esp f0: e9 72 ff ff ff jmp 67 <main+0x67> } if(fork1() == 0) runcmd(parsecmd(buf)); wait(); } exit(); f5: e8 28 0c 00 00 call d22 <exit> if(chdir(buf+3) < 0) printf(2, "cannot cd %s\n", buf+3); continue; } if(fork1() == 0) runcmd(parsecmd(buf)); fa: 83 ec 0c sub $0xc,%esp fd: 68 60 18 00 00 push $0x1860 102: e8 69 09 00 00 call a70 <parsecmd> 107: 89 04 24 mov %eax,(%esp) 10a: e8 71 00 00 00 call 180 <runcmd> 10f: 90 nop 00000110 <getcmd>: exit(); } int getcmd(char *buf, int nbuf) { 110: 55 push %ebp 111: 89 e5 mov %esp,%ebp 113: 56 push %esi 114: 53 push %ebx 115: 8b 75 0c mov 0xc(%ebp),%esi 118: 8b 5d 08 mov 0x8(%ebp),%ebx printf(2, "$ "); 11b: 83 ec 08 sub $0x8,%esp 11e: 68 b0 11 00 00 push $0x11b0 123: 6a 02 push $0x2 125: e8 66 0d 00 00 call e90 <printf> memset(buf, 0, nbuf); 12a: 83 c4 0c add $0xc,%esp 12d: 56 push %esi 12e: 6a 00 push $0x0 130: 53 push %ebx 131: e8 5a 0a 00 00 call b90 <memset> gets(buf, nbuf); 136: 58 pop %eax 137: 5a pop %edx 138: 56 push %esi 139: 53 push %ebx 13a: e8 b1 0a 00 00 call bf0 <gets> 13f: 83 c4 10 add $0x10,%esp 142: 31 c0 xor %eax,%eax 144: 80 3b 00 cmpb $0x0,(%ebx) 147: 0f 94 c0 sete %al if(buf[0] == 0) // EOF return -1; return 0; } 14a: 8d 65 f8 lea -0x8(%ebp),%esp 14d: f7 d8 neg %eax 14f: 5b pop %ebx 150: 5e pop %esi 151: 5d pop %ebp 152: c3 ret 153: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 159: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000160 <panic>: exit(); } void panic(char *s) { 160: 55 push %ebp 161: 89 e5 mov %esp,%ebp 163: 83 ec 0c sub $0xc,%esp printf(2, "%s\n", s); 166: ff 75 08 pushl 0x8(%ebp) 169: 68 4d 12 00 00 push $0x124d 16e: 6a 02 push $0x2 170: e8 1b 0d 00 00 call e90 <printf> exit(); 175: e8 a8 0b 00 00 call d22 <exit> 17a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00000180 <runcmd>: struct cmd *parsecmd(char*); // Execute cmd. Never returns. void runcmd(struct cmd *cmd) { 180: 55 push %ebp 181: 89 e5 mov %esp,%ebp 183: 53 push %ebx 184: 83 ec 14 sub $0x14,%esp 187: 8b 5d 08 mov 0x8(%ebp),%ebx struct execcmd *ecmd; struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) 18a: 85 db test %ebx,%ebx 18c: 74 76 je 204 <runcmd+0x84> exit(); switch(cmd->type){ 18e: 83 3b 05 cmpl $0x5,(%ebx) 191: 0f 87 f8 00 00 00 ja 28f <runcmd+0x10f> 197: 8b 03 mov (%ebx),%eax 199: ff 24 85 68 12 00 00 jmp *0x1268(,%eax,4) runcmd(lcmd->right); break; case PIPE: pcmd = (struct pipecmd*)cmd; if(pipe(p) < 0) 1a0: 8d 45 f0 lea -0x10(%ebp),%eax 1a3: 83 ec 0c sub $0xc,%esp 1a6: 50 push %eax 1a7: e8 86 0b 00 00 call d32 <pipe> 1ac: 83 c4 10 add $0x10,%esp 1af: 85 c0 test %eax,%eax 1b1: 0f 88 07 01 00 00 js 2be <runcmd+0x13e> int fork1(void) { int pid; pid = fork(); 1b7: e8 5e 0b 00 00 call d1a <fork> if(pid == -1) 1bc: 83 f8 ff cmp $0xffffffff,%eax 1bf: 0f 84 d7 00 00 00 je 29c <runcmd+0x11c> case PIPE: pcmd = (struct pipecmd*)cmd; if(pipe(p) < 0) panic("pipe"); if(fork1() == 0){ 1c5: 85 c0 test %eax,%eax 1c7: 0f 84 fe 00 00 00 je 2cb <runcmd+0x14b> int fork1(void) { int pid; pid = fork(); 1cd: e8 48 0b 00 00 call d1a <fork> if(pid == -1) 1d2: 83 f8 ff cmp $0xffffffff,%eax 1d5: 0f 84 c1 00 00 00 je 29c <runcmd+0x11c> dup(p[1]); close(p[0]); close(p[1]); runcmd(pcmd->left); } if(fork1() == 0){ 1db: 85 c0 test %eax,%eax 1dd: 0f 84 16 01 00 00 je 2f9 <runcmd+0x179> dup(p[0]); close(p[0]); close(p[1]); runcmd(pcmd->right); } close(p[0]); 1e3: 83 ec 0c sub $0xc,%esp 1e6: ff 75 f0 pushl -0x10(%ebp) 1e9: e8 5c 0b 00 00 call d4a <close> close(p[1]); 1ee: 58 pop %eax 1ef: ff 75 f4 pushl -0xc(%ebp) 1f2: e8 53 0b 00 00 call d4a <close> wait(); 1f7: e8 2e 0b 00 00 call d2a <wait> wait(); 1fc: e8 29 0b 00 00 call d2a <wait> break; 201: 83 c4 10 add $0x10,%esp struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) exit(); 204: e8 19 0b 00 00 call d22 <exit> int fork1(void) { int pid; pid = fork(); 209: e8 0c 0b 00 00 call d1a <fork> if(pid == -1) 20e: 83 f8 ff cmp $0xffffffff,%eax 211: 0f 84 85 00 00 00 je 29c <runcmd+0x11c> wait(); break; case BACK: bcmd = (struct backcmd*)cmd; if(fork1() == 0) 217: 85 c0 test %eax,%eax 219: 75 e9 jne 204 <runcmd+0x84> 21b: eb 49 jmp 266 <runcmd+0xe6> default: panic("runcmd"); case EXEC: ecmd = (struct execcmd*)cmd; if(ecmd->argv[0] == 0) 21d: 8b 43 04 mov 0x4(%ebx),%eax 220: 85 c0 test %eax,%eax 222: 74 e0 je 204 <runcmd+0x84> exit(); exec(ecmd->argv[0], ecmd->argv); 224: 52 push %edx 225: 52 push %edx 226: 8d 53 04 lea 0x4(%ebx),%edx 229: 52 push %edx 22a: 50 push %eax 22b: e8 2a 0b 00 00 call d5a <exec> printf(2, "exec %s failed\n", ecmd->argv[0]); 230: 83 c4 0c add $0xc,%esp 233: ff 73 04 pushl 0x4(%ebx) 236: 68 ba 11 00 00 push $0x11ba 23b: 6a 02 push $0x2 23d: e8 4e 0c 00 00 call e90 <printf> break; 242: 83 c4 10 add $0x10,%esp 245: eb bd jmp 204 <runcmd+0x84> case REDIR: rcmd = (struct redircmd*)cmd; close(rcmd->fd); 247: 83 ec 0c sub $0xc,%esp 24a: ff 73 14 pushl 0x14(%ebx) 24d: e8 f8 0a 00 00 call d4a <close> if(open(rcmd->file, rcmd->mode) < 0){ 252: 59 pop %ecx 253: 58 pop %eax 254: ff 73 10 pushl 0x10(%ebx) 257: ff 73 08 pushl 0x8(%ebx) 25a: e8 03 0b 00 00 call d62 <open> 25f: 83 c4 10 add $0x10,%esp 262: 85 c0 test %eax,%eax 264: 78 43 js 2a9 <runcmd+0x129> break; case BACK: bcmd = (struct backcmd*)cmd; if(fork1() == 0) runcmd(bcmd->cmd); 266: 83 ec 0c sub $0xc,%esp 269: ff 73 04 pushl 0x4(%ebx) 26c: e8 0f ff ff ff call 180 <runcmd> int fork1(void) { int pid; pid = fork(); 271: e8 a4 0a 00 00 call d1a <fork> if(pid == -1) 276: 83 f8 ff cmp $0xffffffff,%eax 279: 74 21 je 29c <runcmd+0x11c> runcmd(rcmd->cmd); break; case LIST: lcmd = (struct listcmd*)cmd; if(fork1() == 0) 27b: 85 c0 test %eax,%eax 27d: 74 e7 je 266 <runcmd+0xe6> runcmd(lcmd->left); wait(); 27f: e8 a6 0a 00 00 call d2a <wait> runcmd(lcmd->right); 284: 83 ec 0c sub $0xc,%esp 287: ff 73 08 pushl 0x8(%ebx) 28a: e8 f1 fe ff ff call 180 <runcmd> if(cmd == 0) exit(); switch(cmd->type){ default: panic("runcmd"); 28f: 83 ec 0c sub $0xc,%esp 292: 68 b3 11 00 00 push $0x11b3 297: e8 c4 fe ff ff call 160 <panic> { int pid; pid = fork(); if(pid == -1) panic("fork"); 29c: 83 ec 0c sub $0xc,%esp 29f: 68 da 11 00 00 push $0x11da 2a4: e8 b7 fe ff ff call 160 <panic> case REDIR: rcmd = (struct redircmd*)cmd; close(rcmd->fd); if(open(rcmd->file, rcmd->mode) < 0){ printf(2, "open %s failed\n", rcmd->file); 2a9: 52 push %edx 2aa: ff 73 08 pushl 0x8(%ebx) 2ad: 68 ca 11 00 00 push $0x11ca 2b2: 6a 02 push $0x2 2b4: e8 d7 0b 00 00 call e90 <printf> exit(); 2b9: e8 64 0a 00 00 call d22 <exit> break; case PIPE: pcmd = (struct pipecmd*)cmd; if(pipe(p) < 0) panic("pipe"); 2be: 83 ec 0c sub $0xc,%esp 2c1: 68 df 11 00 00 push $0x11df 2c6: e8 95 fe ff ff call 160 <panic> if(fork1() == 0){ close(1); 2cb: 83 ec 0c sub $0xc,%esp 2ce: 6a 01 push $0x1 2d0: e8 75 0a 00 00 call d4a <close> dup(p[1]); 2d5: 58 pop %eax 2d6: ff 75 f4 pushl -0xc(%ebp) 2d9: e8 bc 0a 00 00 call d9a <dup> close(p[0]); 2de: 58 pop %eax 2df: ff 75 f0 pushl -0x10(%ebp) 2e2: e8 63 0a 00 00 call d4a <close> close(p[1]); 2e7: 58 pop %eax 2e8: ff 75 f4 pushl -0xc(%ebp) 2eb: e8 5a 0a 00 00 call d4a <close> runcmd(pcmd->left); 2f0: 58 pop %eax 2f1: ff 73 04 pushl 0x4(%ebx) 2f4: e8 87 fe ff ff call 180 <runcmd> } if(fork1() == 0){ close(0); 2f9: 83 ec 0c sub $0xc,%esp 2fc: 6a 00 push $0x0 2fe: e8 47 0a 00 00 call d4a <close> dup(p[0]); 303: 5a pop %edx 304: ff 75 f0 pushl -0x10(%ebp) 307: e8 8e 0a 00 00 call d9a <dup> close(p[0]); 30c: 59 pop %ecx 30d: ff 75 f0 pushl -0x10(%ebp) 310: e8 35 0a 00 00 call d4a <close> close(p[1]); 315: 58 pop %eax 316: ff 75 f4 pushl -0xc(%ebp) 319: e8 2c 0a 00 00 call d4a <close> runcmd(pcmd->right); 31e: 58 pop %eax 31f: ff 73 08 pushl 0x8(%ebx) 322: e8 59 fe ff ff call 180 <runcmd> 327: 89 f6 mov %esi,%esi 329: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000330 <fork1>: exit(); } int fork1(void) { 330: 55 push %ebp 331: 89 e5 mov %esp,%ebp 333: 83 ec 08 sub $0x8,%esp int pid; pid = fork(); 336: e8 df 09 00 00 call d1a <fork> if(pid == -1) 33b: 83 f8 ff cmp $0xffffffff,%eax 33e: 74 02 je 342 <fork1+0x12> panic("fork"); return pid; } 340: c9 leave 341: c3 ret { int pid; pid = fork(); if(pid == -1) panic("fork"); 342: 83 ec 0c sub $0xc,%esp 345: 68 da 11 00 00 push $0x11da 34a: e8 11 fe ff ff call 160 <panic> 34f: 90 nop 00000350 <execcmd>: //PAGEBREAK! // Constructors struct cmd* execcmd(void) { 350: 55 push %ebp 351: 89 e5 mov %esp,%ebp 353: 53 push %ebx 354: 83 ec 10 sub $0x10,%esp struct execcmd *cmd; cmd = malloc(sizeof(*cmd)); 357: 6a 54 push $0x54 359: e8 62 0d 00 00 call 10c0 <malloc> memset(cmd, 0, sizeof(*cmd)); 35e: 83 c4 0c add $0xc,%esp struct cmd* execcmd(void) { struct execcmd *cmd; cmd = malloc(sizeof(*cmd)); 361: 89 c3 mov %eax,%ebx memset(cmd, 0, sizeof(*cmd)); 363: 6a 54 push $0x54 365: 6a 00 push $0x0 367: 50 push %eax 368: e8 23 08 00 00 call b90 <memset> cmd->type = EXEC; 36d: c7 03 01 00 00 00 movl $0x1,(%ebx) return (struct cmd*)cmd; } 373: 89 d8 mov %ebx,%eax 375: 8b 5d fc mov -0x4(%ebp),%ebx 378: c9 leave 379: c3 ret 37a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00000380 <redircmd>: struct cmd* redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd) { 380: 55 push %ebp 381: 89 e5 mov %esp,%ebp 383: 53 push %ebx 384: 83 ec 10 sub $0x10,%esp struct redircmd *cmd; cmd = malloc(sizeof(*cmd)); 387: 6a 18 push $0x18 389: e8 32 0d 00 00 call 10c0 <malloc> memset(cmd, 0, sizeof(*cmd)); 38e: 83 c4 0c add $0xc,%esp struct cmd* redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd) { struct redircmd *cmd; cmd = malloc(sizeof(*cmd)); 391: 89 c3 mov %eax,%ebx memset(cmd, 0, sizeof(*cmd)); 393: 6a 18 push $0x18 395: 6a 00 push $0x0 397: 50 push %eax 398: e8 f3 07 00 00 call b90 <memset> cmd->type = REDIR; cmd->cmd = subcmd; 39d: 8b 45 08 mov 0x8(%ebp),%eax { struct redircmd *cmd; cmd = malloc(sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd)); cmd->type = REDIR; 3a0: c7 03 02 00 00 00 movl $0x2,(%ebx) cmd->cmd = subcmd; 3a6: 89 43 04 mov %eax,0x4(%ebx) cmd->file = file; 3a9: 8b 45 0c mov 0xc(%ebp),%eax 3ac: 89 43 08 mov %eax,0x8(%ebx) cmd->efile = efile; 3af: 8b 45 10 mov 0x10(%ebp),%eax 3b2: 89 43 0c mov %eax,0xc(%ebx) cmd->mode = mode; 3b5: 8b 45 14 mov 0x14(%ebp),%eax 3b8: 89 43 10 mov %eax,0x10(%ebx) cmd->fd = fd; 3bb: 8b 45 18 mov 0x18(%ebp),%eax 3be: 89 43 14 mov %eax,0x14(%ebx) return (struct cmd*)cmd; } 3c1: 89 d8 mov %ebx,%eax 3c3: 8b 5d fc mov -0x4(%ebp),%ebx 3c6: c9 leave 3c7: c3 ret 3c8: 90 nop 3c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000003d0 <pipecmd>: struct cmd* pipecmd(struct cmd *left, struct cmd *right) { 3d0: 55 push %ebp 3d1: 89 e5 mov %esp,%ebp 3d3: 53 push %ebx 3d4: 83 ec 10 sub $0x10,%esp struct pipecmd *cmd; cmd = malloc(sizeof(*cmd)); 3d7: 6a 0c push $0xc 3d9: e8 e2 0c 00 00 call 10c0 <malloc> memset(cmd, 0, sizeof(*cmd)); 3de: 83 c4 0c add $0xc,%esp struct cmd* pipecmd(struct cmd *left, struct cmd *right) { struct pipecmd *cmd; cmd = malloc(sizeof(*cmd)); 3e1: 89 c3 mov %eax,%ebx memset(cmd, 0, sizeof(*cmd)); 3e3: 6a 0c push $0xc 3e5: 6a 00 push $0x0 3e7: 50 push %eax 3e8: e8 a3 07 00 00 call b90 <memset> cmd->type = PIPE; cmd->left = left; 3ed: 8b 45 08 mov 0x8(%ebp),%eax { struct pipecmd *cmd; cmd = malloc(sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd)); cmd->type = PIPE; 3f0: c7 03 03 00 00 00 movl $0x3,(%ebx) cmd->left = left; 3f6: 89 43 04 mov %eax,0x4(%ebx) cmd->right = right; 3f9: 8b 45 0c mov 0xc(%ebp),%eax 3fc: 89 43 08 mov %eax,0x8(%ebx) return (struct cmd*)cmd; } 3ff: 89 d8 mov %ebx,%eax 401: 8b 5d fc mov -0x4(%ebp),%ebx 404: c9 leave 405: c3 ret 406: 8d 76 00 lea 0x0(%esi),%esi 409: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000410 <listcmd>: struct cmd* listcmd(struct cmd *left, struct cmd *right) { 410: 55 push %ebp 411: 89 e5 mov %esp,%ebp 413: 53 push %ebx 414: 83 ec 10 sub $0x10,%esp struct listcmd *cmd; cmd = malloc(sizeof(*cmd)); 417: 6a 0c push $0xc 419: e8 a2 0c 00 00 call 10c0 <malloc> memset(cmd, 0, sizeof(*cmd)); 41e: 83 c4 0c add $0xc,%esp struct cmd* listcmd(struct cmd *left, struct cmd *right) { struct listcmd *cmd; cmd = malloc(sizeof(*cmd)); 421: 89 c3 mov %eax,%ebx memset(cmd, 0, sizeof(*cmd)); 423: 6a 0c push $0xc 425: 6a 00 push $0x0 427: 50 push %eax 428: e8 63 07 00 00 call b90 <memset> cmd->type = LIST; cmd->left = left; 42d: 8b 45 08 mov 0x8(%ebp),%eax { struct listcmd *cmd; cmd = malloc(sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd)); cmd->type = LIST; 430: c7 03 04 00 00 00 movl $0x4,(%ebx) cmd->left = left; 436: 89 43 04 mov %eax,0x4(%ebx) cmd->right = right; 439: 8b 45 0c mov 0xc(%ebp),%eax 43c: 89 43 08 mov %eax,0x8(%ebx) return (struct cmd*)cmd; } 43f: 89 d8 mov %ebx,%eax 441: 8b 5d fc mov -0x4(%ebp),%ebx 444: c9 leave 445: c3 ret 446: 8d 76 00 lea 0x0(%esi),%esi 449: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000450 <backcmd>: struct cmd* backcmd(struct cmd *subcmd) { 450: 55 push %ebp 451: 89 e5 mov %esp,%ebp 453: 53 push %ebx 454: 83 ec 10 sub $0x10,%esp struct backcmd *cmd; cmd = malloc(sizeof(*cmd)); 457: 6a 08 push $0x8 459: e8 62 0c 00 00 call 10c0 <malloc> memset(cmd, 0, sizeof(*cmd)); 45e: 83 c4 0c add $0xc,%esp struct cmd* backcmd(struct cmd *subcmd) { struct backcmd *cmd; cmd = malloc(sizeof(*cmd)); 461: 89 c3 mov %eax,%ebx memset(cmd, 0, sizeof(*cmd)); 463: 6a 08 push $0x8 465: 6a 00 push $0x0 467: 50 push %eax 468: e8 23 07 00 00 call b90 <memset> cmd->type = BACK; cmd->cmd = subcmd; 46d: 8b 45 08 mov 0x8(%ebp),%eax { struct backcmd *cmd; cmd = malloc(sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd)); cmd->type = BACK; 470: c7 03 05 00 00 00 movl $0x5,(%ebx) cmd->cmd = subcmd; 476: 89 43 04 mov %eax,0x4(%ebx) return (struct cmd*)cmd; } 479: 89 d8 mov %ebx,%eax 47b: 8b 5d fc mov -0x4(%ebp),%ebx 47e: c9 leave 47f: c3 ret 00000480 <gettoken>: char whitespace[] = " \t\r\n\v"; char symbols[] = "<|>&;()"; int gettoken(char **ps, char *es, char **q, char **eq) { 480: 55 push %ebp 481: 89 e5 mov %esp,%ebp 483: 57 push %edi 484: 56 push %esi 485: 53 push %ebx 486: 83 ec 0c sub $0xc,%esp char *s; int ret; s = *ps; 489: 8b 45 08 mov 0x8(%ebp),%eax char whitespace[] = " \t\r\n\v"; char symbols[] = "<|>&;()"; int gettoken(char **ps, char *es, char **q, char **eq) { 48c: 8b 5d 0c mov 0xc(%ebp),%ebx 48f: 8b 75 10 mov 0x10(%ebp),%esi char *s; int ret; s = *ps; 492: 8b 38 mov (%eax),%edi while(s < es && strchr(whitespace, *s)) 494: 39 df cmp %ebx,%edi 496: 72 13 jb 4ab <gettoken+0x2b> 498: eb 29 jmp 4c3 <gettoken+0x43> 49a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi s++; 4a0: 83 c7 01 add $0x1,%edi { char *s; int ret; s = *ps; while(s < es && strchr(whitespace, *s)) 4a3: 39 fb cmp %edi,%ebx 4a5: 0f 84 ed 00 00 00 je 598 <gettoken+0x118> 4ab: 0f be 07 movsbl (%edi),%eax 4ae: 83 ec 08 sub $0x8,%esp 4b1: 50 push %eax 4b2: 68 58 18 00 00 push $0x1858 4b7: e8 f4 06 00 00 call bb0 <strchr> 4bc: 83 c4 10 add $0x10,%esp 4bf: 85 c0 test %eax,%eax 4c1: 75 dd jne 4a0 <gettoken+0x20> s++; if(q) 4c3: 85 f6 test %esi,%esi 4c5: 74 02 je 4c9 <gettoken+0x49> *q = s; 4c7: 89 3e mov %edi,(%esi) ret = *s; 4c9: 0f be 37 movsbl (%edi),%esi 4cc: 89 f1 mov %esi,%ecx 4ce: 89 f0 mov %esi,%eax switch(*s){ 4d0: 80 f9 29 cmp $0x29,%cl 4d3: 7f 5b jg 530 <gettoken+0xb0> 4d5: 80 f9 28 cmp $0x28,%cl 4d8: 7d 61 jge 53b <gettoken+0xbb> 4da: 84 c9 test %cl,%cl 4dc: 0f 85 de 00 00 00 jne 5c0 <gettoken+0x140> ret = 'a'; while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) s++; break; } if(eq) 4e2: 8b 55 14 mov 0x14(%ebp),%edx 4e5: 85 d2 test %edx,%edx 4e7: 74 05 je 4ee <gettoken+0x6e> *eq = s; 4e9: 8b 45 14 mov 0x14(%ebp),%eax 4ec: 89 38 mov %edi,(%eax) while(s < es && strchr(whitespace, *s)) 4ee: 39 fb cmp %edi,%ebx 4f0: 77 0d ja 4ff <gettoken+0x7f> 4f2: eb 23 jmp 517 <gettoken+0x97> 4f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi s++; 4f8: 83 c7 01 add $0x1,%edi break; } if(eq) *eq = s; while(s < es && strchr(whitespace, *s)) 4fb: 39 fb cmp %edi,%ebx 4fd: 74 18 je 517 <gettoken+0x97> 4ff: 0f be 07 movsbl (%edi),%eax 502: 83 ec 08 sub $0x8,%esp 505: 50 push %eax 506: 68 58 18 00 00 push $0x1858 50b: e8 a0 06 00 00 call bb0 <strchr> 510: 83 c4 10 add $0x10,%esp 513: 85 c0 test %eax,%eax 515: 75 e1 jne 4f8 <gettoken+0x78> s++; *ps = s; 517: 8b 45 08 mov 0x8(%ebp),%eax 51a: 89 38 mov %edi,(%eax) return ret; } 51c: 8d 65 f4 lea -0xc(%ebp),%esp 51f: 89 f0 mov %esi,%eax 521: 5b pop %ebx 522: 5e pop %esi 523: 5f pop %edi 524: 5d pop %ebp 525: c3 ret 526: 8d 76 00 lea 0x0(%esi),%esi 529: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi while(s < es && strchr(whitespace, *s)) s++; if(q) *q = s; ret = *s; switch(*s){ 530: 80 f9 3e cmp $0x3e,%cl 533: 75 0b jne 540 <gettoken+0xc0> case '<': s++; break; case '>': s++; if(*s == '>'){ 535: 80 7f 01 3e cmpb $0x3e,0x1(%edi) 539: 74 75 je 5b0 <gettoken+0x130> case '&': case '<': s++; break; case '>': s++; 53b: 83 c7 01 add $0x1,%edi 53e: eb a2 jmp 4e2 <gettoken+0x62> while(s < es && strchr(whitespace, *s)) s++; if(q) *q = s; ret = *s; switch(*s){ 540: 7f 5e jg 5a0 <gettoken+0x120> 542: 83 e9 3b sub $0x3b,%ecx 545: 80 f9 01 cmp $0x1,%cl 548: 76 f1 jbe 53b <gettoken+0xbb> s++; } break; default: ret = 'a'; while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) 54a: 39 fb cmp %edi,%ebx 54c: 77 24 ja 572 <gettoken+0xf2> 54e: eb 7c jmp 5cc <gettoken+0x14c> 550: 0f be 07 movsbl (%edi),%eax 553: 83 ec 08 sub $0x8,%esp 556: 50 push %eax 557: 68 50 18 00 00 push $0x1850 55c: e8 4f 06 00 00 call bb0 <strchr> 561: 83 c4 10 add $0x10,%esp 564: 85 c0 test %eax,%eax 566: 75 1f jne 587 <gettoken+0x107> s++; 568: 83 c7 01 add $0x1,%edi s++; } break; default: ret = 'a'; while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) 56b: 39 fb cmp %edi,%ebx 56d: 74 5b je 5ca <gettoken+0x14a> 56f: 0f be 07 movsbl (%edi),%eax 572: 83 ec 08 sub $0x8,%esp 575: 50 push %eax 576: 68 58 18 00 00 push $0x1858 57b: e8 30 06 00 00 call bb0 <strchr> 580: 83 c4 10 add $0x10,%esp 583: 85 c0 test %eax,%eax 585: 74 c9 je 550 <gettoken+0xd0> ret = '+'; s++; } break; default: ret = 'a'; 587: be 61 00 00 00 mov $0x61,%esi 58c: e9 51 ff ff ff jmp 4e2 <gettoken+0x62> 591: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 598: 89 df mov %ebx,%edi 59a: e9 24 ff ff ff jmp 4c3 <gettoken+0x43> 59f: 90 nop while(s < es && strchr(whitespace, *s)) s++; if(q) *q = s; ret = *s; switch(*s){ 5a0: 80 f9 7c cmp $0x7c,%cl 5a3: 74 96 je 53b <gettoken+0xbb> 5a5: eb a3 jmp 54a <gettoken+0xca> 5a7: 89 f6 mov %esi,%esi 5a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi break; case '>': s++; if(*s == '>'){ ret = '+'; s++; 5b0: 83 c7 02 add $0x2,%edi s++; break; case '>': s++; if(*s == '>'){ ret = '+'; 5b3: be 2b 00 00 00 mov $0x2b,%esi 5b8: e9 25 ff ff ff jmp 4e2 <gettoken+0x62> 5bd: 8d 76 00 lea 0x0(%esi),%esi while(s < es && strchr(whitespace, *s)) s++; if(q) *q = s; ret = *s; switch(*s){ 5c0: 80 f9 26 cmp $0x26,%cl 5c3: 75 85 jne 54a <gettoken+0xca> 5c5: e9 71 ff ff ff jmp 53b <gettoken+0xbb> 5ca: 89 df mov %ebx,%edi ret = 'a'; while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) s++; break; } if(eq) 5cc: 8b 45 14 mov 0x14(%ebp),%eax 5cf: be 61 00 00 00 mov $0x61,%esi 5d4: 85 c0 test %eax,%eax 5d6: 0f 85 0d ff ff ff jne 4e9 <gettoken+0x69> 5dc: e9 36 ff ff ff jmp 517 <gettoken+0x97> 5e1: eb 0d jmp 5f0 <peek> 5e3: 90 nop 5e4: 90 nop 5e5: 90 nop 5e6: 90 nop 5e7: 90 nop 5e8: 90 nop 5e9: 90 nop 5ea: 90 nop 5eb: 90 nop 5ec: 90 nop 5ed: 90 nop 5ee: 90 nop 5ef: 90 nop 000005f0 <peek>: return ret; } int peek(char **ps, char *es, char *toks) { 5f0: 55 push %ebp 5f1: 89 e5 mov %esp,%ebp 5f3: 57 push %edi 5f4: 56 push %esi 5f5: 53 push %ebx 5f6: 83 ec 0c sub $0xc,%esp 5f9: 8b 7d 08 mov 0x8(%ebp),%edi 5fc: 8b 75 0c mov 0xc(%ebp),%esi char *s; s = *ps; 5ff: 8b 1f mov (%edi),%ebx while(s < es && strchr(whitespace, *s)) 601: 39 f3 cmp %esi,%ebx 603: 72 12 jb 617 <peek+0x27> 605: eb 28 jmp 62f <peek+0x3f> 607: 89 f6 mov %esi,%esi 609: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi s++; 610: 83 c3 01 add $0x1,%ebx peek(char **ps, char *es, char *toks) { char *s; s = *ps; while(s < es && strchr(whitespace, *s)) 613: 39 de cmp %ebx,%esi 615: 74 18 je 62f <peek+0x3f> 617: 0f be 03 movsbl (%ebx),%eax 61a: 83 ec 08 sub $0x8,%esp 61d: 50 push %eax 61e: 68 58 18 00 00 push $0x1858 623: e8 88 05 00 00 call bb0 <strchr> 628: 83 c4 10 add $0x10,%esp 62b: 85 c0 test %eax,%eax 62d: 75 e1 jne 610 <peek+0x20> s++; *ps = s; 62f: 89 1f mov %ebx,(%edi) return *s && strchr(toks, *s); 631: 0f be 13 movsbl (%ebx),%edx 634: 31 c0 xor %eax,%eax 636: 84 d2 test %dl,%dl 638: 74 17 je 651 <peek+0x61> 63a: 83 ec 08 sub $0x8,%esp 63d: 52 push %edx 63e: ff 75 10 pushl 0x10(%ebp) 641: e8 6a 05 00 00 call bb0 <strchr> 646: 83 c4 10 add $0x10,%esp 649: 85 c0 test %eax,%eax 64b: 0f 95 c0 setne %al 64e: 0f b6 c0 movzbl %al,%eax } 651: 8d 65 f4 lea -0xc(%ebp),%esp 654: 5b pop %ebx 655: 5e pop %esi 656: 5f pop %edi 657: 5d pop %ebp 658: c3 ret 659: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000660 <parseredirs>: return cmd; } struct cmd* parseredirs(struct cmd *cmd, char **ps, char *es) { 660: 55 push %ebp 661: 89 e5 mov %esp,%ebp 663: 57 push %edi 664: 56 push %esi 665: 53 push %ebx 666: 83 ec 1c sub $0x1c,%esp 669: 8b 75 0c mov 0xc(%ebp),%esi 66c: 8b 5d 10 mov 0x10(%ebp),%ebx 66f: 90 nop int tok; char *q, *eq; while(peek(ps, es, "<>")){ 670: 83 ec 04 sub $0x4,%esp 673: 68 01 12 00 00 push $0x1201 678: 53 push %ebx 679: 56 push %esi 67a: e8 71 ff ff ff call 5f0 <peek> 67f: 83 c4 10 add $0x10,%esp 682: 85 c0 test %eax,%eax 684: 74 6a je 6f0 <parseredirs+0x90> tok = gettoken(ps, es, 0, 0); 686: 6a 00 push $0x0 688: 6a 00 push $0x0 68a: 53 push %ebx 68b: 56 push %esi 68c: e8 ef fd ff ff call 480 <gettoken> 691: 89 c7 mov %eax,%edi if(gettoken(ps, es, &q, &eq) != 'a') 693: 8d 45 e4 lea -0x1c(%ebp),%eax 696: 50 push %eax 697: 8d 45 e0 lea -0x20(%ebp),%eax 69a: 50 push %eax 69b: 53 push %ebx 69c: 56 push %esi 69d: e8 de fd ff ff call 480 <gettoken> 6a2: 83 c4 20 add $0x20,%esp 6a5: 83 f8 61 cmp $0x61,%eax 6a8: 75 51 jne 6fb <parseredirs+0x9b> panic("missing file for redirection"); switch(tok){ 6aa: 83 ff 3c cmp $0x3c,%edi 6ad: 74 31 je 6e0 <parseredirs+0x80> 6af: 83 ff 3e cmp $0x3e,%edi 6b2: 74 05 je 6b9 <parseredirs+0x59> 6b4: 83 ff 2b cmp $0x2b,%edi 6b7: 75 b7 jne 670 <parseredirs+0x10> break; case '>': cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); break; case '+': // >> cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); 6b9: 83 ec 0c sub $0xc,%esp 6bc: 6a 01 push $0x1 6be: 68 01 02 00 00 push $0x201 6c3: ff 75 e4 pushl -0x1c(%ebp) 6c6: ff 75 e0 pushl -0x20(%ebp) 6c9: ff 75 08 pushl 0x8(%ebp) 6cc: e8 af fc ff ff call 380 <redircmd> break; 6d1: 83 c4 20 add $0x20,%esp break; case '>': cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); break; case '+': // >> cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); 6d4: 89 45 08 mov %eax,0x8(%ebp) break; 6d7: eb 97 jmp 670 <parseredirs+0x10> 6d9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi tok = gettoken(ps, es, 0, 0); if(gettoken(ps, es, &q, &eq) != 'a') panic("missing file for redirection"); switch(tok){ case '<': cmd = redircmd(cmd, q, eq, O_RDONLY, 0); 6e0: 83 ec 0c sub $0xc,%esp 6e3: 6a 00 push $0x0 6e5: 6a 00 push $0x0 6e7: eb da jmp 6c3 <parseredirs+0x63> 6e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); break; } } return cmd; } 6f0: 8b 45 08 mov 0x8(%ebp),%eax 6f3: 8d 65 f4 lea -0xc(%ebp),%esp 6f6: 5b pop %ebx 6f7: 5e pop %esi 6f8: 5f pop %edi 6f9: 5d pop %ebp 6fa: c3 ret char *q, *eq; while(peek(ps, es, "<>")){ tok = gettoken(ps, es, 0, 0); if(gettoken(ps, es, &q, &eq) != 'a') panic("missing file for redirection"); 6fb: 83 ec 0c sub $0xc,%esp 6fe: 68 e4 11 00 00 push $0x11e4 703: e8 58 fa ff ff call 160 <panic> 708: 90 nop 709: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000710 <parseexec>: return cmd; } struct cmd* parseexec(char **ps, char *es) { 710: 55 push %ebp 711: 89 e5 mov %esp,%ebp 713: 57 push %edi 714: 56 push %esi 715: 53 push %ebx 716: 83 ec 30 sub $0x30,%esp 719: 8b 75 08 mov 0x8(%ebp),%esi 71c: 8b 7d 0c mov 0xc(%ebp),%edi char *q, *eq; int tok, argc; struct execcmd *cmd; struct cmd *ret; if(peek(ps, es, "(")) 71f: 68 04 12 00 00 push $0x1204 724: 57 push %edi 725: 56 push %esi 726: e8 c5 fe ff ff call 5f0 <peek> 72b: 83 c4 10 add $0x10,%esp 72e: 85 c0 test %eax,%eax 730: 0f 85 9a 00 00 00 jne 7d0 <parseexec+0xc0> return parseblock(ps, es); ret = execcmd(); 736: e8 15 fc ff ff call 350 <execcmd> cmd = (struct execcmd*)ret; argc = 0; ret = parseredirs(ret, ps, es); 73b: 83 ec 04 sub $0x4,%esp struct cmd *ret; if(peek(ps, es, "(")) return parseblock(ps, es); ret = execcmd(); 73e: 89 c3 mov %eax,%ebx 740: 89 45 cc mov %eax,-0x34(%ebp) cmd = (struct execcmd*)ret; argc = 0; ret = parseredirs(ret, ps, es); 743: 57 push %edi 744: 56 push %esi 745: 8d 5b 04 lea 0x4(%ebx),%ebx 748: 50 push %eax 749: e8 12 ff ff ff call 660 <parseredirs> 74e: 83 c4 10 add $0x10,%esp 751: 89 45 d0 mov %eax,-0x30(%ebp) return parseblock(ps, es); ret = execcmd(); cmd = (struct execcmd*)ret; argc = 0; 754: c7 45 d4 00 00 00 00 movl $0x0,-0x2c(%ebp) 75b: eb 16 jmp 773 <parseexec+0x63> 75d: 8d 76 00 lea 0x0(%esi),%esi cmd->argv[argc] = q; cmd->eargv[argc] = eq; argc++; if(argc >= MAXARGS) panic("too many args"); ret = parseredirs(ret, ps, es); 760: 83 ec 04 sub $0x4,%esp 763: 57 push %edi 764: 56 push %esi 765: ff 75 d0 pushl -0x30(%ebp) 768: e8 f3 fe ff ff call 660 <parseredirs> 76d: 83 c4 10 add $0x10,%esp 770: 89 45 d0 mov %eax,-0x30(%ebp) ret = execcmd(); cmd = (struct execcmd*)ret; argc = 0; ret = parseredirs(ret, ps, es); while(!peek(ps, es, "|)&;")){ 773: 83 ec 04 sub $0x4,%esp 776: 68 1b 12 00 00 push $0x121b 77b: 57 push %edi 77c: 56 push %esi 77d: e8 6e fe ff ff call 5f0 <peek> 782: 83 c4 10 add $0x10,%esp 785: 85 c0 test %eax,%eax 787: 75 5f jne 7e8 <parseexec+0xd8> if((tok=gettoken(ps, es, &q, &eq)) == 0) 789: 8d 45 e4 lea -0x1c(%ebp),%eax 78c: 50 push %eax 78d: 8d 45 e0 lea -0x20(%ebp),%eax 790: 50 push %eax 791: 57 push %edi 792: 56 push %esi 793: e8 e8 fc ff ff call 480 <gettoken> 798: 83 c4 10 add $0x10,%esp 79b: 85 c0 test %eax,%eax 79d: 74 49 je 7e8 <parseexec+0xd8> break; if(tok != 'a') 79f: 83 f8 61 cmp $0x61,%eax 7a2: 75 66 jne 80a <parseexec+0xfa> panic("syntax"); cmd->argv[argc] = q; 7a4: 8b 45 e0 mov -0x20(%ebp),%eax cmd->eargv[argc] = eq; argc++; 7a7: 83 45 d4 01 addl $0x1,-0x2c(%ebp) 7ab: 83 c3 04 add $0x4,%ebx while(!peek(ps, es, "|)&;")){ if((tok=gettoken(ps, es, &q, &eq)) == 0) break; if(tok != 'a') panic("syntax"); cmd->argv[argc] = q; 7ae: 89 43 fc mov %eax,-0x4(%ebx) cmd->eargv[argc] = eq; 7b1: 8b 45 e4 mov -0x1c(%ebp),%eax 7b4: 89 43 24 mov %eax,0x24(%ebx) argc++; 7b7: 8b 45 d4 mov -0x2c(%ebp),%eax if(argc >= MAXARGS) 7ba: 83 f8 0a cmp $0xa,%eax 7bd: 75 a1 jne 760 <parseexec+0x50> panic("too many args"); 7bf: 83 ec 0c sub $0xc,%esp 7c2: 68 0d 12 00 00 push $0x120d 7c7: e8 94 f9 ff ff call 160 <panic> 7cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi int tok, argc; struct execcmd *cmd; struct cmd *ret; if(peek(ps, es, "(")) return parseblock(ps, es); 7d0: 83 ec 08 sub $0x8,%esp 7d3: 57 push %edi 7d4: 56 push %esi 7d5: e8 56 01 00 00 call 930 <parseblock> 7da: 83 c4 10 add $0x10,%esp ret = parseredirs(ret, ps, es); } cmd->argv[argc] = 0; cmd->eargv[argc] = 0; return ret; } 7dd: 8d 65 f4 lea -0xc(%ebp),%esp 7e0: 5b pop %ebx 7e1: 5e pop %esi 7e2: 5f pop %edi 7e3: 5d pop %ebp 7e4: c3 ret 7e5: 8d 76 00 lea 0x0(%esi),%esi 7e8: 8b 45 cc mov -0x34(%ebp),%eax 7eb: 8b 55 d4 mov -0x2c(%ebp),%edx 7ee: 8d 04 90 lea (%eax,%edx,4),%eax argc++; if(argc >= MAXARGS) panic("too many args"); ret = parseredirs(ret, ps, es); } cmd->argv[argc] = 0; 7f1: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax) cmd->eargv[argc] = 0; 7f8: c7 40 2c 00 00 00 00 movl $0x0,0x2c(%eax) 7ff: 8b 45 d0 mov -0x30(%ebp),%eax return ret; } 802: 8d 65 f4 lea -0xc(%ebp),%esp 805: 5b pop %ebx 806: 5e pop %esi 807: 5f pop %edi 808: 5d pop %ebp 809: c3 ret ret = parseredirs(ret, ps, es); while(!peek(ps, es, "|)&;")){ if((tok=gettoken(ps, es, &q, &eq)) == 0) break; if(tok != 'a') panic("syntax"); 80a: 83 ec 0c sub $0xc,%esp 80d: 68 06 12 00 00 push $0x1206 812: e8 49 f9 ff ff call 160 <panic> 817: 89 f6 mov %esi,%esi 819: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000820 <parsepipe>: return cmd; } struct cmd* parsepipe(char **ps, char *es) { 820: 55 push %ebp 821: 89 e5 mov %esp,%ebp 823: 57 push %edi 824: 56 push %esi 825: 53 push %ebx 826: 83 ec 14 sub $0x14,%esp 829: 8b 5d 08 mov 0x8(%ebp),%ebx 82c: 8b 75 0c mov 0xc(%ebp),%esi struct cmd *cmd; cmd = parseexec(ps, es); 82f: 56 push %esi 830: 53 push %ebx 831: e8 da fe ff ff call 710 <parseexec> if(peek(ps, es, "|")){ 836: 83 c4 0c add $0xc,%esp struct cmd* parsepipe(char **ps, char *es) { struct cmd *cmd; cmd = parseexec(ps, es); 839: 89 c7 mov %eax,%edi if(peek(ps, es, "|")){ 83b: 68 20 12 00 00 push $0x1220 840: 56 push %esi 841: 53 push %ebx 842: e8 a9 fd ff ff call 5f0 <peek> 847: 83 c4 10 add $0x10,%esp 84a: 85 c0 test %eax,%eax 84c: 75 12 jne 860 <parsepipe+0x40> gettoken(ps, es, 0, 0); cmd = pipecmd(cmd, parsepipe(ps, es)); } return cmd; } 84e: 8d 65 f4 lea -0xc(%ebp),%esp 851: 89 f8 mov %edi,%eax 853: 5b pop %ebx 854: 5e pop %esi 855: 5f pop %edi 856: 5d pop %ebp 857: c3 ret 858: 90 nop 859: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi { struct cmd *cmd; cmd = parseexec(ps, es); if(peek(ps, es, "|")){ gettoken(ps, es, 0, 0); 860: 6a 00 push $0x0 862: 6a 00 push $0x0 864: 56 push %esi 865: 53 push %ebx 866: e8 15 fc ff ff call 480 <gettoken> cmd = pipecmd(cmd, parsepipe(ps, es)); 86b: 58 pop %eax 86c: 5a pop %edx 86d: 56 push %esi 86e: 53 push %ebx 86f: e8 ac ff ff ff call 820 <parsepipe> 874: 89 7d 08 mov %edi,0x8(%ebp) 877: 89 45 0c mov %eax,0xc(%ebp) 87a: 83 c4 10 add $0x10,%esp } return cmd; } 87d: 8d 65 f4 lea -0xc(%ebp),%esp 880: 5b pop %ebx 881: 5e pop %esi 882: 5f pop %edi 883: 5d pop %ebp struct cmd *cmd; cmd = parseexec(ps, es); if(peek(ps, es, "|")){ gettoken(ps, es, 0, 0); cmd = pipecmd(cmd, parsepipe(ps, es)); 884: e9 47 fb ff ff jmp 3d0 <pipecmd> 889: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000890 <parseline>: return cmd; } struct cmd* parseline(char **ps, char *es) { 890: 55 push %ebp 891: 89 e5 mov %esp,%ebp 893: 57 push %edi 894: 56 push %esi 895: 53 push %ebx 896: 83 ec 14 sub $0x14,%esp 899: 8b 5d 08 mov 0x8(%ebp),%ebx 89c: 8b 75 0c mov 0xc(%ebp),%esi struct cmd *cmd; cmd = parsepipe(ps, es); 89f: 56 push %esi 8a0: 53 push %ebx 8a1: e8 7a ff ff ff call 820 <parsepipe> while(peek(ps, es, "&")){ 8a6: 83 c4 10 add $0x10,%esp struct cmd* parseline(char **ps, char *es) { struct cmd *cmd; cmd = parsepipe(ps, es); 8a9: 89 c7 mov %eax,%edi while(peek(ps, es, "&")){ 8ab: eb 1b jmp 8c8 <parseline+0x38> 8ad: 8d 76 00 lea 0x0(%esi),%esi gettoken(ps, es, 0, 0); 8b0: 6a 00 push $0x0 8b2: 6a 00 push $0x0 8b4: 56 push %esi 8b5: 53 push %ebx 8b6: e8 c5 fb ff ff call 480 <gettoken> cmd = backcmd(cmd); 8bb: 89 3c 24 mov %edi,(%esp) 8be: e8 8d fb ff ff call 450 <backcmd> 8c3: 83 c4 10 add $0x10,%esp 8c6: 89 c7 mov %eax,%edi parseline(char **ps, char *es) { struct cmd *cmd; cmd = parsepipe(ps, es); while(peek(ps, es, "&")){ 8c8: 83 ec 04 sub $0x4,%esp 8cb: 68 22 12 00 00 push $0x1222 8d0: 56 push %esi 8d1: 53 push %ebx 8d2: e8 19 fd ff ff call 5f0 <peek> 8d7: 83 c4 10 add $0x10,%esp 8da: 85 c0 test %eax,%eax 8dc: 75 d2 jne 8b0 <parseline+0x20> gettoken(ps, es, 0, 0); cmd = backcmd(cmd); } if(peek(ps, es, ";")){ 8de: 83 ec 04 sub $0x4,%esp 8e1: 68 1e 12 00 00 push $0x121e 8e6: 56 push %esi 8e7: 53 push %ebx 8e8: e8 03 fd ff ff call 5f0 <peek> 8ed: 83 c4 10 add $0x10,%esp 8f0: 85 c0 test %eax,%eax 8f2: 75 0c jne 900 <parseline+0x70> gettoken(ps, es, 0, 0); cmd = listcmd(cmd, parseline(ps, es)); } return cmd; } 8f4: 8d 65 f4 lea -0xc(%ebp),%esp 8f7: 89 f8 mov %edi,%eax 8f9: 5b pop %ebx 8fa: 5e pop %esi 8fb: 5f pop %edi 8fc: 5d pop %ebp 8fd: c3 ret 8fe: 66 90 xchg %ax,%ax while(peek(ps, es, "&")){ gettoken(ps, es, 0, 0); cmd = backcmd(cmd); } if(peek(ps, es, ";")){ gettoken(ps, es, 0, 0); 900: 6a 00 push $0x0 902: 6a 00 push $0x0 904: 56 push %esi 905: 53 push %ebx 906: e8 75 fb ff ff call 480 <gettoken> cmd = listcmd(cmd, parseline(ps, es)); 90b: 58 pop %eax 90c: 5a pop %edx 90d: 56 push %esi 90e: 53 push %ebx 90f: e8 7c ff ff ff call 890 <parseline> 914: 89 7d 08 mov %edi,0x8(%ebp) 917: 89 45 0c mov %eax,0xc(%ebp) 91a: 83 c4 10 add $0x10,%esp } return cmd; } 91d: 8d 65 f4 lea -0xc(%ebp),%esp 920: 5b pop %ebx 921: 5e pop %esi 922: 5f pop %edi 923: 5d pop %ebp gettoken(ps, es, 0, 0); cmd = backcmd(cmd); } if(peek(ps, es, ";")){ gettoken(ps, es, 0, 0); cmd = listcmd(cmd, parseline(ps, es)); 924: e9 e7 fa ff ff jmp 410 <listcmd> 929: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000930 <parseblock>: return cmd; } struct cmd* parseblock(char **ps, char *es) { 930: 55 push %ebp 931: 89 e5 mov %esp,%ebp 933: 57 push %edi 934: 56 push %esi 935: 53 push %ebx 936: 83 ec 10 sub $0x10,%esp 939: 8b 5d 08 mov 0x8(%ebp),%ebx 93c: 8b 75 0c mov 0xc(%ebp),%esi struct cmd *cmd; if(!peek(ps, es, "(")) 93f: 68 04 12 00 00 push $0x1204 944: 56 push %esi 945: 53 push %ebx 946: e8 a5 fc ff ff call 5f0 <peek> 94b: 83 c4 10 add $0x10,%esp 94e: 85 c0 test %eax,%eax 950: 74 4a je 99c <parseblock+0x6c> panic("parseblock"); gettoken(ps, es, 0, 0); 952: 6a 00 push $0x0 954: 6a 00 push $0x0 956: 56 push %esi 957: 53 push %ebx 958: e8 23 fb ff ff call 480 <gettoken> cmd = parseline(ps, es); 95d: 58 pop %eax 95e: 5a pop %edx 95f: 56 push %esi 960: 53 push %ebx 961: e8 2a ff ff ff call 890 <parseline> if(!peek(ps, es, ")")) 966: 83 c4 0c add $0xc,%esp struct cmd *cmd; if(!peek(ps, es, "(")) panic("parseblock"); gettoken(ps, es, 0, 0); cmd = parseline(ps, es); 969: 89 c7 mov %eax,%edi if(!peek(ps, es, ")")) 96b: 68 40 12 00 00 push $0x1240 970: 56 push %esi 971: 53 push %ebx 972: e8 79 fc ff ff call 5f0 <peek> 977: 83 c4 10 add $0x10,%esp 97a: 85 c0 test %eax,%eax 97c: 74 2b je 9a9 <parseblock+0x79> panic("syntax - missing )"); gettoken(ps, es, 0, 0); 97e: 6a 00 push $0x0 980: 6a 00 push $0x0 982: 56 push %esi 983: 53 push %ebx 984: e8 f7 fa ff ff call 480 <gettoken> cmd = parseredirs(cmd, ps, es); 989: 83 c4 0c add $0xc,%esp 98c: 56 push %esi 98d: 53 push %ebx 98e: 57 push %edi 98f: e8 cc fc ff ff call 660 <parseredirs> return cmd; } 994: 8d 65 f4 lea -0xc(%ebp),%esp 997: 5b pop %ebx 998: 5e pop %esi 999: 5f pop %edi 99a: 5d pop %ebp 99b: c3 ret parseblock(char **ps, char *es) { struct cmd *cmd; if(!peek(ps, es, "(")) panic("parseblock"); 99c: 83 ec 0c sub $0xc,%esp 99f: 68 24 12 00 00 push $0x1224 9a4: e8 b7 f7 ff ff call 160 <panic> gettoken(ps, es, 0, 0); cmd = parseline(ps, es); if(!peek(ps, es, ")")) panic("syntax - missing )"); 9a9: 83 ec 0c sub $0xc,%esp 9ac: 68 2f 12 00 00 push $0x122f 9b1: e8 aa f7 ff ff call 160 <panic> 9b6: 8d 76 00 lea 0x0(%esi),%esi 9b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000009c0 <nulterminate>: } // NUL-terminate all the counted strings. struct cmd* nulterminate(struct cmd *cmd) { 9c0: 55 push %ebp 9c1: 89 e5 mov %esp,%ebp 9c3: 53 push %ebx 9c4: 83 ec 04 sub $0x4,%esp 9c7: 8b 5d 08 mov 0x8(%ebp),%ebx struct execcmd *ecmd; struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) 9ca: 85 db test %ebx,%ebx 9cc: 0f 84 96 00 00 00 je a68 <nulterminate+0xa8> return 0; switch(cmd->type){ 9d2: 83 3b 05 cmpl $0x5,(%ebx) 9d5: 77 48 ja a1f <nulterminate+0x5f> 9d7: 8b 03 mov (%ebx),%eax 9d9: ff 24 85 80 12 00 00 jmp *0x1280(,%eax,4) nulterminate(pcmd->right); break; case LIST: lcmd = (struct listcmd*)cmd; nulterminate(lcmd->left); 9e0: 83 ec 0c sub $0xc,%esp 9e3: ff 73 04 pushl 0x4(%ebx) 9e6: e8 d5 ff ff ff call 9c0 <nulterminate> nulterminate(lcmd->right); 9eb: 58 pop %eax 9ec: ff 73 08 pushl 0x8(%ebx) 9ef: e8 cc ff ff ff call 9c0 <nulterminate> break; 9f4: 83 c4 10 add $0x10,%esp 9f7: 89 d8 mov %ebx,%eax bcmd = (struct backcmd*)cmd; nulterminate(bcmd->cmd); break; } return cmd; } 9f9: 8b 5d fc mov -0x4(%ebp),%ebx 9fc: c9 leave 9fd: c3 ret 9fe: 66 90 xchg %ax,%ax return 0; switch(cmd->type){ case EXEC: ecmd = (struct execcmd*)cmd; for(i=0; ecmd->argv[i]; i++) a00: 8b 4b 04 mov 0x4(%ebx),%ecx a03: 8d 43 2c lea 0x2c(%ebx),%eax a06: 85 c9 test %ecx,%ecx a08: 74 15 je a1f <nulterminate+0x5f> a0a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi *ecmd->eargv[i] = 0; a10: 8b 10 mov (%eax),%edx a12: 83 c0 04 add $0x4,%eax a15: c6 02 00 movb $0x0,(%edx) return 0; switch(cmd->type){ case EXEC: ecmd = (struct execcmd*)cmd; for(i=0; ecmd->argv[i]; i++) a18: 8b 50 d8 mov -0x28(%eax),%edx a1b: 85 d2 test %edx,%edx a1d: 75 f1 jne a10 <nulterminate+0x50> struct redircmd *rcmd; if(cmd == 0) return 0; switch(cmd->type){ a1f: 89 d8 mov %ebx,%eax bcmd = (struct backcmd*)cmd; nulterminate(bcmd->cmd); break; } return cmd; } a21: 8b 5d fc mov -0x4(%ebp),%ebx a24: c9 leave a25: c3 ret a26: 8d 76 00 lea 0x0(%esi),%esi a29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi nulterminate(lcmd->right); break; case BACK: bcmd = (struct backcmd*)cmd; nulterminate(bcmd->cmd); a30: 83 ec 0c sub $0xc,%esp a33: ff 73 04 pushl 0x4(%ebx) a36: e8 85 ff ff ff call 9c0 <nulterminate> break; a3b: 89 d8 mov %ebx,%eax a3d: 83 c4 10 add $0x10,%esp } return cmd; } a40: 8b 5d fc mov -0x4(%ebp),%ebx a43: c9 leave a44: c3 ret a45: 8d 76 00 lea 0x0(%esi),%esi *ecmd->eargv[i] = 0; break; case REDIR: rcmd = (struct redircmd*)cmd; nulterminate(rcmd->cmd); a48: 83 ec 0c sub $0xc,%esp a4b: ff 73 04 pushl 0x4(%ebx) a4e: e8 6d ff ff ff call 9c0 <nulterminate> *rcmd->efile = 0; a53: 8b 43 0c mov 0xc(%ebx),%eax break; a56: 83 c4 10 add $0x10,%esp break; case REDIR: rcmd = (struct redircmd*)cmd; nulterminate(rcmd->cmd); *rcmd->efile = 0; a59: c6 00 00 movb $0x0,(%eax) break; a5c: 89 d8 mov %ebx,%eax bcmd = (struct backcmd*)cmd; nulterminate(bcmd->cmd); break; } return cmd; } a5e: 8b 5d fc mov -0x4(%ebp),%ebx a61: c9 leave a62: c3 ret a63: 90 nop a64: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) return 0; a68: 31 c0 xor %eax,%eax a6a: eb 8d jmp 9f9 <nulterminate+0x39> a6c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000a70 <parsecmd>: struct cmd *parseexec(char**, char*); struct cmd *nulterminate(struct cmd*); struct cmd* parsecmd(char *s) { a70: 55 push %ebp a71: 89 e5 mov %esp,%ebp a73: 56 push %esi a74: 53 push %ebx char *es; struct cmd *cmd; es = s + strlen(s); a75: 8b 5d 08 mov 0x8(%ebp),%ebx a78: 83 ec 0c sub $0xc,%esp a7b: 53 push %ebx a7c: e8 df 00 00 00 call b60 <strlen> cmd = parseline(&s, es); a81: 59 pop %ecx parsecmd(char *s) { char *es; struct cmd *cmd; es = s + strlen(s); a82: 01 c3 add %eax,%ebx cmd = parseline(&s, es); a84: 8d 45 08 lea 0x8(%ebp),%eax a87: 5e pop %esi a88: 53 push %ebx a89: 50 push %eax a8a: e8 01 fe ff ff call 890 <parseline> a8f: 89 c6 mov %eax,%esi peek(&s, es, ""); a91: 8d 45 08 lea 0x8(%ebp),%eax a94: 83 c4 0c add $0xc,%esp a97: 68 c9 11 00 00 push $0x11c9 a9c: 53 push %ebx a9d: 50 push %eax a9e: e8 4d fb ff ff call 5f0 <peek> if(s != es){ aa3: 8b 45 08 mov 0x8(%ebp),%eax aa6: 83 c4 10 add $0x10,%esp aa9: 39 c3 cmp %eax,%ebx aab: 75 12 jne abf <parsecmd+0x4f> printf(2, "leftovers: %s\n", s); panic("syntax"); } nulterminate(cmd); aad: 83 ec 0c sub $0xc,%esp ab0: 56 push %esi ab1: e8 0a ff ff ff call 9c0 <nulterminate> return cmd; } ab6: 8d 65 f8 lea -0x8(%ebp),%esp ab9: 89 f0 mov %esi,%eax abb: 5b pop %ebx abc: 5e pop %esi abd: 5d pop %ebp abe: c3 ret es = s + strlen(s); cmd = parseline(&s, es); peek(&s, es, ""); if(s != es){ printf(2, "leftovers: %s\n", s); abf: 52 push %edx ac0: 50 push %eax ac1: 68 42 12 00 00 push $0x1242 ac6: 6a 02 push $0x2 ac8: e8 c3 03 00 00 call e90 <printf> panic("syntax"); acd: c7 04 24 06 12 00 00 movl $0x1206,(%esp) ad4: e8 87 f6 ff ff call 160 <panic> ad9: 66 90 xchg %ax,%ax adb: 66 90 xchg %ax,%ax add: 66 90 xchg %ax,%ax adf: 90 nop 00000ae0 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { ae0: 55 push %ebp ae1: 89 e5 mov %esp,%ebp ae3: 53 push %ebx ae4: 8b 45 08 mov 0x8(%ebp),%eax ae7: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) aea: 89 c2 mov %eax,%edx aec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi af0: 83 c1 01 add $0x1,%ecx af3: 0f b6 59 ff movzbl -0x1(%ecx),%ebx af7: 83 c2 01 add $0x1,%edx afa: 84 db test %bl,%bl afc: 88 5a ff mov %bl,-0x1(%edx) aff: 75 ef jne af0 <strcpy+0x10> ; return os; } b01: 5b pop %ebx b02: 5d pop %ebp b03: c3 ret b04: 8d b6 00 00 00 00 lea 0x0(%esi),%esi b0a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000b10 <strcmp>: int strcmp(const char *p, const char *q) { b10: 55 push %ebp b11: 89 e5 mov %esp,%ebp b13: 56 push %esi b14: 53 push %ebx b15: 8b 55 08 mov 0x8(%ebp),%edx b18: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) b1b: 0f b6 02 movzbl (%edx),%eax b1e: 0f b6 19 movzbl (%ecx),%ebx b21: 84 c0 test %al,%al b23: 75 1e jne b43 <strcmp+0x33> b25: eb 29 jmp b50 <strcmp+0x40> b27: 89 f6 mov %esi,%esi b29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; b30: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) b33: 0f b6 02 movzbl (%edx),%eax p++, q++; b36: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) b39: 0f b6 59 01 movzbl 0x1(%ecx),%ebx b3d: 84 c0 test %al,%al b3f: 74 0f je b50 <strcmp+0x40> b41: 89 f1 mov %esi,%ecx b43: 38 d8 cmp %bl,%al b45: 74 e9 je b30 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; b47: 29 d8 sub %ebx,%eax } b49: 5b pop %ebx b4a: 5e pop %esi b4b: 5d pop %ebp b4c: c3 ret b4d: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) b50: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; b52: 29 d8 sub %ebx,%eax } b54: 5b pop %ebx b55: 5e pop %esi b56: 5d pop %ebp b57: c3 ret b58: 90 nop b59: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000b60 <strlen>: uint strlen(char *s) { b60: 55 push %ebp b61: 89 e5 mov %esp,%ebp b63: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) b66: 80 39 00 cmpb $0x0,(%ecx) b69: 74 12 je b7d <strlen+0x1d> b6b: 31 d2 xor %edx,%edx b6d: 8d 76 00 lea 0x0(%esi),%esi b70: 83 c2 01 add $0x1,%edx b73: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) b77: 89 d0 mov %edx,%eax b79: 75 f5 jne b70 <strlen+0x10> ; return n; } b7b: 5d pop %ebp b7c: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) b7d: 31 c0 xor %eax,%eax ; return n; } b7f: 5d pop %ebp b80: c3 ret b81: eb 0d jmp b90 <memset> b83: 90 nop b84: 90 nop b85: 90 nop b86: 90 nop b87: 90 nop b88: 90 nop b89: 90 nop b8a: 90 nop b8b: 90 nop b8c: 90 nop b8d: 90 nop b8e: 90 nop b8f: 90 nop 00000b90 <memset>: void* memset(void *dst, int c, uint n) { b90: 55 push %ebp b91: 89 e5 mov %esp,%ebp b93: 57 push %edi b94: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : b97: 8b 4d 10 mov 0x10(%ebp),%ecx b9a: 8b 45 0c mov 0xc(%ebp),%eax b9d: 89 d7 mov %edx,%edi b9f: fc cld ba0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } ba2: 89 d0 mov %edx,%eax ba4: 5f pop %edi ba5: 5d pop %ebp ba6: c3 ret ba7: 89 f6 mov %esi,%esi ba9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000bb0 <strchr>: char* strchr(const char *s, char c) { bb0: 55 push %ebp bb1: 89 e5 mov %esp,%ebp bb3: 53 push %ebx bb4: 8b 45 08 mov 0x8(%ebp),%eax bb7: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) bba: 0f b6 10 movzbl (%eax),%edx bbd: 84 d2 test %dl,%dl bbf: 74 1d je bde <strchr+0x2e> if(*s == c) bc1: 38 d3 cmp %dl,%bl bc3: 89 d9 mov %ebx,%ecx bc5: 75 0d jne bd4 <strchr+0x24> bc7: eb 17 jmp be0 <strchr+0x30> bc9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi bd0: 38 ca cmp %cl,%dl bd2: 74 0c je be0 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) bd4: 83 c0 01 add $0x1,%eax bd7: 0f b6 10 movzbl (%eax),%edx bda: 84 d2 test %dl,%dl bdc: 75 f2 jne bd0 <strchr+0x20> if(*s == c) return (char*)s; return 0; bde: 31 c0 xor %eax,%eax } be0: 5b pop %ebx be1: 5d pop %ebp be2: c3 ret be3: 8d b6 00 00 00 00 lea 0x0(%esi),%esi be9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000bf0 <gets>: char* gets(char *buf, int max) { bf0: 55 push %ebp bf1: 89 e5 mov %esp,%ebp bf3: 57 push %edi bf4: 56 push %esi bf5: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ bf6: 31 f6 xor %esi,%esi cc = read(0, &c, 1); bf8: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { bfb: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ bfe: eb 29 jmp c29 <gets+0x39> cc = read(0, &c, 1); c00: 83 ec 04 sub $0x4,%esp c03: 6a 01 push $0x1 c05: 57 push %edi c06: 6a 00 push $0x0 c08: e8 2d 01 00 00 call d3a <read> if(cc < 1) c0d: 83 c4 10 add $0x10,%esp c10: 85 c0 test %eax,%eax c12: 7e 1d jle c31 <gets+0x41> break; buf[i++] = c; c14: 0f b6 45 e7 movzbl -0x19(%ebp),%eax c18: 8b 55 08 mov 0x8(%ebp),%edx c1b: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') c1d: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; c1f: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') c23: 74 1b je c40 <gets+0x50> c25: 3c 0d cmp $0xd,%al c27: 74 17 je c40 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ c29: 8d 5e 01 lea 0x1(%esi),%ebx c2c: 3b 5d 0c cmp 0xc(%ebp),%ebx c2f: 7c cf jl c00 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; c31: 8b 45 08 mov 0x8(%ebp),%eax c34: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } c38: 8d 65 f4 lea -0xc(%ebp),%esp c3b: 5b pop %ebx c3c: 5e pop %esi c3d: 5f pop %edi c3e: 5d pop %ebp c3f: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; c40: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ c43: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; c45: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } c49: 8d 65 f4 lea -0xc(%ebp),%esp c4c: 5b pop %ebx c4d: 5e pop %esi c4e: 5f pop %edi c4f: 5d pop %ebp c50: c3 ret c51: eb 0d jmp c60 <stat> c53: 90 nop c54: 90 nop c55: 90 nop c56: 90 nop c57: 90 nop c58: 90 nop c59: 90 nop c5a: 90 nop c5b: 90 nop c5c: 90 nop c5d: 90 nop c5e: 90 nop c5f: 90 nop 00000c60 <stat>: int stat(char *n, struct stat *st) { c60: 55 push %ebp c61: 89 e5 mov %esp,%ebp c63: 56 push %esi c64: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); c65: 83 ec 08 sub $0x8,%esp c68: 6a 00 push $0x0 c6a: ff 75 08 pushl 0x8(%ebp) c6d: e8 f0 00 00 00 call d62 <open> if(fd < 0) c72: 83 c4 10 add $0x10,%esp c75: 85 c0 test %eax,%eax c77: 78 27 js ca0 <stat+0x40> return -1; r = fstat(fd, st); c79: 83 ec 08 sub $0x8,%esp c7c: ff 75 0c pushl 0xc(%ebp) c7f: 89 c3 mov %eax,%ebx c81: 50 push %eax c82: e8 f3 00 00 00 call d7a <fstat> c87: 89 c6 mov %eax,%esi close(fd); c89: 89 1c 24 mov %ebx,(%esp) c8c: e8 b9 00 00 00 call d4a <close> return r; c91: 83 c4 10 add $0x10,%esp c94: 89 f0 mov %esi,%eax } c96: 8d 65 f8 lea -0x8(%ebp),%esp c99: 5b pop %ebx c9a: 5e pop %esi c9b: 5d pop %ebp c9c: c3 ret c9d: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; ca0: b8 ff ff ff ff mov $0xffffffff,%eax ca5: eb ef jmp c96 <stat+0x36> ca7: 89 f6 mov %esi,%esi ca9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000cb0 <atoi>: return r; } int atoi(const char *s) { cb0: 55 push %ebp cb1: 89 e5 mov %esp,%ebp cb3: 53 push %ebx cb4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') cb7: 0f be 11 movsbl (%ecx),%edx cba: 8d 42 d0 lea -0x30(%edx),%eax cbd: 3c 09 cmp $0x9,%al cbf: b8 00 00 00 00 mov $0x0,%eax cc4: 77 1f ja ce5 <atoi+0x35> cc6: 8d 76 00 lea 0x0(%esi),%esi cc9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; cd0: 8d 04 80 lea (%eax,%eax,4),%eax cd3: 83 c1 01 add $0x1,%ecx cd6: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') cda: 0f be 11 movsbl (%ecx),%edx cdd: 8d 5a d0 lea -0x30(%edx),%ebx ce0: 80 fb 09 cmp $0x9,%bl ce3: 76 eb jbe cd0 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } ce5: 5b pop %ebx ce6: 5d pop %ebp ce7: c3 ret ce8: 90 nop ce9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000cf0 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { cf0: 55 push %ebp cf1: 89 e5 mov %esp,%ebp cf3: 56 push %esi cf4: 53 push %ebx cf5: 8b 5d 10 mov 0x10(%ebp),%ebx cf8: 8b 45 08 mov 0x8(%ebp),%eax cfb: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) cfe: 85 db test %ebx,%ebx d00: 7e 14 jle d16 <memmove+0x26> d02: 31 d2 xor %edx,%edx d04: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; d08: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx d0c: 88 0c 10 mov %cl,(%eax,%edx,1) d0f: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) d12: 39 da cmp %ebx,%edx d14: 75 f2 jne d08 <memmove+0x18> *dst++ = *src++; return vdst; } d16: 5b pop %ebx d17: 5e pop %esi d18: 5d pop %ebp d19: c3 ret 00000d1a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) d1a: b8 01 00 00 00 mov $0x1,%eax d1f: cd 40 int $0x40 d21: c3 ret 00000d22 <exit>: SYSCALL(exit) d22: b8 02 00 00 00 mov $0x2,%eax d27: cd 40 int $0x40 d29: c3 ret 00000d2a <wait>: SYSCALL(wait) d2a: b8 03 00 00 00 mov $0x3,%eax d2f: cd 40 int $0x40 d31: c3 ret 00000d32 <pipe>: SYSCALL(pipe) d32: b8 04 00 00 00 mov $0x4,%eax d37: cd 40 int $0x40 d39: c3 ret 00000d3a <read>: SYSCALL(read) d3a: b8 05 00 00 00 mov $0x5,%eax d3f: cd 40 int $0x40 d41: c3 ret 00000d42 <write>: SYSCALL(write) d42: b8 10 00 00 00 mov $0x10,%eax d47: cd 40 int $0x40 d49: c3 ret 00000d4a <close>: SYSCALL(close) d4a: b8 15 00 00 00 mov $0x15,%eax d4f: cd 40 int $0x40 d51: c3 ret 00000d52 <kill>: SYSCALL(kill) d52: b8 06 00 00 00 mov $0x6,%eax d57: cd 40 int $0x40 d59: c3 ret 00000d5a <exec>: SYSCALL(exec) d5a: b8 07 00 00 00 mov $0x7,%eax d5f: cd 40 int $0x40 d61: c3 ret 00000d62 <open>: SYSCALL(open) d62: b8 0f 00 00 00 mov $0xf,%eax d67: cd 40 int $0x40 d69: c3 ret 00000d6a <mknod>: SYSCALL(mknod) d6a: b8 11 00 00 00 mov $0x11,%eax d6f: cd 40 int $0x40 d71: c3 ret 00000d72 <unlink>: SYSCALL(unlink) d72: b8 12 00 00 00 mov $0x12,%eax d77: cd 40 int $0x40 d79: c3 ret 00000d7a <fstat>: SYSCALL(fstat) d7a: b8 08 00 00 00 mov $0x8,%eax d7f: cd 40 int $0x40 d81: c3 ret 00000d82 <link>: SYSCALL(link) d82: b8 13 00 00 00 mov $0x13,%eax d87: cd 40 int $0x40 d89: c3 ret 00000d8a <mkdir>: SYSCALL(mkdir) d8a: b8 14 00 00 00 mov $0x14,%eax d8f: cd 40 int $0x40 d91: c3 ret 00000d92 <chdir>: SYSCALL(chdir) d92: b8 09 00 00 00 mov $0x9,%eax d97: cd 40 int $0x40 d99: c3 ret 00000d9a <dup>: SYSCALL(dup) d9a: b8 0a 00 00 00 mov $0xa,%eax d9f: cd 40 int $0x40 da1: c3 ret 00000da2 <getpid>: SYSCALL(getpid) da2: b8 0b 00 00 00 mov $0xb,%eax da7: cd 40 int $0x40 da9: c3 ret 00000daa <sbrk>: SYSCALL(sbrk) daa: b8 0c 00 00 00 mov $0xc,%eax daf: cd 40 int $0x40 db1: c3 ret 00000db2 <sleep>: SYSCALL(sleep) db2: b8 0d 00 00 00 mov $0xd,%eax db7: cd 40 int $0x40 db9: c3 ret 00000dba <uptime>: SYSCALL(uptime) dba: b8 0e 00 00 00 mov $0xe,%eax dbf: cd 40 int $0x40 dc1: c3 ret 00000dc2 <init_taskmaster>: #/***************** LAB QUIZ 4 *****************/ SYSCALL(init_taskmaster) dc2: b8 16 00 00 00 mov $0x16,%eax dc7: cd 40 int $0x40 dc9: c3 ret 00000dca <do_task>: SYSCALL(do_task) dca: b8 17 00 00 00 mov $0x17,%eax dcf: cd 40 int $0x40 dd1: c3 ret 00000dd2 <wait_for_task_to_complete>: SYSCALL(wait_for_task_to_complete) dd2: b8 18 00 00 00 mov $0x18,%eax dd7: cd 40 int $0x40 dd9: c3 ret 00000dda <wait_for_task>: SYSCALL(wait_for_task) dda: b8 19 00 00 00 mov $0x19,%eax ddf: cd 40 int $0x40 de1: c3 ret 00000de2 <task_ret>: SYSCALL(task_ret) de2: b8 1a 00 00 00 mov $0x1a,%eax de7: cd 40 int $0x40 de9: c3 ret dea: 66 90 xchg %ax,%ax dec: 66 90 xchg %ax,%ax dee: 66 90 xchg %ax,%ax 00000df0 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { df0: 55 push %ebp df1: 89 e5 mov %esp,%ebp df3: 57 push %edi df4: 56 push %esi df5: 53 push %ebx df6: 89 c6 mov %eax,%esi df8: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ dfb: 8b 5d 08 mov 0x8(%ebp),%ebx dfe: 85 db test %ebx,%ebx e00: 74 7e je e80 <printint+0x90> e02: 89 d0 mov %edx,%eax e04: c1 e8 1f shr $0x1f,%eax e07: 84 c0 test %al,%al e09: 74 75 je e80 <printint+0x90> neg = 1; x = -xx; e0b: 89 d0 mov %edx,%eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; e0d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) x = -xx; e14: f7 d8 neg %eax e16: 89 75 c0 mov %esi,-0x40(%ebp) } else { x = xx; } i = 0; e19: 31 ff xor %edi,%edi e1b: 8d 5d d7 lea -0x29(%ebp),%ebx e1e: 89 ce mov %ecx,%esi e20: eb 08 jmp e2a <printint+0x3a> e22: 8d b6 00 00 00 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; e28: 89 cf mov %ecx,%edi e2a: 31 d2 xor %edx,%edx e2c: 8d 4f 01 lea 0x1(%edi),%ecx e2f: f7 f6 div %esi e31: 0f b6 92 a0 12 00 00 movzbl 0x12a0(%edx),%edx }while((x /= base) != 0); e38: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; e3a: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); e3d: 75 e9 jne e28 <printint+0x38> if(neg) e3f: 8b 45 c4 mov -0x3c(%ebp),%eax e42: 8b 75 c0 mov -0x40(%ebp),%esi e45: 85 c0 test %eax,%eax e47: 74 08 je e51 <printint+0x61> buf[i++] = '-'; e49: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1) e4e: 8d 4f 02 lea 0x2(%edi),%ecx e51: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi e55: 8d 76 00 lea 0x0(%esi),%esi e58: 0f b6 07 movzbl (%edi),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); e5b: 83 ec 04 sub $0x4,%esp e5e: 83 ef 01 sub $0x1,%edi e61: 6a 01 push $0x1 e63: 53 push %ebx e64: 56 push %esi e65: 88 45 d7 mov %al,-0x29(%ebp) e68: e8 d5 fe ff ff call d42 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) e6d: 83 c4 10 add $0x10,%esp e70: 39 df cmp %ebx,%edi e72: 75 e4 jne e58 <printint+0x68> putc(fd, buf[i]); } e74: 8d 65 f4 lea -0xc(%ebp),%esp e77: 5b pop %ebx e78: 5e pop %esi e79: 5f pop %edi e7a: 5d pop %ebp e7b: c3 ret e7c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; } else { x = xx; e80: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; e82: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) e89: eb 8b jmp e16 <printint+0x26> e8b: 90 nop e8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000e90 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { e90: 55 push %ebp e91: 89 e5 mov %esp,%ebp e93: 57 push %edi e94: 56 push %esi e95: 53 push %ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ e96: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { e99: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ e9c: 8b 75 0c mov 0xc(%ebp),%esi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { e9f: 8b 7d 08 mov 0x8(%ebp),%edi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ ea2: 89 45 d0 mov %eax,-0x30(%ebp) ea5: 0f b6 1e movzbl (%esi),%ebx ea8: 83 c6 01 add $0x1,%esi eab: 84 db test %bl,%bl ead: 0f 84 b0 00 00 00 je f63 <printf+0xd3> eb3: 31 d2 xor %edx,%edx eb5: eb 39 jmp ef0 <printf+0x60> eb7: 89 f6 mov %esi,%esi eb9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ ec0: 83 f8 25 cmp $0x25,%eax ec3: 89 55 d4 mov %edx,-0x2c(%ebp) state = '%'; ec6: ba 25 00 00 00 mov $0x25,%edx state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ ecb: 74 18 je ee5 <printf+0x55> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); ecd: 8d 45 e2 lea -0x1e(%ebp),%eax ed0: 83 ec 04 sub $0x4,%esp ed3: 88 5d e2 mov %bl,-0x1e(%ebp) ed6: 6a 01 push $0x1 ed8: 50 push %eax ed9: 57 push %edi eda: e8 63 fe ff ff call d42 <write> edf: 8b 55 d4 mov -0x2c(%ebp),%edx ee2: 83 c4 10 add $0x10,%esp ee5: 83 c6 01 add $0x1,%esi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ ee8: 0f b6 5e ff movzbl -0x1(%esi),%ebx eec: 84 db test %bl,%bl eee: 74 73 je f63 <printf+0xd3> c = fmt[i] & 0xff; if(state == 0){ ef0: 85 d2 test %edx,%edx uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; ef2: 0f be cb movsbl %bl,%ecx ef5: 0f b6 c3 movzbl %bl,%eax if(state == 0){ ef8: 74 c6 je ec0 <printf+0x30> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ efa: 83 fa 25 cmp $0x25,%edx efd: 75 e6 jne ee5 <printf+0x55> if(c == 'd'){ eff: 83 f8 64 cmp $0x64,%eax f02: 0f 84 f8 00 00 00 je 1000 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ f08: 81 e1 f7 00 00 00 and $0xf7,%ecx f0e: 83 f9 70 cmp $0x70,%ecx f11: 74 5d je f70 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ f13: 83 f8 73 cmp $0x73,%eax f16: 0f 84 84 00 00 00 je fa0 <printf+0x110> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ f1c: 83 f8 63 cmp $0x63,%eax f1f: 0f 84 ea 00 00 00 je 100f <printf+0x17f> putc(fd, *ap); ap++; } else if(c == '%'){ f25: 83 f8 25 cmp $0x25,%eax f28: 0f 84 c2 00 00 00 je ff0 <printf+0x160> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); f2e: 8d 45 e7 lea -0x19(%ebp),%eax f31: 83 ec 04 sub $0x4,%esp f34: c6 45 e7 25 movb $0x25,-0x19(%ebp) f38: 6a 01 push $0x1 f3a: 50 push %eax f3b: 57 push %edi f3c: e8 01 fe ff ff call d42 <write> f41: 83 c4 0c add $0xc,%esp f44: 8d 45 e6 lea -0x1a(%ebp),%eax f47: 88 5d e6 mov %bl,-0x1a(%ebp) f4a: 6a 01 push $0x1 f4c: 50 push %eax f4d: 57 push %edi f4e: 83 c6 01 add $0x1,%esi f51: e8 ec fd ff ff call d42 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ f56: 0f b6 5e ff movzbl -0x1(%esi),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); f5a: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; f5d: 31 d2 xor %edx,%edx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ f5f: 84 db test %bl,%bl f61: 75 8d jne ef0 <printf+0x60> putc(fd, c); } state = 0; } } } f63: 8d 65 f4 lea -0xc(%ebp),%esp f66: 5b pop %ebx f67: 5e pop %esi f68: 5f pop %edi f69: 5d pop %ebp f6a: c3 ret f6b: 90 nop f6c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); f70: 83 ec 0c sub $0xc,%esp f73: b9 10 00 00 00 mov $0x10,%ecx f78: 6a 00 push $0x0 f7a: 8b 5d d0 mov -0x30(%ebp),%ebx f7d: 89 f8 mov %edi,%eax f7f: 8b 13 mov (%ebx),%edx f81: e8 6a fe ff ff call df0 <printint> ap++; f86: 89 d8 mov %ebx,%eax f88: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; f8b: 31 d2 xor %edx,%edx if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; f8d: 83 c0 04 add $0x4,%eax f90: 89 45 d0 mov %eax,-0x30(%ebp) f93: e9 4d ff ff ff jmp ee5 <printf+0x55> f98: 90 nop f99: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; fa0: 8b 45 d0 mov -0x30(%ebp),%eax fa3: 8b 18 mov (%eax),%ebx ap++; fa5: 83 c0 04 add $0x4,%eax fa8: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) s = "(null)"; fab: b8 98 12 00 00 mov $0x1298,%eax fb0: 85 db test %ebx,%ebx fb2: 0f 44 d8 cmove %eax,%ebx while(*s != 0){ fb5: 0f b6 03 movzbl (%ebx),%eax fb8: 84 c0 test %al,%al fba: 74 23 je fdf <printf+0x14f> fbc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi fc0: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); fc3: 8d 45 e3 lea -0x1d(%ebp),%eax fc6: 83 ec 04 sub $0x4,%esp fc9: 6a 01 push $0x1 ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; fcb: 83 c3 01 add $0x1,%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); fce: 50 push %eax fcf: 57 push %edi fd0: e8 6d fd ff ff call d42 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ fd5: 0f b6 03 movzbl (%ebx),%eax fd8: 83 c4 10 add $0x10,%esp fdb: 84 c0 test %al,%al fdd: 75 e1 jne fc0 <printf+0x130> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; fdf: 31 d2 xor %edx,%edx fe1: e9 ff fe ff ff jmp ee5 <printf+0x55> fe6: 8d 76 00 lea 0x0(%esi),%esi fe9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); ff0: 83 ec 04 sub $0x4,%esp ff3: 88 5d e5 mov %bl,-0x1b(%ebp) ff6: 8d 45 e5 lea -0x1b(%ebp),%eax ff9: 6a 01 push $0x1 ffb: e9 4c ff ff ff jmp f4c <printf+0xbc> } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 1000: 83 ec 0c sub $0xc,%esp 1003: b9 0a 00 00 00 mov $0xa,%ecx 1008: 6a 01 push $0x1 100a: e9 6b ff ff ff jmp f7a <printf+0xea> 100f: 8b 5d d0 mov -0x30(%ebp),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 1012: 83 ec 04 sub $0x4,%esp 1015: 8b 03 mov (%ebx),%eax 1017: 6a 01 push $0x1 1019: 88 45 e4 mov %al,-0x1c(%ebp) 101c: 8d 45 e4 lea -0x1c(%ebp),%eax 101f: 50 push %eax 1020: 57 push %edi 1021: e8 1c fd ff ff call d42 <write> 1026: e9 5b ff ff ff jmp f86 <printf+0xf6> 102b: 66 90 xchg %ax,%ax 102d: 66 90 xchg %ax,%ax 102f: 90 nop 00001030 <free>: static Header base; static Header *freep; void free(void *ap) { 1030: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1031: a1 c4 18 00 00 mov 0x18c4,%eax static Header base; static Header *freep; void free(void *ap) { 1036: 89 e5 mov %esp,%ebp 1038: 57 push %edi 1039: 56 push %esi 103a: 53 push %ebx 103b: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 103e: 8b 10 mov (%eax),%edx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 1040: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1043: 39 c8 cmp %ecx,%eax 1045: 73 19 jae 1060 <free+0x30> 1047: 89 f6 mov %esi,%esi 1049: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 1050: 39 d1 cmp %edx,%ecx 1052: 72 1c jb 1070 <free+0x40> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1054: 39 d0 cmp %edx,%eax 1056: 73 18 jae 1070 <free+0x40> static Header base; static Header *freep; void free(void *ap) { 1058: 89 d0 mov %edx,%eax Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 105a: 39 c8 cmp %ecx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 105c: 8b 10 mov (%eax),%edx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 105e: 72 f0 jb 1050 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1060: 39 d0 cmp %edx,%eax 1062: 72 f4 jb 1058 <free+0x28> 1064: 39 d1 cmp %edx,%ecx 1066: 73 f0 jae 1058 <free+0x28> 1068: 90 nop 1069: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi break; if(bp + bp->s.size == p->s.ptr){ 1070: 8b 73 fc mov -0x4(%ebx),%esi 1073: 8d 3c f1 lea (%ecx,%esi,8),%edi 1076: 39 d7 cmp %edx,%edi 1078: 74 19 je 1093 <free+0x63> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 107a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 107d: 8b 50 04 mov 0x4(%eax),%edx 1080: 8d 34 d0 lea (%eax,%edx,8),%esi 1083: 39 f1 cmp %esi,%ecx 1085: 74 23 je 10aa <free+0x7a> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 1087: 89 08 mov %ecx,(%eax) freep = p; 1089: a3 c4 18 00 00 mov %eax,0x18c4 } 108e: 5b pop %ebx 108f: 5e pop %esi 1090: 5f pop %edi 1091: 5d pop %ebp 1092: c3 ret bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 1093: 03 72 04 add 0x4(%edx),%esi 1096: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 1099: 8b 10 mov (%eax),%edx 109b: 8b 12 mov (%edx),%edx 109d: 89 53 f8 mov %edx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 10a0: 8b 50 04 mov 0x4(%eax),%edx 10a3: 8d 34 d0 lea (%eax,%edx,8),%esi 10a6: 39 f1 cmp %esi,%ecx 10a8: 75 dd jne 1087 <free+0x57> p->s.size += bp->s.size; 10aa: 03 53 fc add -0x4(%ebx),%edx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 10ad: a3 c4 18 00 00 mov %eax,0x18c4 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 10b2: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 10b5: 8b 53 f8 mov -0x8(%ebx),%edx 10b8: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 10ba: 5b pop %ebx 10bb: 5e pop %esi 10bc: 5f pop %edi 10bd: 5d pop %ebp 10be: c3 ret 10bf: 90 nop 000010c0 <malloc>: return freep; } void* malloc(uint nbytes) { 10c0: 55 push %ebp 10c1: 89 e5 mov %esp,%ebp 10c3: 57 push %edi 10c4: 56 push %esi 10c5: 53 push %ebx 10c6: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 10c9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 10cc: 8b 15 c4 18 00 00 mov 0x18c4,%edx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 10d2: 8d 78 07 lea 0x7(%eax),%edi 10d5: c1 ef 03 shr $0x3,%edi 10d8: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 10db: 85 d2 test %edx,%edx 10dd: 0f 84 a3 00 00 00 je 1186 <malloc+0xc6> 10e3: 8b 02 mov (%edx),%eax 10e5: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 10e8: 39 cf cmp %ecx,%edi 10ea: 76 74 jbe 1160 <malloc+0xa0> 10ec: 81 ff 00 10 00 00 cmp $0x1000,%edi 10f2: be 00 10 00 00 mov $0x1000,%esi 10f7: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx 10fe: 0f 43 f7 cmovae %edi,%esi 1101: ba 00 80 00 00 mov $0x8000,%edx 1106: 81 ff ff 0f 00 00 cmp $0xfff,%edi 110c: 0f 46 da cmovbe %edx,%ebx 110f: eb 10 jmp 1121 <malloc+0x61> 1111: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1118: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 111a: 8b 48 04 mov 0x4(%eax),%ecx 111d: 39 cf cmp %ecx,%edi 111f: 76 3f jbe 1160 <malloc+0xa0> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 1121: 39 05 c4 18 00 00 cmp %eax,0x18c4 1127: 89 c2 mov %eax,%edx 1129: 75 ed jne 1118 <malloc+0x58> char *p; Header *hp; if(nu < 4096) nu = 4096; p = sbrk(nu * sizeof(Header)); 112b: 83 ec 0c sub $0xc,%esp 112e: 53 push %ebx 112f: e8 76 fc ff ff call daa <sbrk> if(p == (char*)-1) 1134: 83 c4 10 add $0x10,%esp 1137: 83 f8 ff cmp $0xffffffff,%eax 113a: 74 1c je 1158 <malloc+0x98> return 0; hp = (Header*)p; hp->s.size = nu; 113c: 89 70 04 mov %esi,0x4(%eax) free((void*)(hp + 1)); 113f: 83 ec 0c sub $0xc,%esp 1142: 83 c0 08 add $0x8,%eax 1145: 50 push %eax 1146: e8 e5 fe ff ff call 1030 <free> return freep; 114b: 8b 15 c4 18 00 00 mov 0x18c4,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 1151: 83 c4 10 add $0x10,%esp 1154: 85 d2 test %edx,%edx 1156: 75 c0 jne 1118 <malloc+0x58> return 0; 1158: 31 c0 xor %eax,%eax 115a: eb 1c jmp 1178 <malloc+0xb8> 115c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) 1160: 39 cf cmp %ecx,%edi 1162: 74 1c je 1180 <malloc+0xc0> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 1164: 29 f9 sub %edi,%ecx 1166: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 1169: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 116c: 89 78 04 mov %edi,0x4(%eax) } freep = prevp; 116f: 89 15 c4 18 00 00 mov %edx,0x18c4 return (void*)(p + 1); 1175: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 1178: 8d 65 f4 lea -0xc(%ebp),%esp 117b: 5b pop %ebx 117c: 5e pop %esi 117d: 5f pop %edi 117e: 5d pop %ebp 117f: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 1180: 8b 08 mov (%eax),%ecx 1182: 89 0a mov %ecx,(%edx) 1184: eb e9 jmp 116f <malloc+0xaf> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 1186: c7 05 c4 18 00 00 c8 movl $0x18c8,0x18c4 118d: 18 00 00 1190: c7 05 c8 18 00 00 c8 movl $0x18c8,0x18c8 1197: 18 00 00 base.s.size = 0; 119a: b8 c8 18 00 00 mov $0x18c8,%eax 119f: c7 05 cc 18 00 00 00 movl $0x0,0x18cc 11a6: 00 00 00 11a9: e9 3e ff ff ff jmp 10ec <malloc+0x2c>
; Listing generated by Microsoft (R) Optimizing Compiler Version 18.00.40629.0 TITLE C:\Users\cex123\Desktop\FYP\develop\spartan\Source\Kernel\BootLoad\Intel\Gdt.c .686P .XMM include listing.inc .model flat INCLUDELIB OLDNAMES PUBLIC _gdt EXTRN _movsd:PROC EXTRN _lgdt:PROC _gdt DQ 0000000000000000H DQ 00cf9a000000ffffH DQ 00cf92000000ffffH DQ 00dffa000000ffffH DQ 00dff2000000ffffH DQ 000f98000000ffffH DQ 000f92000000ffffH DQ 0000e9000000ffffH PUBLIC _EnableGdt PUBLIC _InstallGdt ; Function compile flags: /Ogspy ; File c:\users\cex123\desktop\fyp\develop\spartan\source\kernel\bootload\intel\gdt.c _TEXT SEGMENT _base$ = 8 ; size = 4 _size$ = 12 ; size = 4 _InstallGdt PROC ; 32 : u32 tss = (u32)base + size; ; 33 : gdt[7] |= tss*65536; mov eax, DWORD PTR _size$[esp-4] push esi mov esi, DWORD PTR _base$[esp] add eax, esi ; 34 : movsd(base, gdt, sizeof(gdt)/4); push 16 ; 00000010H shl eax, 16 ; 00000010H or DWORD PTR _gdt+56, eax push OFFSET _gdt push esi call _movsd add esp, 12 ; 0000000cH ; 35 : ; 36 : u32 *gdtr = (u32*)&base[sizeof(gdt)]; ; 37 : gdtr[0] = (sizeof(gdt)-1) << 16; mov DWORD PTR [esi+64], 4128768 ; 003f0000H ; 38 : gdtr[1] = (u32)base; ; 39 : return true; xor eax, eax mov DWORD PTR [esi+68], esi inc eax pop esi ; 40 : } ret 0 _InstallGdt ENDP _TEXT ENDS ; Function compile flags: /Ogspy ; File c:\users\cex123\desktop\fyp\develop\spartan\source\kernel\bootload\intel\gdt.c _TEXT SEGMENT _base$ = 8 ; size = 4 _size$ = 12 ; size = 4 _EnableGdt PROC ; 43 : lgdt(&base[sizeof(gdt)+2]); mov eax, DWORD PTR _base$[esp-4] add eax, 66 ; 00000042H push eax call _lgdt ; 44 : return true; xor eax, eax pop ecx inc eax ; 45 : } ret 0 _EnableGdt ENDP _TEXT ENDS END
#include "benchmark/benchmark.h" #include "c4/log.hpp" #include "c4/allocator.hpp" #include "../list_types.hpp" namespace bm = benchmark; namespace c4 { template< class List > void BM_ListPushBack(bm::State& st) { List li; using T = typename List::value_type; T v{}; size_t count = 0; while(st.KeepRunning()) { for(int i = 0, e = st.range(0); i < e; ++i) { if(li.size() == li.max_size()) li.clear(); li.push_back(v); ++count; } li.clear(); } st.SetComplexityN(st.range(0)); st.SetItemsProcessed(count); st.SetBytesProcessed(count * sizeof(T)); } BENCHMARK_TEMPLATE(BM_ListPushBack, split_list__small< NumBytes<4096> C4_COMMA int32_t >) ->RangeMultiplier(2) ->Range(4, 1<<19) ->Complexity(); } // end namespace c4 BENCHMARK_MAIN()
INCLUDE "hardware.inc" INCLUDE "header.inc" ;-------------------------------------------------------------------------- ;- RESTART VECTORS - ;-------------------------------------------------------------------------- SECTION "RST_00",HOME[$0000] ret SECTION "RST_08",HOME[$0008] ret SECTION "RST_10",HOME[$0010] ret SECTION "RST_18",HOME[$0018] ret SECTION "RST_20",HOME[$0020] ret SECTION "RST_28",HOME[$0028] ret SECTION "RST_30",HOME[$0030] ret SECTION "RST_38",HOME[$0038] jp Reset ;-------------------------------------------------------------------------- ;- INTERRUPT VECTORS - ;-------------------------------------------------------------------------- SECTION "Interrupt Vectors",HOME[$0040] ; SECTION "VBL Interrupt Vector",HOME[$0040] push hl ld hl,_is_vbl_flag ld [hl],1 jr irq_VBlank ; SECTION "LCD Interrupt Vector",HOME[$0048] push hl ld hl,LCD_handler jr irq_Common nop nop ; SECTION "TIM Interrupt Vector",HOME[$0050] ld [hl+],a ret nop nop nop nop nop nop ; SECTION "SIO Interrupt Vector",HOME[$0058] push hl ld hl,SIO_handler jr irq_Common nop nop ; SECTION "JOY Interrupt Vector",HOME[$0060] push hl ld hl,JOY_handler jr irq_Common ; nop ; nop ;-------------------------------------------------------------------------- ;- IRQS HANDLER - ;-------------------------------------------------------------------------- irq_VBlank: ld hl,VBL_handler irq_Common: push af ld a,[hl+] ld h,[hl] ld l,a ; or a,h ; jr z,.no_irq push bc push de call .goto_irq_handler pop de pop bc ;.no_irq: pop af pop hl reti .goto_irq_handler: jp hl ;-------------------------------------------------------------------------- ;- wait_vbl() - ;-------------------------------------------------------------------------- wait_vbl: ld hl,_is_vbl_flag ld [hl],0 ._not_yet: halt bit 0,[hl] jr z,._not_yet ret ;-------------------------------------------------------------------------- ;- CARTRIDGE HEADER - ;-------------------------------------------------------------------------- SECTION "Cartridge Header",HOME[$0100] nop jp StartPoint DB $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D DB $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99 DB $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E ; 0123456789ABC DB "TESTING......" DW $0000 DB $C0 ;GBC flag DB 0,0,0 ;SuperGameboy DB $1B ;CARTTYPE (MBC5+RAM+BATTERY) DB 0 ;ROMSIZE DB 2 ;RAMSIZE (8KB) DB $01 ;Destination (0 = Japan, 1 = Non Japan) DB $00 ;Manufacturer DB 0 ;Version DB 0 ;Complement check DW 0 ;Checksum ;-------------------------------------------------------------------------- ;- INITIALIZE THE GAMEBOY - ;-------------------------------------------------------------------------- SECTION "Program Start",HOME[$0150] StartPoint: di ld sp,$FFFE ; Use this as stack for a while push af ; Save CPU type push bc xor a,a ld [rNR52],a ; Switch off sound ld hl,_RAM ; Clear RAM ld bc,$2000 ld d,$00 call memset pop bc ; Get CPU type pop af ld [Init_Reg_A],a ; Save CPU type into RAM ld a,b ld [Init_Reg_B],a ld sp,StackTop ; Real stack call screen_off ld hl,_VRAM ; Clear VRAM ld bc,$2000 ld d,$00 call memset ld hl,_HRAM ; Clear high RAM (and rIE) ld bc,$0080 ld d,$00 call memset call init_OAM ; Copy OAM refresh function to high ram call refresh_OAM ; We filled RAM with $00, so this will clear OAM call rom_handler_init ; Real program starts here call Main ;Should never reach this point jp Reset ;-------------------------------------------------------------------------- ;- Reset() - ;-------------------------------------------------------------------------- Reset:: ld a,[Init_Reg_B] ld b,a ld a,[Init_Reg_A] jp $0100 ;-------------------------------------------------------------------------- ;- irq_set_VBL() bc = function pointer - ;- irq_set_LCD() bc = function pointer - ;- irq_set_TIM() bc = function pointer - ;- irq_set_SIO() bc = function pointer - ;- irq_set_JOY() bc = function pointer - ;-------------------------------------------------------------------------- irq_set_VBL:: ld hl,VBL_handler jr irq_set_handler irq_set_LCD:: ld hl,LCD_handler jr irq_set_handler irq_set_TIM:: ld hl,TIM_handler jr irq_set_handler irq_set_SIO:: ld hl,SIO_handler jr irq_set_handler irq_set_JOY:: ld hl,JOY_handler ; jr irq_set_handler irq_set_handler: ; hl = dest handler bc = function pointer ld [hl],c inc hl ld [hl],b ret ;-------------------------------------------------------------------------- ;- CPU_fast() - ;- CPU_slow() - ;-------------------------------------------------------------------------- CPU_fast:: ld a,[rKEY1] bit 7,a jr z,__CPU_switch ret CPU_slow:: ld a,[rKEY1] bit 7,a jr nz,__CPU_switch ret __CPU_switch: ld a,[rIE] ld b,a ; save IE xor a,a ld [rIE],a ld a,$30 ld [rP1],a ld a,$01 ld [rKEY1],a stop ld a,b ld [rIE],a ; restore IE ret ;-------------------------------------------------------------------------- ;- Variables - ;-------------------------------------------------------------------------- SECTION "StartupVars",BSS Init_Reg_A:: DS 1 Init_Reg_B:: DS 1 _is_vbl_flag: DS 1 VBL_handler: DS 2 LCD_handler: DS 2 TIM_handler: DS 2 SIO_handler: DS 2 JOY_handler: DS 2 SECTION "Stack",BSS[$CE00] Stack: DS $200 StackTop: ; $D000
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR NIRVANA+ ENGINE - by Einar Saukas ; ; See "nirvana+.h" for further details ; ---------------------------------------------------------------- ; void NIRVANAP_spriteT(unsigned int sprite, unsigned int tile, unsigned int lin, unsigned int col) SECTION code_clib SECTION code_nirvanap PUBLIC _NIRVANAP_spriteT EXTERN asm_NIRVANAP_spriteT _NIRVANAP_spriteT: ld hl,2 add hl,sp ld c,(hl) ; sprite inc hl inc hl ld a,(hl) ; tile inc hl inc hl ld d,(hl) ; lin inc hl inc hl ld e,(hl) ; col ld l,c ld h,0 jp asm_NIRVANAP_spriteT
; A315684: Coordination sequence Gal.5.291.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,12,17,22,27,32,37,42,48,54,60,66,71,76,81,86,91,96,102,108,114,120,125,130,135,140,145,150,156,162,168,174,179,184,189,194,199,204,210,216,222,228,233,238,243,248,253,258,264 mov $1,1 mov $2,$0 mov $3,$0 add $3,3 lpb $0,1 sub $0,1 add $1,$0 trn $3,5 mov $0,$3 trn $3,$1 sub $1,$0 trn $0,5 add $3,$0 lpe lpb $2,1 add $1,5 sub $2,1 lpe
/* * (C) Copyright 2009-2016 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include "model/Traits.h" #include "model/instantiateAqLocalizationFactory.h" #include "oops/runs/Run.h" #include "test/interface/Localization.h" int main(int argc, char ** argv) { oops::Run run(argc, argv); aq::instantiateAqLocalizationFactory(); test::Localization<aq::Traits> tests; return run.execute(tests); }
; A100577: Number of sets of divisors of n with an odd sum. ; Submitted by Christian Krause ; 1,2,2,4,2,8,2,8,4,8,2,32,2,8,8,16,2,32,2,32,8,8,2,128,4,8,8,32,2,128,2,32,8,8,8,256,2,8,8,128,2,128,2,32,32,8,2,512,4,32,8,32,2,128,8,128,8,8,2,2048,2,8,32,64,8,128,2,32,8,128,2,2048,2,8,32,32,8,128,2,512,16,8,2,2048,8,8,8,128,2,2048,8,32,8,8,8,2048,2,32,32,256 seq $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. mov $1,2 pow $1,$0 mov $0,$1 div $0,2
lda {m2}+3 lsr sta {m1}+3 lda {m2}+2 ror sta {m1}+2 lda {m2}+1 ror sta {m1}+1 lda {m2} ror sta {m1} lsr {m1}+3 ror {m1}+2 ror {m1}+1 ror {m1} lsr {m1}+3 ror {m1}+2 ror {m1}+1 ror {m1}
INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC getmaxy PUBLIC _getmaxy EXTERN __z9001_mode EXTERN CONSOLE_ROWS .getmaxy ._getmaxy ld a,(__z9001_mode) and a ld hl, +(CONSOLE_ROWS * 2) - 1 ret z ld hl, 191 ret
; A295220: a(n) = Sum_{i=1..floor(n/2)} floor((n+i)/i) - floor((n-i-1)/i). ; 0,3,3,6,5,9,7,11,10,13,11,17,13,17,17,20,17,23,19,25,23,25,23,31,26,29,29,33,29,37,31,37,35,37,37,44,37,41,41,47,41,49,43,49,49,49,47,57,50,55,53,57,53,61,57,63,59,61,59,71,61,65,67,70,67,73 mov $2,$0 mov $3,$0 mod $3,2 mov $0,$3 add $0,$2 seq $2,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n. add $0,$2 sub $0,1
; --COPYRIGHT--,BSD_EX ; Copyright (c) 2012, Texas Instruments Incorporated ; 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 Texas Instruments Incorporated nor the names of ; its contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ; THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ; EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, ; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, ; EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; ; ****************************************************************************** ; ; MSP430 CODE EXAMPLE DISCLAIMER ; ; MSP430 code examples are self-contained low-level programs that typically ; demonstrate a single peripheral function or device feature in a highly ; concise manner. For this the code may rely on the device's power-on default ; register values and settings such as the clock configuration and care must ; be taken when combining code from several examples to avoid potential side ; effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware ; for an API functional library-approach to peripheral configuration. ; ; --/COPYRIGHT-- ;****************************************************************************** ; MSP430F54xA Demo - USCI_A0, SPI 3-Wire Master Incremented Data ; ; Description: SPI master talks to SPI slave using 3-wire mode. Incrementing ; data is sent by the master starting at 0x01. Received data is expected to ; be same as the previous transmission. USCI RX ISR is used to handle ; communication with the CPU, normally in LPM0. If high, P1.0 indicates ; valid data reception. Because all execution after LPM0 is in ISRs, ; initialization waits for DCO to stabilize against ACLK. ; ACLK = ~32.768kHz, MCLK = SMCLK = DCO ~ 1048kHz. BRCLK = SMCLK/2 ; ; Use with SPI Slave Data Echo code example. If slave is in debug mode, P1.1 ; slave reset signal conflicts with slave's JTAG; to work around, use IAR's ; "Release JTAG on Go" on slave device. If breakpoints are set in ; slave RX ISR, master must stopped also to avoid overrunning slave ; RXBUF. ; ; MSP430F5438A ; ----------------- ; /|\| | ; | | | ; --|RST P1.0|-> LED ; | | ; | P3.4|-> Data Out (UCA0SIMO) ; | | ; | P3.5|<- Data In (UCA0SOMI) ; | | ; Slave reset <-|P1.1 P3.0|-> Serial Clock Out (UCA0CLK) ; ; ; D. Dang ; Texas Instruments Inc. ; December 2009 ; Built with CCS Version: 4.0.2 ;****************************************************************************** .cdecls C,LIST,"msp430.h" ;------------------------------------------------------------------------------- .def RESET ; Export program entry-point to ; make it known to linker. count .equ R4 MST_Data .equ R5 SLV_Data .equ R6 ;------------------------------------------------------------------------------- .global _main .text ; Assemble to Flash memory ;------------------------------------------------------------------------------- _main RESET mov.w #0x5C00,SP ; Initialize stackpointer mov.w #WDTPW + WDTHOLD,&WDTCTL; Stop WDT bis.b #0x02,&P1OUT ; Set P1.0 for LED ; Set P1.1 for slave reset bis.b #0x03,&P1DIR ; Set P1.0-2 to output direction bis.b #0x31,&P3SEL ; P3.5,4,0 option select bis.b #UCSWRST,&UCA0CTL1 ; **Reset USCI state machine** bis.b #UCMST + UCSYNC + UCCKPL + UCMSB,&UCA0CTL0 ; 3-pin, 8-bit SPI master ; Clock polarity high, MSB bis.b #UCSSEL_2,&UCA0CTL1 ; SMCLK mov.b #0x02,&UCA0BR0 ; /2 mov.b #0x00,&UCA0BR1 mov.b #0x00,&UCA0MCTL ; No modulation bic.b #UCSWRST,&UCA0CTL1 ;**Initialize USCI state machine** bis.b #UCRXIE,&UCA0IE ; Enable USCI_A0 RX interrupt bic.b #BIT1,&P1OUT ; Now with SPI signals initialized, bis.b #BIT1,&P1OUT ; reset slave mov.b #50,count ; Load delay counter slave_init_delay dec.b count ; Wait for slave to initialize jne slave_init_delay mov.b #0x01,MST_Data ; Initialize data values mov.b #0x00,SLV_Data ; check_Tx_buf bit.b #UCTXIFG,&UCA0IFG ; USCI_A0 TX buffer ready? jnc check_Tx_buf ; no -> check again mov.b MST_Data,&UCA0TXBUF ; yes -> Transmit first character bis.w #LPM0 + GIE,SR ; Enter LPM0, enable interrupts nop ; For debugger ;------------------------------------------------------------------------------- USCI_A0_ISR ;------------------------------------------------------------------------------- add.w &UCA0IV,PC ; Vector to interrupt handler reti ; Vector 0: No interrupt jmp RXIFG_HND ; Vector 2: RXIFG reti ; Vector 4: TXIFG RXIFG_HND check_TX_rdy bit.b #UCTXIFG,&UCA0IFG ; USCI_A0 TX buffer ready? jnc check_TX_rdy cmp.b SLV_Data,&UCA0RXBUF ; Test for correct character RX'd jne clear_led set_led bis.b #BIT0,&P1OUT ; If correct, light LED jmp correct_LED clear_led bic.b #BIT0,&P1OUT ; If incorrect, clear LED correct_LED inc.b MST_Data ; Increment data inc.b SLV_Data mov.b MST_Data,&UCA0TXBUF ; Send next value mov.b #30,count ; Load delay counter tx_delay dec.b count ; Add time between transmissions to jne tx_delay ; make sure slave can keep up reti ; Return from interrupt ;------------------------------------------------------------------------------- ; Interrupt Vectors ;------------------------------------------------------------------------------- .sect ".int57" .short USCI_A0_ISR .sect ".reset" ; POR, ext. Reset .short RESET .end
; A043656: Numbers whose base-12 representation has exactly 7 runs. ; 3006865,3006866,3006867,3006868,3006869,3006870,3006871,3006872,3006873,3006874,3006875,3006888,3006889,3006891,3006892,3006893,3006894,3006895,3006896,3006897,3006898,3006899,3006900,3006901 seq $0,43652 ; Numbers whose base-12 representation has exactly 3 runs. add $1,$0 add $1,3006720 mov $0,$1
; A016882: (5n+2)^10. ; 1024,282475249,61917364224,2015993900449,26559922791424,205891132094649,1125899906842624,4808584372417849,17080198121677824,52599132235830049,144555105949057024,362033331456891249,839299365868340224,1822837804551761449,3743906242624487424,7326680472586200649,13744803133596058624,24842341419143568849,43438845422363213824,73742412689492826049,121899441999475713024,196715135728956532249,310584820834420916224,480682838924478847449,730463141542791783424,1091533853073393531649,1605976966052654874624 mul $0,5 add $0,2 pow $0,10
;-------------------------------------------------------- ; File Created by SDCC : free open source ANSI-C Compiler ; Version 4.0.0 #11528 (Linux) ;-------------------------------------------------------- ; Processed by Z88DK ;-------------------------------------------------------- EXTERN __divschar EXTERN __divschar_callee EXTERN __divsint EXTERN __divsint_callee EXTERN __divslong EXTERN __divslong_callee EXTERN __divslonglong EXTERN __divslonglong_callee EXTERN __divsuchar EXTERN __divsuchar_callee EXTERN __divuchar EXTERN __divuchar_callee EXTERN __divuint EXTERN __divuint_callee EXTERN __divulong EXTERN __divulong_callee EXTERN __divulonglong EXTERN __divulonglong_callee EXTERN __divuschar EXTERN __divuschar_callee EXTERN __modschar EXTERN __modschar_callee EXTERN __modsint EXTERN __modsint_callee EXTERN __modslong EXTERN __modslong_callee EXTERN __modslonglong EXTERN __modslonglong_callee EXTERN __modsuchar EXTERN __modsuchar_callee EXTERN __moduchar EXTERN __moduchar_callee EXTERN __moduint EXTERN __moduint_callee EXTERN __modulong EXTERN __modulong_callee EXTERN __modulonglong EXTERN __modulonglong_callee EXTERN __moduschar EXTERN __moduschar_callee EXTERN __mulint EXTERN __mulint_callee EXTERN __mullong EXTERN __mullong_callee EXTERN __mullonglong EXTERN __mullonglong_callee EXTERN __mulschar EXTERN __mulschar_callee EXTERN __mulsuchar EXTERN __mulsuchar_callee EXTERN __muluschar EXTERN __muluschar_callee EXTERN __rlslonglong EXTERN __rlslonglong_callee EXTERN __rlulonglong EXTERN __rlulonglong_callee EXTERN __rrslonglong EXTERN __rrslonglong_callee EXTERN __rrulonglong EXTERN __rrulonglong_callee EXTERN ___sdcc_call_hl EXTERN ___sdcc_call_iy EXTERN ___sdcc_enter_ix EXTERN _banked_call EXTERN _banked_ret EXTERN ___fs2schar EXTERN ___fs2schar_callee EXTERN ___fs2sint EXTERN ___fs2sint_callee EXTERN ___fs2slong EXTERN ___fs2slong_callee EXTERN ___fs2slonglong EXTERN ___fs2slonglong_callee EXTERN ___fs2uchar EXTERN ___fs2uchar_callee EXTERN ___fs2uint EXTERN ___fs2uint_callee EXTERN ___fs2ulong EXTERN ___fs2ulong_callee EXTERN ___fs2ulonglong EXTERN ___fs2ulonglong_callee EXTERN ___fsadd EXTERN ___fsadd_callee EXTERN ___fsdiv EXTERN ___fsdiv_callee EXTERN ___fseq EXTERN ___fseq_callee EXTERN ___fsgt EXTERN ___fsgt_callee EXTERN ___fslt EXTERN ___fslt_callee EXTERN ___fsmul EXTERN ___fsmul_callee EXTERN ___fsneq EXTERN ___fsneq_callee EXTERN ___fssub EXTERN ___fssub_callee EXTERN ___schar2fs EXTERN ___schar2fs_callee EXTERN ___sint2fs EXTERN ___sint2fs_callee EXTERN ___slong2fs EXTERN ___slong2fs_callee EXTERN ___slonglong2fs EXTERN ___slonglong2fs_callee EXTERN ___uchar2fs EXTERN ___uchar2fs_callee EXTERN ___uint2fs EXTERN ___uint2fs_callee EXTERN ___ulong2fs EXTERN ___ulong2fs_callee EXTERN ___ulonglong2fs EXTERN ___ulonglong2fs_callee EXTERN ____sdcc_2_copy_src_mhl_dst_deix EXTERN ____sdcc_2_copy_src_mhl_dst_bcix EXTERN ____sdcc_4_copy_src_mhl_dst_deix EXTERN ____sdcc_4_copy_src_mhl_dst_bcix EXTERN ____sdcc_4_copy_src_mhl_dst_mbc EXTERN ____sdcc_4_ldi_nosave_bc EXTERN ____sdcc_4_ldi_save_bc EXTERN ____sdcc_4_push_hlix EXTERN ____sdcc_4_push_mhl EXTERN ____sdcc_lib_setmem_hl EXTERN ____sdcc_ll_add_de_bc_hl EXTERN ____sdcc_ll_add_de_bc_hlix EXTERN ____sdcc_ll_add_de_hlix_bc EXTERN ____sdcc_ll_add_de_hlix_bcix EXTERN ____sdcc_ll_add_deix_bc_hl EXTERN ____sdcc_ll_add_deix_hlix EXTERN ____sdcc_ll_add_hlix_bc_deix EXTERN ____sdcc_ll_add_hlix_deix_bc EXTERN ____sdcc_ll_add_hlix_deix_bcix EXTERN ____sdcc_ll_asr_hlix_a EXTERN ____sdcc_ll_asr_mbc_a EXTERN ____sdcc_ll_copy_src_de_dst_hlix EXTERN ____sdcc_ll_copy_src_de_dst_hlsp EXTERN ____sdcc_ll_copy_src_deix_dst_hl EXTERN ____sdcc_ll_copy_src_deix_dst_hlix EXTERN ____sdcc_ll_copy_src_deixm_dst_hlsp EXTERN ____sdcc_ll_copy_src_desp_dst_hlsp EXTERN ____sdcc_ll_copy_src_hl_dst_de EXTERN ____sdcc_ll_copy_src_hlsp_dst_de EXTERN ____sdcc_ll_copy_src_hlsp_dst_deixm EXTERN ____sdcc_ll_lsl_hlix_a EXTERN ____sdcc_ll_lsl_mbc_a EXTERN ____sdcc_ll_lsr_hlix_a EXTERN ____sdcc_ll_lsr_mbc_a EXTERN ____sdcc_ll_push_hlix EXTERN ____sdcc_ll_push_mhl EXTERN ____sdcc_ll_sub_de_bc_hl EXTERN ____sdcc_ll_sub_de_bc_hlix EXTERN ____sdcc_ll_sub_de_hlix_bc EXTERN ____sdcc_ll_sub_de_hlix_bcix EXTERN ____sdcc_ll_sub_deix_bc_hl EXTERN ____sdcc_ll_sub_deix_hlix EXTERN ____sdcc_ll_sub_hlix_bc_deix EXTERN ____sdcc_ll_sub_hlix_deix_bc EXTERN ____sdcc_ll_sub_hlix_deix_bcix EXTERN ____sdcc_load_debc_deix EXTERN ____sdcc_load_dehl_deix EXTERN ____sdcc_load_debc_mhl EXTERN ____sdcc_load_hlde_mhl EXTERN ____sdcc_store_dehl_bcix EXTERN ____sdcc_store_debc_hlix EXTERN ____sdcc_store_debc_mhl EXTERN ____sdcc_cpu_pop_ei EXTERN ____sdcc_cpu_pop_ei_jp EXTERN ____sdcc_cpu_push_di EXTERN ____sdcc_outi EXTERN ____sdcc_outi_128 EXTERN ____sdcc_outi_256 EXTERN ____sdcc_ldi EXTERN ____sdcc_ldi_128 EXTERN ____sdcc_ldi_256 EXTERN ____sdcc_4_copy_srcd_hlix_dst_deix EXTERN ____sdcc_4_and_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_or_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_deix EXTERN ____sdcc_4_or_src_dehl_dst_bcix EXTERN ____sdcc_4_xor_src_dehl_dst_bcix EXTERN ____sdcc_4_and_src_dehl_dst_bcix EXTERN ____sdcc_4_xor_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_or_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_and_src_mbc_mhl_dst_debc EXTERN ____sdcc_4_cpl_src_mhl_dst_debc EXTERN ____sdcc_4_xor_src_debc_mhl_dst_debc EXTERN ____sdcc_4_or_src_debc_mhl_dst_debc EXTERN ____sdcc_4_and_src_debc_mhl_dst_debc EXTERN ____sdcc_4_and_src_debc_hlix_dst_debc EXTERN ____sdcc_4_or_src_debc_hlix_dst_debc EXTERN ____sdcc_4_xor_src_debc_hlix_dst_debc ;-------------------------------------------------------- ; Public variables in this module ;-------------------------------------------------------- GLOBAL _m32_log10f ;-------------------------------------------------------- ; Externals used ;-------------------------------------------------------- GLOBAL _m32_polyf GLOBAL _m32_hypotf GLOBAL _m32_ldexpf GLOBAL _m32_frexpf GLOBAL _m32_invsqrtf GLOBAL _m32_sqrtf GLOBAL _m32_invf GLOBAL _m32_sqrf GLOBAL _m32_div2f GLOBAL _m32_mul2f GLOBAL _m32_modff GLOBAL _m32_fmodf GLOBAL _m32_roundf GLOBAL _m32_floorf GLOBAL _m32_fabsf GLOBAL _m32_ceilf GLOBAL _m32_powf GLOBAL _m32_log2f GLOBAL _m32_logf GLOBAL _m32_exp10f GLOBAL _m32_exp2f GLOBAL _m32_expf GLOBAL _m32_atanhf GLOBAL _m32_acoshf GLOBAL _m32_asinhf GLOBAL _m32_tanhf GLOBAL _m32_coshf GLOBAL _m32_sinhf GLOBAL _m32_atan2f GLOBAL _m32_atanf GLOBAL _m32_acosf GLOBAL _m32_asinf GLOBAL _m32_tanf GLOBAL _m32_cosf GLOBAL _m32_sinf GLOBAL _m32_coeff_logf GLOBAL __MAX_OPEN ;-------------------------------------------------------- ; special function registers ;-------------------------------------------------------- ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- SECTION bss_compiler ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- IF 0 ; .area _INITIALIZED removed by z88dk ENDIF ;-------------------------------------------------------- ; absolute external ram data ;-------------------------------------------------------- SECTION IGNORE ;-------------------------------------------------------- ; global & static initialisations ;-------------------------------------------------------- SECTION code_crt_init ;-------------------------------------------------------- ; Home ;-------------------------------------------------------- SECTION IGNORE ;-------------------------------------------------------- ; code ;-------------------------------------------------------- SECTION code_compiler ; --------------------------------- ; Function m32_log10f ; --------------------------------- _m32_log10f: push ix ld ix,0 add ix,sp ld c, l ld b, h ld hl, -14 add hl, sp ld sp, hl push bc push de push de push bc ld hl,0x0000 push hl push hl call ___fslt_callee pop de pop bc bit 0,l jr NZ,l_m32_log10f_00102 ld de,0xff00 ld hl,0x0000 jp l_m32_log10f_00106 l_m32_log10f_00102: ld hl,12 add hl, sp ld (ix-8),l ld (ix-7),h push hl push de push bc call _m32_frexpf push hl ld c,l ld b,h push de ld hl,0x3f35 push hl ld hl,0x04f3 push hl push de push bc call ___fslt_callee pop de pop bc ld a,l or a, a jr Z,l_m32_log10f_00104 ld l,(ix-2) ld h,(ix-1) dec hl ld (ix-2),l ld (ix-1),h ld l, c ld h, b call _m32_mul2f ld bc,0x3f80 push bc ld bc,0x0000 push bc push de push hl call ___fssub_callee ld (ix-6),l ld (ix-5),h ld (ix-4),e ld (ix-3),d jr l_m32_log10f_00105 l_m32_log10f_00104: ld hl,0x3f80 push hl ld hl,0x0000 push hl push de push bc call ___fssub_callee ld (ix-6),l ld (ix-5),h ld (ix-4),e ld (ix-3),d l_m32_log10f_00105: ld e,(ix-4) ld d,(ix-3) ld l,(ix-6) ld h,(ix-5) call _m32_sqrf ld (ix-14),l ld (ix-13),h ld (ix-12),e ld (ix-11),d ld hl,0x0009 push hl ld hl,_m32_coeff_logf push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call _m32_polyf ld c, l ld l,(ix-12) ld b,h ld h,(ix-11) push hl ld l,(ix-14) ld h,(ix-13) push hl push de push bc call ___fsmul_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld (ix-7),d pop bc pop de push de ld l,c ld h,b push hl call _m32_div2f push de push hl ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl call ___fssub_callee ld (ix-14),l ld (ix-13),h ld (ix-12),e ld l, e ld (ix-11),d ld h,d push hl ld l,(ix-14) ld h,(ix-13) push hl ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl call ___fsadd_callee push de push hl ld hl,0x3a37 push hl ld hl,0xb152 push hl call ___fsmul_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld (ix-7),d ld l,(ix-12) ld h,(ix-11) push hl ld l,(ix-14) ld h,(ix-13) push hl ld hl,0x3ede push hl ld hl,0x0000 push hl call ___fsmul_callee push de push hl ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl call ___fsadd_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld (ix-7),d ld l,(ix-4) ld h,(ix-3) push hl ld l,(ix-6) ld h,(ix-5) push hl ld hl,0x3ede push hl ld hl,0x0000 push hl call ___fsmul_callee push de push hl ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl call ___fsadd_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld (ix-7),d ld l,(ix-2) ld h,(ix-1) push hl call ___sint2fs_callee ld (ix-14),l ld (ix-13),h ld (ix-12),e ld l, e ld (ix-11),d ld h,d push hl ld l,(ix-14) ld h,(ix-13) push hl ld hl,0x3982 push hl ld hl,0x6a14 push hl call ___fsmul_callee push de push hl ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl call ___fsadd_callee ld (ix-10),l ld (ix-9),h ld (ix-8),e ld (ix-7),d ld l,(ix-12) ld h,(ix-11) push hl ld l,(ix-14) ld h,(ix-13) push hl ld hl,0x3e9a push hl ld hl,0x0000 push hl call ___fsmul_callee push de push hl ld l,(ix-8) ld h,(ix-7) push hl ld l,(ix-10) ld h,(ix-9) push hl call ___fsadd_callee l_m32_log10f_00106: ld sp, ix pop ix ret SECTION IGNORE
;Mupen64plus - linkage_x86.asm ;Copyright (C) 2009-2011 Ari64 ; ;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. %ifdef ELF_TYPE %macro cglobal 1 global %1 %endmacro %macro cextern 1 extern %1 %endmacro %else %macro cglobal 1 global _%1 %define %1 _%1 %endmacro %macro cextern 1 extern _%1 %define %1 _%1 %endmacro %endif cglobal dyna_linker cglobal dyna_linker_ds cglobal jump_vaddr_eax cglobal jump_vaddr_ecx cglobal jump_vaddr_edx cglobal jump_vaddr_ebx cglobal jump_vaddr_ebp cglobal jump_vaddr_edi cglobal verify_code_ds cglobal verify_code_vm cglobal verify_code cglobal cc_interrupt cglobal do_interrupt cglobal fp_exception cglobal fp_exception_ds cglobal jump_syscall cglobal jump_eret cglobal new_dyna_start cglobal invalidate_block_eax cglobal invalidate_block_ecx cglobal invalidate_block_edx cglobal invalidate_block_ebx cglobal invalidate_block_ebp cglobal invalidate_block_esi cglobal invalidate_block_edi cglobal write_rdram_new cglobal write_rdramb_new cglobal write_rdramh_new cglobal write_rdramd_new cglobal read_nomem_new cglobal read_nomemb_new cglobal read_nomemh_new cglobal read_nomemd_new cglobal write_nomem_new cglobal write_nomemb_new cglobal write_nomemh_new cglobal write_nomemd_new cglobal breakpoint cextern base_addr cextern tlb_LUT_r cextern jump_in cextern add_link cextern hash_table cextern jump_dirty cextern new_recompile_block cextern g_cp0_regs cextern get_addr_ht cextern cycle_count cextern get_addr cextern branch_target cextern memory_map cextern pending_exception cextern restore_candidate cextern gen_interupt cextern next_interupt cextern stop cextern last_count cextern pcaddr cextern clean_blocks cextern reg cextern hi cextern lo cextern invalidate_block cextern address cextern g_rdram cextern cpu_byte cextern cpu_hword cextern cpu_word cextern cpu_dword cextern invalid_code cextern readmem_dword cextern check_interupt cextern get_addr_32 section .bss align 4 section .rodata section .text dyna_linker: ;eax = virtual target address ;ebx = instruction to patch mov edi, eax mov ecx, eax shr edi, 12 cmp eax, 0C0000000h cmovge ecx, [tlb_LUT_r+edi*4] test ecx, ecx cmovz ecx, eax xor ecx, 080000000h mov edx, 2047 shr ecx, 12 and edx, ecx or edx, 2048 cmp ecx, edx cmova ecx, edx ;jump_in lookup mov edx, [jump_in+ecx*4] _A1: test edx, edx je _A3 mov edi, [edx] xor edi, eax or edi, [4+edx] je _A2 mov edx, DWORD [12+edx] jmp _A1 _A2: mov edi, [ebx] mov ebp, esi lea esi, [4+ebx+edi*1] mov edi, eax pusha call add_link popa mov edi, [8+edx] mov esi, ebp lea edx, [-4+edi] sub edx, ebx mov DWORD [ebx], edx jmp edi _A3: ;hash_table lookup mov edi, eax mov edx, eax shr edi, 16 shr edx, 12 xor edi, eax and edx, 2047 movzx edi, di shl edi, 4 cmp ecx, 2048 cmovc ecx, edx cmp eax, [hash_table+edi] jne _A5 _A4: mov edx, [hash_table+4+edi] jmp edx _A5: cmp eax, [hash_table+8+edi] lea edi, [8+edi] je _A4 ;jump_dirty lookup mov edx, [jump_dirty+ecx*4] _A6: test edx, edx je _A8 mov ecx, [edx] xor ecx, eax or ecx, [4+edx] je _A7 mov edx, DWORD [12+edx] jmp _A6 _A7: mov edx, [8+edx] ;hash_table insert mov ebx, [hash_table-8+edi] mov ecx, [hash_table-4+edi] mov [hash_table-8+edi], eax mov [hash_table-4+edi], edx mov [hash_table+edi], ebx mov [hash_table+4+edi], ecx jmp edx _A8: mov edi, eax pusha call new_recompile_block test eax, eax popa je dyna_linker ;pagefault mov ebx, eax mov ecx, 008h exec_pagefault: ;eax = instruction pointer ;ebx = fault address ;ecx = cause mov edx, [g_cp0_regs+48] add esp, -12 mov edi, [g_cp0_regs+16] or edx, 2 mov [g_cp0_regs+32], ebx ;BadVAddr and edi, 0FF80000Fh mov [g_cp0_regs+48], edx ;Status mov [g_cp0_regs+52], ecx ;Cause mov [g_cp0_regs+56], eax ;EPC mov ecx, ebx shr ebx, 9 and ecx, 0FFFFE000h and ebx, 0007FFFF0h mov [g_cp0_regs+40], ecx ;EntryHI or edi, ebx mov [g_cp0_regs+16], edi ;Context push 080000000h call get_addr_ht add esp, 16 jmp eax ;Special dynamic linker for the case where a page fault ;may occur in a branch delay slot dyna_linker_ds: mov edi, eax mov ecx, eax shr edi, 12 cmp eax, 0C0000000h cmovge ecx, [tlb_LUT_r+edi*4] test ecx, ecx cmovz ecx, eax xor ecx, 080000000h mov edx, 2047 shr ecx, 12 and edx, ecx or edx, 2048 cmp ecx, edx cmova ecx, edx ;jump_in lookup mov edx, [jump_in+ecx*4] _B1: test edx, edx je _B3 mov edi, [edx] xor edi, eax or edi, [4+edx] je _B2 mov edx, DWORD [12+edx] jmp _B1 _B2: mov edi, [ebx] mov ecx, esi lea esi, [4+ebx+edi*1] mov edi, eax pusha call add_link popa mov edi, [8+edx] mov esi, ecx lea edx, [-4+edi] sub edx, ebx mov DWORD [ebx], edx jmp edi _B3: ;hash_table lookup mov edi, eax mov edx, eax shr edi, 16 shr edx, 12 xor edi, eax and edx, 2047 movzx edi, di shl edi, 4 cmp ecx, 2048 cmovc ecx, edx cmp eax, [hash_table+edi] jne _B5 _B4: mov edx, [hash_table+4+edi] jmp edx _B5: cmp eax, [hash_table+8+edi] lea edi, [8+edi] je _B4 ;jump_dirty lookup mov edx, [jump_dirty+ecx*4] _B6: test edx, edx je _B8 mov ecx, [edx] xor ecx, eax or ecx, [4+edx] je _B7 mov edx, DWORD [12+edx] jmp _B6 _B7: mov edx, [8+edx] ;hash_table insert mov ebx, [hash_table-8+edi] mov ecx, [hash_table-4+edi] mov [hash_table-8+edi], eax mov [hash_table-4+edi], edx mov [hash_table+edi], ebx mov [hash_table+4+edi], ecx jmp edx _B8: mov edi, eax and edi, 0FFFFFFF8h inc edi pusha call new_recompile_block test eax, eax popa je dyna_linker_ds ;pagefault and eax, 0FFFFFFF8h mov ecx, 080000008h ;High bit set indicates pagefault in delay slot mov ebx, eax sub eax, 4 jmp exec_pagefault jump_vaddr_eax: mov edi, eax jmp jump_vaddr_edi jump_vaddr_ecx: mov edi, ecx jmp jump_vaddr_edi jump_vaddr_edx: mov edi, edx jmp jump_vaddr_edi jump_vaddr_ebx: mov edi, ebx jmp jump_vaddr_edi jump_vaddr_ebp: mov edi, ebp jump_vaddr_edi: mov eax, edi jump_vaddr: ;Check hash table shr eax, 16 xor eax, edi movzx eax, ax shl eax, 4 cmp edi, [hash_table+eax] jne _C2 _C1: mov edi, [hash_table+4+eax] jmp edi _C2: cmp edi, [hash_table+8+eax] lea eax, [8+eax] je _C1 ;No hit on hash table, call compiler add esp, -12 push edi mov [cycle_count], esi ;CCREG call get_addr mov esi, [cycle_count] add esp, 16 jmp eax verify_code_ds: mov [branch_target], ebp verify_code_vm: ;eax = source (virtual address) ;ebx = target ;ecx = length cmp eax, 0C0000000h jl verify_code mov edx, eax lea ebp, [-1+eax+ecx*1] shr edx, 12 shr ebp, 12 mov edi, [memory_map+edx*4] test edi, edi js _D5 lea eax, [eax+edi*4] _D1: xor edi, [memory_map+edx*4] shl edi, 2 jne _D5 mov edi, [memory_map+edx*4] inc edx cmp edx, ebp jbe _D1 verify_code: ;eax = source ;ebx = target ;ecx = length mov edi, [-4+eax+ecx*1] xor edi, [-4+ebx+ecx*1] jne _D5 mov edx, ecx add ecx, -4 je _D3 test edx, 4 cmove ecx, edx mov [cycle_count], esi _D2: mov edx, [-4+eax+ecx*1] mov ebp, [-4+ebx+ecx*1] mov esi, [-8+eax+ecx*1] xor ebp, edx mov edi, [-8+ebx+ecx*1] jne _D4 xor edi, esi jne _D4 add ecx, -8 jne _D2 mov esi, [cycle_count] mov ebp, [branch_target] _D3: ret _D4: mov esi, [cycle_count] _D5: mov ebp, [branch_target] push esi ;for stack alignment, unused push DWORD [8+esp] call get_addr add esp, 16 ;pop stack jmp eax cc_interrupt: add esi, [last_count] add esp, -28 ;Align stack mov [g_cp0_regs+36], esi ;Count shr esi, 19 mov DWORD [pending_exception], 0 and esi, 07fh cmp DWORD [restore_candidate+esi*4], 0 jne _E4 _E1: call gen_interupt mov esi, [g_cp0_regs+36] mov eax, [next_interupt] mov ebx, [pending_exception] mov ecx, [stop] add esp, 28 mov [last_count], eax sub esi, eax test ecx, ecx jne _E3 test ebx, ebx jne _E2 ret _E2: add esp, -8 mov edi, [pcaddr] mov [cycle_count], esi ;CCREG push edi call get_addr_ht mov esi, [cycle_count] add esp, 16 jmp eax _E3: add esp, 16 ;pop stack pop edi ;restore edi pop esi ;restore esi pop ebx ;restore ebx pop ebp ;restore ebp ret ;exit dynarec _E4: ;Move 'dirty' blocks to the 'clean' list mov ebx, [restore_candidate+esi*4] mov ebp, esi mov DWORD [restore_candidate+esi*4], 0 shl ebp, 5 _E5: shr ebx, 1 jnc _E6 mov [esp], ebp call clean_blocks _E6: inc ebp test ebp, 31 jne _E5 jmp _E1 do_interrupt: mov edi, [pcaddr] add esp, -12 push edi call get_addr_ht add esp, 16 mov esi, [g_cp0_regs+36] mov ebx, [next_interupt] mov [last_count], ebx sub esi, ebx add esi, 2 jmp eax fp_exception: mov edx, 01000002ch _E7: mov ebx, [g_cp0_regs+48] add esp, -12 or ebx, 2 mov [g_cp0_regs+48], ebx ;Status mov [g_cp0_regs+52], edx ;Cause mov [g_cp0_regs+56], eax ;EPC push 080000180h call get_addr_ht add esp, 16 jmp eax fp_exception_ds: mov edx, 09000002ch ;Set high bit if delay slot jmp _E7 jump_syscall: mov edx, 020h mov ebx, [g_cp0_regs+48] add esp, -12 or ebx, 2 mov [g_cp0_regs+48], ebx ;Status mov [g_cp0_regs+52], edx ;Cause mov [g_cp0_regs+56], eax ;EPC push 080000180h call get_addr_ht add esp, 16 jmp eax jump_eret: mov ebx, [g_cp0_regs+48] ;Status add esi, [last_count] and ebx, 0FFFFFFFDh mov [g_cp0_regs+36], esi ;Count mov [g_cp0_regs+48], ebx ;Status call check_interupt mov eax, [next_interupt] mov esi, [g_cp0_regs+36] mov [last_count], eax sub esi, eax mov eax, [g_cp0_regs+56] ;EPC jns _E11 _E8: mov ebx, 248 xor edi, edi _E9: mov ecx, [reg+ebx] mov edx, [reg+4+ebx] sar ecx, 31 xor edx, ecx neg edx adc edi, edi sub ebx, 8 jne _E9 mov ecx, [hi+ebx] mov edx, [hi+4+ebx] sar ecx, 31 xor edx, ecx jne _E10 mov ecx, [lo+ebx] mov edx, [lo+4+ebx] sar ecx, 31 xor edx, ecx _E10: neg edx adc edi, edi add esp, -8 push edi push eax mov [cycle_count], esi call get_addr_32 mov esi, [cycle_count] add esp, 16 jmp eax _E11: mov [pcaddr], eax call cc_interrupt mov eax, [pcaddr] jmp _E8 new_dyna_start: push ebp push ebx push esi push edi add esp, -8 ;align stack push 0a4000040h call new_recompile_block mov edi, DWORD [next_interupt] mov esi, DWORD [g_cp0_regs+36] mov DWORD [last_count], edi sub esi, edi jmp DWORD [base_addr] invalidate_block_eax: push eax push ecx push edx push eax jmp invalidate_block_call invalidate_block_ecx: push eax push ecx push edx push ecx jmp invalidate_block_call invalidate_block_edx: push eax push ecx push edx push edx jmp invalidate_block_call invalidate_block_ebx: push eax push ecx push edx push ebx jmp invalidate_block_call invalidate_block_ebp: push eax push ecx push edx push ebp jmp invalidate_block_call invalidate_block_esi: push eax push ecx push edx push esi jmp invalidate_block_call invalidate_block_edi: push eax push ecx push edx push edi invalidate_block_call: call invalidate_block pop eax ;Throw away pop edx pop ecx pop eax ret write_rdram_new: mov edi, [address] mov ecx, [cpu_word] mov [g_rdram-0x80000000+edi], ecx jmp _E12 write_rdramb_new: mov edi, [address] xor edi, 3 mov cl, BYTE [cpu_byte] mov BYTE [g_rdram-0x80000000+edi], cl jmp _E12 write_rdramh_new: mov edi, [address] xor edi, 2 mov cx, WORD [cpu_hword] mov WORD [g_rdram-0x80000000+edi], cx jmp _E12 write_rdramd_new: mov edi, [address] mov ecx, [cpu_dword+4] mov edx, [cpu_dword+0] mov [g_rdram-0x80000000+edi], ecx mov [g_rdram-0x80000000+4+edi], edx jmp _E12 do_invalidate: mov edi, [address] mov ebx, edi ;Return ebx to caller _E12: shr edi, 12 cmp BYTE [invalid_code+edi], 1 je _E13 push edi call invalidate_block pop edi _E13: ret read_nomem_new: mov edi, [address] mov ebx, edi shr edi, 12 mov edi, [memory_map+edi*4] mov eax, 08h test edi, edi js tlb_exception mov ecx, [ebx+edi*4] mov [readmem_dword], ecx ret read_nomemb_new: mov edi, [address] mov ebx, edi shr edi, 12 mov edi, [memory_map+edi*4] mov eax, 08h test edi, edi js tlb_exception xor ebx, 3 movzx ecx, BYTE [ebx+edi*4] mov [readmem_dword], ecx ret read_nomemh_new: mov edi, [address] mov ebx, edi shr edi, 12 mov edi, [memory_map+edi*4] mov eax, 08h test edi, edi js tlb_exception xor ebx, 2 movzx ecx, WORD [ebx+edi*4] mov [readmem_dword], ecx ret read_nomemd_new: mov edi, [address] mov ebx, edi shr edi, 12 mov edi, [memory_map+edi*4] mov eax, 08h test edi, edi js tlb_exception mov ecx, [4+ebx+edi*4] mov edx, [ebx+edi*4] mov [readmem_dword], ecx mov [readmem_dword+4], edx ret write_nomem_new: call do_invalidate mov edi, [memory_map+edi*4] mov ecx, [cpu_word] mov eax, 0ch shl edi, 2 jc tlb_exception mov [ebx+edi], ecx ret write_nomemb_new: call do_invalidate mov edi, [memory_map+edi*4] mov cl, BYTE [cpu_byte] mov eax, 0ch shl edi, 2 jc tlb_exception xor ebx, 3 mov BYTE [ebx+edi], cl ret write_nomemh_new: call do_invalidate mov edi, [memory_map+edi*4] mov cx, WORD [cpu_hword] mov eax, 0ch shl edi, 2 jc tlb_exception xor ebx, 2 mov WORD [ebx+edi], cx ret write_nomemd_new: call do_invalidate mov edi, [memory_map+edi*4] mov edx, [cpu_dword+4] mov ecx, [cpu_dword+0] mov eax, 0ch shl edi, 2 jc tlb_exception mov [ebx+edi], edx mov [4+ebx+edi], ecx ret tlb_exception: ;eax = cause ;ebx = address ;ebp = instr addr + flags mov ebp, [024h+esp] ;Debug: ;push ebp ;push ebx ;push eax ;call tlb_debug ;pop eax ;pop ebx ;pop ebp ;end debug mov esi, [g_cp0_regs+48] mov ecx, ebp mov edx, ebp mov edi, ebp shl ebp, 31 shr ecx, 12 or eax, ebp sar ebp, 29 and edx, 0FFFFFFFCh mov ecx, [memory_map+ecx*4] or esi, 2 mov ecx, [edx+ecx*4] add edx, ebp mov [g_cp0_regs+48], esi ;Status mov [g_cp0_regs+52], eax ;Cause mov [g_cp0_regs+56], edx ;EPC add esp, 024h mov edx, 06000022h mov ebp, ecx movsx eax, cx shr ecx, 26 shr ebp, 21 sub ebx, eax and ebp, 01fh ror edx, cl mov esi, [g_cp0_regs+16] cmovc ebx, [reg+ebp*8] and esi, 0FF80000Fh mov [reg+ebp*8], ebx add eax, ebx sar ebx, 31 mov [g_cp0_regs+32], eax ;BadVAddr shr eax, 9 test edi, 2 cmove ebx, [reg+4+ebp*8] add esp, -12 and eax, 0007FFFF0h mov [reg+4+ebp*8], ebx push 080000180h or esi, eax mov [g_cp0_regs+16], esi ;Context call get_addr_ht add esp, 16 mov edi, DWORD [next_interupt] mov esi, DWORD [g_cp0_regs+36] ;Count mov DWORD [last_count], edi sub esi, edi jmp eax breakpoint:
; ___________________________________________________________ ;/ __ _ \ ;| / _| (_) | ;| | |_ _ _ ___ _ ___ _ __ | ;| | _| | | / __| |/ _ \| '_ \ | ;| | | | |_| \__ \ | (_) | | | | | ;| |_| \__,_|___/_|\___/|_| |_| * | ;| | ;| The MSX C Library for SDCC | ;| V1.0 - 09-10-11 2018 | ;| | ;| Eric Boez & Fernando Garcia | ;| | ;| A S M S O U R C E C O D E | ;| | ;| | ;\___________________________________________________________/ ; ; ; IO.H ; Disk operations ; ; (c) 1995, SOLID MSX C ; ; SDCC port 2015 ; ; MSXDOS1, MSXDOS2 disk operations ; SECTION CODE ;--- proc FCBs ; ; INIT for IO operations ; Returns pointer to FCB list ; PUBLIC _FCBs _FCBs: call _OS_version call _prep_fcbs ld hl, __buf8_fcbs ret ;--- end of proc ;--- proc GET_OS_VERSION ; ; int GetOSVersion( ) ; ; PUBLIC _GetOSVersion _GetOSVersion: call _OS_version ld h, 0 ld a,(__os_ver) ld l, a ret _OS_version: ld c,0xC call 5 cp 5 jr z,lb_v1 lb_va: ld bc,0x6F call 5 ld (__mx_ver),de ;MSXDOS2.SYS version number ld a,b ;MSX-DOS kernel version cp 2 jr c,lb_v1 ld a,2 lb_vb: ld (__os_ver),a ret lb_v1: ld a,1 jr lb_vb ;.area _DATA PUBLIC __os_ver __os_ver: db 0 ;1 -> MSXDOS 1.X, 2-> MSXDOS2 PUBLIC __mx_ver __mx_ver: db 0 ;--- end of proc SECTION CODE ;- ; Variables and temporary FCBs for DOS1 functions ;- ;.area _DATA PUBLIC __buf8_fcbs __buf8_fcbs: ;allocate 8 FCBs for DOS1 ds 38*8 ;304 bytes = 0xff PUBLIC __io_errno __io_errno: db 0,0 _xfcb: ds 38 _ffcb: ds 38 lb_con: db 0 db "CON " db 0 SECTION CODE ;--- proc prep_fcbs _prep_fcbs: xor a ld (de),a ;allocate 8 FCBs for DOS1 ld hl, __buf8_fcbs ;set 2 FCBs to CON call _opencon ld de,38 add hl,de call _opencon ret _opencon: push hl ex de,hl push de ld hl,lb_con ld bc,13 ldir pop de push de ld c,0xF call 5 pop ix ld (ix+14),1 ld (ix+15),0 pop hl ret ; ;--- end of proc ;--- proc setfcb ; setup FCB, used for DOS1 file IO functions PUBLIC __setupfcb __setupfcb: push hl push de ld l,e ld h,d inc de ld bc,16 ld (hl),0 ldir pop de pop hl ; xor a ld (de),a inc hl ld a,(hl) cp ':' dec hl jr nz,lb_setu5 ld a,(hl) and 0xF ld (de),a inc hl inc hl lb_setu5: inc de lb_setu6: ld b,8 call lb_setu7 ld a,(hl) cp '.' jr nz,lb_setu8 inc hl lb_setu8: ld b,3 call lb_setu7 xor a ret ; lb_setu7: ld a,(hl) cp '.' jr z,lb_setu9 cp '*' jr z,lb_setu12 cp '!' jr c,lb_setu9 ld (de),a inc hl inc de djnz lb_setu7 ret lb_setu12: inc hl ld a,'?' jr lb_setu10 ; lb_setu9: ld a,' ' lb_setu10: ld (de),a inc de djnz lb_setu10 ret ;--- end of proc ;--- proc dos1fd ; convert FD to FCB address for DOS1 PUBLIC _get_fd _get_fd: ld h,0 add hl,hl ld d,h ld e,l add hl,hl ld b,h ld c,l add hl,hl add hl,hl add hl,hl add hl,de add hl,bc ld de, __buf8_fcbs add hl,de ret ;--- end of proc ;--- proc open ; ; FD Open(char *name, int mode) -- DOS1 (attributes ignored), DOS2 ; FD OpenAttrib(char *name, int mode, int attrib) -- DOS2 ; ; Attributes are for MSXDOS2 only ; PUBLIC _Open _Open: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld bc,0 pop ix jr _iopen PUBLIC _OpenAttrib _OpenAttrib: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) pop ix PUBLIC _iopen _iopen: push ix ld a,(__os_ver) or a jr nz,lb_opC ; maybe not initiated push hl push de push bc call _OS_version call _prep_fcbs pop bc pop de pop hl ld a,(__os_ver) or a jr z, lb_op15 ; if can not manage lb_opC: dec a dec a jr z,lb_op2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_op1 ; MSXDOS1 lb_op25: pop ix or a ld (__io_errno),a ld h,0 ret z lb_op14: ld hl,-1 ret ; lb_op2: xor a ld b,c ;attributes bit 0,e ;O_WRITE jr nz,lb_op21 or 1 lb_op21: bit 2,e ;O_EXCL? jr z,lb_op22 set 7,b lb_op22: bit 5,e ld c,0x43 jr z,lb_op23 bit 4,e jr z,lb_op23 inc c lb_op23: ex de,hl push hl call 5 ld (__io_errno),a pop de bit 6,e jr z,lb_op24 push bc ld hl,0 ;O_APPEND ld d,h ld e,l ld a,2 ld c,0x4A ; seek to end call 5 pop bc lb_op24: ld h,0 ld l,b jr lb_op25 ; lb_op1: push de push hl ;attributes ignored in DOS-1 ld hl, __buf8_fcbs ld de,38 ld b,8 ; 8-fcbs lb_op11: ld a,(hl) inc a jr z,lb_op12 add hl,de djnz lb_op11 pop de pop hl lb_op15: pop ix jr lb_op14 ; lb_op12: ld a,8 ; 8-fcbs sub b ld (lb_fdd),a ex de,hl pop hl push de call __setupfcb pop de pop bc bit 5,c ;CREATE? push bc ld c,0xF jr z,lb_op13 ld c,0x16 lb_op13: push de call 5 ld (__io_errno),a pop de pop bc or a jr nz,lb_op15 ld hl,14 add hl,de ld (hl),1 ;set reclen = 1 inc hl ld (hl),0 push hl ld de,18 add hl,de ;hl -> RANDOMREC ex de,hl pop hl inc hl bit 6,c jr nz,lb_op16 ld hl,lb_po0 lb_op16: ld bc,4 ldir ld hl,(lb_fdd) jp lb_op25 ; ;.area _DATA lb_po0: db 0,0,0,0 ;pointer position for OPEN ;--- end of proc SECTION CODE ;--- proc close ; ; int Close(FD fd); -- DOS1, DOS2 ; PUBLIC _Close _Close: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix PUBLIC _iclose _iclose: ld h,0 ld a,(__os_ver) dec a dec a jr z,lb_cl2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_cl1 ; MSXDOS1 lb_cl0: push ix call 5 lb_cl00: pop ix or a ld hl,0 ld (__io_errno),a ret z dec hl ret ; lb_cl1: call _get_fd ex de,hl ld c,0x10 push ix push de call 5 pop hl ld (hl),255 jr lb_cl00 ; lb_cl2: ld b,l ld c,0x45 jr lb_cl0 ; ;.area _DATA lb_fdd: dw 0 ;--- end of proc SECTION CODE ;--- proc create ; ; FD Create(char *name) -- DOS1(attributes ignored), DOS2 ; FD CreateAttrib(char *name, int attr) -- DOS2 ; PUBLIC _Create _Create: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix ld de,0 jr lb_crt PUBLIC _CreateAttrib _CreateAttrib: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) pop ix lb_crt: ld c,e ld b,d ld e,0x39 jp _iopen ;--- end of proc ;--- proc read ; ; int Read(FD fd, void *buf, int nbytes); -- DOS1, DOS2 ; PUBLIC _Read _Read: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) pop ix PUBLIC _iread _iread: push ix ld a,(__os_ver) dec a dec a jr z,lb_rd2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_rd1 ; MSXDOS1 lb_rd3: call 5 lb_rd3a: pop ix cp 2 ret c ld (__io_errno),a ld hl,0 ret ; lb_rd1: push bc push hl ld c,0x1A call 5 pop hl call _get_fd ex de,hl pop hl ;byte cnt ld c,0x27 push de call 5 pop ix bit 7,(ix+24) jr z,lb_rd3a set 6,(ix+24) jr lb_rd3a ; lb_rd2: ld a,l ld l,c ld h,b ld b,a ld c,0x48 jr lb_rd3 ;--- end of proc ;--- proc write ; ; int Write(FD fd,void *buf,int nbytes); -- DOS1, DOS2 ; PUBLIC _Write _Write: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) pop ix PUBLIC _iwrite _iwrite: push ix ld a,(__os_ver) dec a dec a jr z,lb_wr2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_wr1 ; MSXDOS1 lb_wr3: call 5 pop ix cp 2 ret c ld (__io_errno),a ld hl,0 ret ; lb_wr1: push bc push hl ld c,0x1A call 5 pop hl call _get_fd ex de,hl pop hl ;byte cnt ld c,0x26 jr lb_wr3 ; lb_wr2: ld a,l ld l,c ld h,b ld b,a ld c,0x49 jr lb_wr3 ;--- end of proc ;--- proc lseek ; ; char Lseek(FD fd,long *where, char ot); -- DOS1, DOS2 ; ; PUBLIC _Lseek _Lseek: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) pop ix call _ilseek ld l,a ld h,0 ret PUBLIC _ilseek _ilseek: push ix ld a,(__os_ver) dec a dec a jr z,lb_sk2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_sk1 ; MSXDOS1 lb_sk0: call 5 pop ix ld (__io_errno),a ret ; lb_sk2: ld a,c ld b,l push de pop ix ld l,(ix+0) ld h,(ix+1) ld e,(ix+2) ld d,(ix+3) ld c,0x4A jr lb_sk0 ; lb_sk1: push de push bc call _get_fd ex de,hl ;where to put pop bc ld a,c or a ld hl,lb_p00 jr z,lb_sk11 ld hl,33 add hl,de dec a jr z,lb_sk11 ld hl,16 add hl,de lb_sk11: ld b,h ld c,l ;where to get ld hl,33 add hl,de ex de,hl ;where to put pop hl ;pop offset pointer ld a,(bc) add a,(hl) ld (de),a inc bc inc de inc hl ld a,(bc) adc a,(hl) ld (de),a inc bc inc de inc hl ld a,(bc) adc a,(hl) ld (de),a inc bc inc de inc hl ld a,(bc) adc a,(hl) ld (de),a xor a pop ix ret ;.area _DATA lb_p00: db 0,0,0,0 ;--- end of proc SECTION CODE ;--- proc ltell ; ; char _Ltell(FD fd, long *where); -- DOS1, DOS2 ; PUBLIC _Ltell _Ltell: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) pop ix call _iltell ld l,a ld h,0 ret PUBLIC _iltell _iltell: push ix ld a,(__os_ver) dec a dec a jr z,lb_tl2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_tl1 ; MSXDOS1 lb_tl2a: pop ix ld (__io_errno),a ret ; lb_tl2: push de ld a,1 ld b,l ld hl,0 ld de,0 ld c,0x4A call 5 pop ix ld (ix+0),l ld (ix+1),h ld (ix+2),e ld (ix+3),d jr lb_tl2a ; lb_tl1: push de call _get_fd ld de,33 add hl,de pop de ld bc,4 ldir xor a pop ix ret ;--- end of proc ;--- proc getcwd ; ; char GetCWD(char *buf, int size); -- DOS1, DOS2 ; PUBLIC _GetCWD _GetCWD: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld c,(ix+6) ld b,(ix+7) pop ix call _igetcwd ld l,a ld h,0 ret PUBLIC _igetcwd _igetcwd: push ix push hl push bc ld c,0x19 call 5 ld l,a ld a,(__os_ver) dec a dec a jr z,lb_gc2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_gc1 ; MSXDOS1 lb_gc3: pop bc pop de ld hl,(0xF34D) push de ldir dec de lb_gc0: xor a ld (de),a pop hl pop ix ret ; lb_gc1: pop bc pop de push de ld a,'A' add a,l ld (de),a inc de ld a,':' ld (de),a inc de jr lb_gc0 ; lb_gc2: ld b,l ld de,(0xF34D) ld c,0x59 call 5 jr lb_gc3 ;--- end of proc ;--- proc REMOVE ; ; char Remove(char *filename) -- DOS1, DOS2 ; PUBLIC _Remove _Remove: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix call _iremove ld l,a ld h,0 ret PUBLIC _iremove _iremove: ld a,(__os_ver) dec a dec a jr z,lb_re2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_re1 ; MSXDOS1 lb_re3: push ix call 5 pop ix ld (__io_errno),a ret lb_re2: ex de,hl ld c,0x4D ld hl,0 jr lb_re3 lb_re1: ld de,_xfcb call __setupfcb ld de,_xfcb ld c,0x13 jr lb_re3 ;--- end of proc ;--- proc RENAME ; ; char Rename(char *old_name, char *new_name); -- DOS1, DOS2 ; PUBLIC _Rename _Rename: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) pop ix call _irename ld l,a ld h,0 ret PUBLIC _irename _irename: push ix ld a,(__os_ver) dec a dec a jr z,lb_ren2 ; MSXDOS2 can do the same as MSXDOS1 xor a jr lb_ren1 ; MSXDOS1 lb_ren0: call 5 pop ix ld (__io_errno),a ret ; lb_ren2: push hl push de ld c,0x4D call 5 ;delete new pop hl pop de ld c,0x4E jr lb_ren0 ; lb_ren1: push de ld de,_xfcb call __setupfcb pop hl ld de,_xfcb+16 call __setupfcb ld de,_xfcb+16 ld c,0x13 call 5 ld de,_xfcb ld c,0x17 jr lb_ren0 ;--- end of proc ;--- proc CHDIR ; ; char ChangeDir(char *path); -- DOS2 ; PUBLIC _ChangeDir _ChangeDir: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix call _ichdir ld l,a ld h,0 ret PUBLIC _ichdir _ichdir: ld a,(__os_ver) dec a dec a ret m ex de,hl ld c,0x5A push ix call 5 pop ix ld (__io_errno),a ret ;--- end of proc ;--- proc MKDIR ; ; char MakeDir(char *name); -- DOS2 ; PUBLIC _MakeDir _MakeDir: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix call _imkdir ld l,a ld h,0 ret PUBLIC _imkdir _imkdir: ld a,(__os_ver) dec a dec a ret m push ix ex de,hl jr z,lb_mkd1 ld c,0x41 lb_mkd0: call 5 pop ix ld (__io_errno),a ret ; lb_mkd1: ld bc,0x9044 xor a jr lb_mkd0 ;--- end of proc ;--- proc RMDIR ; ; char Removedir(char *name); -- DOS2 ; PUBLIC _RemoveDir _RemoveDir: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) pop ix call _irmdir ld l,a ld h,0 ret PUBLIC _irmdir _irmdir: ex de,hl ld a,(__os_ver) dec a dec a ret m push ix ld c,0x4D jr z,lb_rmd0 ld c,0x42 lb_rmd0: call 5 pop ix ld (__io_errno),a ret ;--- end of proc ;--- proc FINDFIRST ; ; char FindFirst(char *willcard, char *result, int attrib); -- DOS1, DOS2 ; ; For MSXDOS2 attrib: ; 0 - only non-hidden, non-system files ; PUBLIC _FindFirst _FindFirst: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) call _ifindfirst pop ix ld l,a ld h,0 ret _ifindfirst: ld a,(__os_ver) dec a dec a jr z,lb_ff2 ; MSXDOS2 can do the same as MSXDOS1 xor a ; other use FCB way to get filename, attribute is ignored push de ld de,_ffcb push de call __setupfcb pop de push de ld de,_xfcb ld c,0x1A call 5 pop de ld c,0x11 PUBLIC lb_ff1c lb_ff1c: call 5 ld (__io_errno),a pop de or a ret nz ld c,12 ld hl,_xfcb+1 lb_ffo: ld a,(hl) cp a, 32 jr z, lb_ff0 ld (de),a inc de lb_ff0: inc hl dec c jr z, lb_ffe ld a,4 cp c jr nz, lb_ffo ld a, '.' ld (de),a inc de jr lb_ffo lb_ffe: dec de ld a,(de) cp '.' jr nz, lb_ffe2 inc de lb_ffe2: xor a ld (de),a ret lb_ff2: push de ld c,0x40 ld b,c ld d,h ld e,l PUBLIC lb_ff2c lb_ff2c: xor a ld h,a ld l,a ld ix, _xfcb call 5 ld (__io_errno),a pop de or a ret nz ld hl, _xfcb+1 lb_ff2a: ld a, (hl) ld (de),a inc hl inc de or a jr nz, lb_ff2a ret ;--- end of proc ;--- proc FINDNEXT ; ; char FindNext(char *result); -- DOS1, DOS2 ; ; PUBLIC _FindNext _FindNext: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld c,(ix+6) ld b,(ix+7) call _ifindnext pop ix ld l,a ld h,0 ret _ifindnext: push hl ld a,(__os_ver) dec a dec a jr z,lb_fn2 ; MSXDOS2 can do the same as MSXDOS1 xor a ld c,0x12 jr lb_ff1c lb_fn2: ld c,0x41 jr lb_ff2c ;--- end of proc ;--- proc setdisk ; ; void SetDisk(int diskno) ; PUBLIC _SetDisk _SetDisk: push ix ld ix,0 add ix,sp ld a,(ix+4) ld e,a ld c,0xE call 5 pop ix ret ;--- end of proc ;--- proc getdisk ; ; int GetDisk(); ; PUBLIC _GetDisk _GetDisk: push ix ld c,0x19 call 5 ld h,0 ld l,a pop ix ret ;--- end of proc ; ; Diskload - load binary file from disk to RAM. ; ; Compile on SDCC for MSX ; SECTION CODE PUBLIC _DiskLoad _DiskLoad: push ix ld ix,0 add ix,sp ld l,(ix+4) ld h,(ix+5) ld e,(ix+6) ld d,(ix+7) ld c,(ix+8) ld b,(ix+9) push bc push de ld a,1 ld (loadflag),a ; prepare FCB push hl ld hl,f_fcb ld de,f_fn push de ld bc,36 xor a ld (hl),a ldir pop de pop hl ; copy filename into FCB ld bc,11 ldir ; open file for reading ld de,f_fcb ld c, 0xF call 5 ld hl,1 ld (f_groot),hl dec hl ld (f_blok),hl ld (f_blok+2),hl ld hl,(f_bleng) ; obtain file size pop de push hl ; set writing to RAM address ld c,0x1A call 5 pop hl ; read from file ld de,f_fcb ld c,0x27 call 5 ld (loadflag),a ;sets 0 if ok, 1 if can not load ld de,f_fcb ld c,0x10 call 5 pop bc ld (lb_calladdr),bc pop ix xor a or b or c jr z, lb_exit_ db 0xCD ; call to address lb_calladdr: db 0 db 0 lb_exit_: ld a,(loadflag) ld l,a ld h,0 ret ; .area _DATA loadflag: db 0 f_fcb: db 0 f_fn: db "???????????" ;11 chars dw 0 f_groot: dw 0 f_bleng: ds 17 f_blok: dw 0 dw 0 db 0 SECTION CODE ;
; A045681: Extension of Beatty sequence; complement of A045682. ; 0,1,2,3,4,6,7,8,9,11,12,13,14,16,17,18,19,21,22,23,24,25,26,28,29,30,31,33,34,35,36,38,39,40,41,43,44,45,46,47,48,50,51,52,53,55,56,57,58,60,61,62,63,65,66,67,68,69,70,72,73 mov $3,$0 add $0,1 mov $1,$0 div $0,3 div $1,2 mov $2,24 lpb $0 sub $0,5 trn $0,1 sub $1,1 lpe add $1,$2 div $1,2 sub $1,12 add $1,$3
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: HP PCL type print drivers FILE: graphicsPrintSwathPCL.asm AUTHOR: Dave Durran 1 March 1990 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 3/1/90 Initial revision Dave 3/92 moved from epson9 DESCRIPTION: $Id: graphicsPrintSwathPCL.asm,v 1.1 97/04/18 11:51:25 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintSwath %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Print a swath passed from spooler, all in one variable sized band, since the min band height is 1 scanline. CALLED BY: GLOBAL PASS: bp - PState segment dx.cx - VM file and block handle for Huge bitmap RETURN: carry - set if some transmission error DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 03/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintSwath proc far uses ax,cx,ds,bx,dx,si,di,ds,es .enter mov es, bp ; es -> PState ; load the bitmap header into the PState call LoadSwathHeader ; bitmap header into PS_swath ; load up the band width and height call PrLoadPstateVars ;set up the pstate band Vars. ; size and allocate a graphics data buffer call PrCreatePrintBuffers ;allocate the print buffer. ; get pointer to data clr ax mov es:[PS_curColorNumber],ax ;init offset into scanline. call DerefFirstScanline ; ds:si -> scan line zero ; dec cx ; see if only one band to do clc jcxz destroyBuffer ;set the graphics mode in the printer. clr bh mov bl,es:PS_mode mov ax,cs:[bx].pr_graphic_Res_Values mov di,offset pr_codes_SetGraphicRes call WriteNumCommand jc destroyBuffer scanlineLoop: call DerefAScanline call PrSendScanline ;print a line from this swath. jc destroyBuffer inc es:[PS_newScanNumber] ;point at next line down. loop scanlineLoop mov si,offset pr_codes_EndGraphics call SendCodeOut ; all done, kill the buffer and leave destroyBuffer: pushf call PrDestroyPrintBuffers ;get rid of print buffer space. popf ; no errors .leave ret PrintSwath endp
; A086348: On a 3 X 3 board, number of n-move routes of chess king ending in the central square. ; Submitted by Christian Krause ; 1,8,32,168,784,3840,18432,89216,430336,2078720,10035200,48457728,233967616,1129709568,5454692352,26337640448,127169265664,614027755520,2964787822592,14315262836736 mov $2,$0 add $2,1 seq $2,110048 ; Expansion of 1/((2*x+1)*(1-4*x-4*x^2)). mov $0,$2 div $0,2
; A001008: Numerators of harmonic numbers H(n) = Sum_{i=1..n} 1/i. ; Submitted by Christian Krause ; 1,3,11,25,137,49,363,761,7129,7381,83711,86021,1145993,1171733,1195757,2436559,42142223,14274301,275295799,55835135,18858053,19093197,444316699,1347822955,34052522467,34395742267,312536252003,315404588903,9227046511387,9304682830147,290774257297357,586061125622639,53676090078349,54062195834749,54437269998109,54801925434709,2040798836801833,2053580969474233,2066035355155033,2078178381193813,85691034670497533,12309312989335019,532145396070491417,5884182435213075787,5914085889685464427 mov $1,1 lpb $0 mov $2,$0 sub $0,1 add $2,1 mul $3,$2 add $3,$1 mul $1,$2 lpe add $1,$3 gcd $3,$1 div $1,$3 mov $0,$1
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: et sw=2 ts=2 fdm=marker */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsEUCKRProber.h" void nsEUCKRProber::Reset(void) { mCodingSM->Reset(); mState = eDetecting; mDistributionAnalyser.Reset(mIsPreferredLanguage); //mContextAnalyser.Reset(); } nsProbingState nsEUCKRProber::HandleData(const char* aBuf, PRUint32 aLen) { nsSMState codingState; for (PRUint32 i = 0; i < aLen; i++) { codingState = mCodingSM->NextState(aBuf[i]); if (codingState == eItsMe) { mState = eFoundIt; break; } if (codingState == eStart) { PRUint32 charLen = mCodingSM->GetCurrentCharLen(); if (i == 0) { mLastChar[1] = aBuf[0]; mDistributionAnalyser.HandleOneChar(mLastChar, charLen); } else mDistributionAnalyser.HandleOneChar(aBuf+i-1, charLen); } } mLastChar[0] = aBuf[aLen-1]; if (mState == eDetecting) if (mDistributionAnalyser.GotEnoughData() && GetConfidence() > SHORTCUT_THRESHOLD) mState = eFoundIt; // else // mDistributionAnalyser.HandleData(aBuf, aLen); return mState; } float nsEUCKRProber::GetConfidence(void) { float distribCf = mDistributionAnalyser.GetConfidence(); return (float)distribCf; }
; ; ZX Spectrum specific routines ; ; int zx_betadisk(); ; ; The result is: ; - 0 (false) if the Beta 128 Disk Interface is missing ; - 1 (true) if the Beta 128 Disk Interface is connected ; ; It has the side effect of enabling the TRDOS System variables ; ; ; $Id: zx_betadisk.asm,v 1.1 2008/06/29 08:25:47 aralbrec Exp $ ; XLIB zx_betadisk LIB trdos_installed zx_betadisk: ld hl,16384 ld a,(hl) push af ld (hl),201 ; ret instruction call 15619 pop af ld (16384),a jp trdos_installed
; A262617: First differences of A256266. ; 0,6,12,6,24,18,12,6,48,42,36,30,24,18,12,6,96,90,84,78,72,66,60,54,48,42,36,30,24,18,12,6,192,186,180,174,168,162,156,150,144,138,132,126,120,114,108,102,96,90,84,78,72,66,60,54,48,42,36,30,24,18,12,6,384,378,372,366,360,354,348,342,336,330,324,318 mul $0,8 mov $2,$0 div $2,2 lpb $2,1 sub $1,7 add $3,7 trn $4,$1 lpb $4,1 mov $1,$3 sub $4,$4 lpe sub $2,1 add $4,5 lpe div $1,28 mul $1,6
<% from pwnlib.shellcraft.amd64.linux import syscall %> <%page args="fd, iovec, count"/> <%docstring> Invokes the syscall writev. See 'man 2 writev' for more information. Arguments: fd(int): fd iovec(iovec): iovec count(int): count </%docstring> ${syscall('SYS_writev', fd, iovec, count)}
; A047623: Numbers that are congruent to {1, 3, 5} mod 8. ; 1,3,5,9,11,13,17,19,21,25,27,29,33,35,37,41,43,45,49,51,53,57,59,61,65,67,69,73,75,77,81,83,85,89,91,93,97,99,101,105,107,109,113,115,117,121,123,125,129,131,133,137,139,141,145,147,149,153,155,157,161,163,165,169,171,173,177,179,181,185,187,189,193,195,197,201,203,205,209,211,213,217,219,221,225,227,229,233,235,237,241,243,245,249,251,253,257,259,261,265,267,269,273,275,277,281,283,285,289,291,293,297,299,301,305,307,309,313,315,317,321,323,325,329,331,333,337,339,341,345,347,349,353,355,357,361,363,365,369,371,373,377,379,381,385,387,389,393,395,397,401,403,405,409,411,413,417,419,421,425,427,429,433,435,437,441,443,445,449,451,453,457,459,461,465,467,469,473,475,477,481,483,485,489,491,493,497,499,501,505,507,509,513,515,517,521,523,525,529,531,533,537,539,541,545,547,549,553,555,557,561,563,565,569,571,573,577,579,581,585,587,589,593,595,597,601,603,605,609,611,613,617,619,621,625,627,629,633,635,637,641,643,645,649,651,653,657,659,661,665 mov $1,$0 div $1,3 add $1,$0 mul $1,2 add $1,1
/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * macro_rules/parse.cpp * - macro_rules! evaluation (expansion) */ #include <common.hpp> #include "macro_rules.hpp" #include <parse/parseerror.hpp> #include <parse/ttstream.hpp> #include <parse/common.hpp> #include <limits.h> #include "pattern_checks.hpp" #include <parse/interpolated_fragment.hpp> #include <ast/expr.hpp> #include <ast/crate.hpp> #include <hir/hir.hpp> // HIR::Crate // Map of: LoopIndex=>(Path=>Count) typedef std::map<unsigned, std::map< std::vector<unsigned>, unsigned > > loop_counts_t; class ParameterMappings { /// A particular captured fragment struct CapturedVal { unsigned int num_uses; // Number of times this var will be used unsigned int num_used; // Number of times it has been used InterpolatedFragment frag; }; /// A single layer of the capture set TAGGED_UNION(CaptureLayer, Vals, (Vals, ::std::vector<CapturedVal>), (Nested, ::std::vector<CaptureLayer>) ); /// Represents the fragments captured for a name struct CapturedVar { CaptureLayer top_layer; friend ::std::ostream& operator<<(::std::ostream& os, const CapturedVar& x) { os << "CapturedVar { " << x.top_layer << " }"; return os; } }; loop_counts_t m_loop_counts; ::std::vector<CapturedVar> m_mappings; unsigned m_layer_count; public: ParameterMappings(): m_layer_count(0) { } ParameterMappings(ParameterMappings&&) = default; const ::std::vector<CapturedVar>& mappings() const { return m_mappings; } void dump() const { DEBUG("m_mappings = {" << m_mappings << "}"); } size_t layer_count() const { return m_layer_count+1; } void set_loop_counts(loop_counts_t loop_counts) { for(const auto& e : loop_counts) { DEBUG(e.first << ": {" << e.second << "}"); } m_loop_counts = std::move(loop_counts); } void insert(unsigned int name_index, const ::std::vector<unsigned int>& iterations, InterpolatedFragment data); InterpolatedFragment* get(const ::std::vector<unsigned int>& iterations, unsigned int name_idx); unsigned int get_loop_repeats(const ::std::vector<unsigned int>& iterations, unsigned int loop_idx) const; /// Increment the number of times a particular fragment will be used void inc_count(const ::std::vector<unsigned int>& iterations, unsigned int name_idx); /// Decrement the number of times a particular fragment is used (returns true if there are still usages remaining) bool dec_count(const ::std::vector<unsigned int>& iterations, unsigned int name_idx); friend ::std::ostream& operator<<(::std::ostream& os, const CapturedVal& x) { os << x.frag; return os; } friend ::std::ostream& operator<<(::std::ostream& os, const CaptureLayer& x) { TU_MATCH(CaptureLayer, (x), (e), (Vals, os << "[" << e << "]"; ), (Nested, os << "{" << e << "}"; ) ) return os; } private: CapturedVal& get_cap(const ::std::vector<unsigned int>& iterations, unsigned int name_idx); }; class MacroPatternStream { const ::std::vector<SimplePatEnt>& m_simple_ents; size_t m_cur_pos; bool m_last_was_cond; bool m_condition_met; ::std::vector<bool> m_condition_history; const ::std::vector<bool>* m_condition_replay; size_t m_condition_replay_pos; // Currently processed loop indexes ::std::vector<unsigned int> m_current_loops; // Iteration index of each active loop level ::std::vector<unsigned int> m_loop_iterations; loop_counts_t m_loop_counts; bool m_peek_cache_valid = false; const SimplePatEnt* m_peek_cache; public: MacroPatternStream(const ::std::vector<SimplePatEnt>& ents, const ::std::vector<bool>* condition_replay=nullptr): m_simple_ents(ents), m_cur_pos(0), m_last_was_cond(false), m_condition_replay(condition_replay), m_condition_replay_pos(0) { } size_t cur_pos() const { return m_cur_pos; } /// Get the next pattern entry const SimplePatEnt& next(); const SimplePatEnt& peek() { if( !m_peek_cache_valid ) { m_peek_cache = &next(); m_peek_cache_valid = true; } return *m_peek_cache; } /// Inform the stream that the `if` rule that was just returned succeeded void if_succeeded(); /// Get the current loop iteration count const ::std::vector<unsigned int>& get_loop_iters() const { return m_loop_iterations; } ::std::vector<bool> take_history() { return ::std::move(m_condition_history); } loop_counts_t take_loop_counts() { return ::std::move(m_loop_counts); } }; // === Prototypes === unsigned int Macro_InvokeRules_MatchPattern(const Span& sp, const MacroRules& rules, TokenTree input, const AST::Crate& crate, AST::Module& mod, ParameterMappings& bound_tts); void Macro_InvokeRules_CountSubstUses(ParameterMappings& bound_tts, const ::std::vector<MacroExpansionEnt>& contents); // ------------------------------------ // ParameterMappings // ------------------------------------ void ParameterMappings::insert(unsigned int name_index, const ::std::vector<unsigned int>& iterations, InterpolatedFragment data) { DEBUG("index="<<name_index << ", iterations=[" << iterations << "], data="<<data); if( name_index >= m_mappings.size() ) { m_mappings.resize( name_index + 1 ); } auto* layer = &m_mappings[name_index].top_layer; if( iterations.size() > 0 ) { for(unsigned int i = 0; i < iterations.size()-1; i ++ ) { auto iter = iterations[i]; if( layer->is_Vals() ) { assert( layer->as_Vals().size() == 0 ); *layer = CaptureLayer::make_Nested({}); } auto& e = layer->as_Nested(); while( e.size() < iter ) { DEBUG("- Skipped iteration " << e.size()); e.push_back( CaptureLayer::make_Nested({}) ); } if(e.size() == iter) { e.push_back( CaptureLayer::make_Vals({}) ); } else { if( e.size() > iter ) { DEBUG("ERROR: Iterations ran backwards? - " << e.size() << " > " << iter); } } layer = &e[iter]; } ASSERT_BUG(Span(), layer->as_Vals().size() == iterations.back(), "Capture count mismatch with iteration index - iterations=[" << iterations << "]"); } else { assert(layer->as_Vals().size() == 0); } layer->as_Vals().push_back( CapturedVal { 0,0, mv$(data) } ); } ParameterMappings::CapturedVal& ParameterMappings::get_cap(const ::std::vector<unsigned int>& iterations, unsigned int name_idx) { DEBUG("(iterations=[" << iterations << "], name_idx=" << name_idx << ")"); auto& e = m_mappings.at(name_idx); //DEBUG("- e = " << e); auto* layer = &e.top_layer; // - If the top layer is a 1-sized set of values, unconditionally return it TU_IFLET(CaptureLayer, (*layer), Vals, e, if( e.size() == 1 ) { return e[0]; } if( e.size() == 0 ) { BUG(Span(), "Attempting to get binding for empty capture - #" << name_idx); } ) for(const auto iter : iterations) { TU_MATCH(CaptureLayer, (*layer), (e), (Vals, ASSERT_BUG(Span(), iter < e.size(), "Iteration index " << iter << " outside of range " << e.size() << " (values)"); return e.at(iter); ), (Nested, ASSERT_BUG(Span(), iter < e.size(), "Iteration index " << iter << " outside of range " << e.size() << " (nest)"); layer = &e.at(iter); ) ) } ERROR(Span(), E0000, "Variable #" << name_idx << " is still repeating at this level (" << iterations.size() << ")"); } InterpolatedFragment* ParameterMappings::get(const ::std::vector<unsigned int>& iterations, unsigned int name_idx) { return &get_cap(iterations, name_idx).frag; } unsigned int ParameterMappings::get_loop_repeats(const ::std::vector<unsigned int>& iterations, unsigned int loop_idx) const { const auto& list = m_loop_counts.at(loop_idx); // Iterate the list, find the first prefix match of `iterations` // - `iterations` should always be longer or equal in length to every entry in `list` //auto ranges = list.equal_range(iterations); for(const auto& e : list) { ASSERT_BUG(Span(), e.first.size() <= iterations.size(), "Loop " << loop_idx << " iteration path [" << e.first << "] larger than query path [" << iterations << "]"); if( std::equal(e.first.begin(), e.first.end(), iterations.begin()) ) { return e.second; } } BUG(Span(), "Loop " << loop_idx << " cannot find an iteration count for path [" << iterations << "]"); } void ParameterMappings::inc_count(const ::std::vector<unsigned int>& iterations, unsigned int name_idx) { auto& cap = get_cap(iterations, name_idx); assert(cap.num_used == 0); cap.num_uses += 1; } bool ParameterMappings::dec_count(const ::std::vector<unsigned int>& iterations, unsigned int name_idx) { auto& cap = get_cap(iterations, name_idx); assert(cap.num_used < cap.num_uses); cap.num_used += 1; return (cap.num_used < cap.num_uses); } // ------------------------------------ // MacroPatternStream // ------------------------------------ const SimplePatEnt& MacroPatternStream::next() { if( m_peek_cache_valid ) { m_peek_cache_valid = false; return *m_peek_cache; } for(;;) { // If not replaying, and the previous entry was a conditional, record the result of that conditional if( !m_condition_replay && m_last_was_cond ) { m_condition_history.push_back(m_condition_met); } m_last_was_cond = false; // End of list? return End entry if( m_cur_pos == m_simple_ents.size() ) { static SimplePatEnt END = SimplePatEnt::make_End({}); return END; } const auto& cur_ent = m_simple_ents[m_cur_pos]; // If replaying, and this is a conditional if( m_condition_replay && cur_ent.is_If() ) { // Skip the conditional (following its target or just skipping over) if( (*m_condition_replay)[m_condition_replay_pos++] ) m_cur_pos = cur_ent.as_If().jump_target; else m_cur_pos += 1; continue ; } m_cur_pos += 1; TU_MATCH_HDRA( (cur_ent), {) default: if( cur_ent.is_If() ) { m_last_was_cond = true; m_condition_met = false; } return cur_ent; TU_ARMA(End, _e) BUG(Span(), "Unexpected End"); TU_ARMA(Jump, e) m_cur_pos = e.jump_target; TU_ARMA(LoopStart, e) { m_current_loops.push_back(e.index); m_loop_iterations.push_back(0); } TU_ARMA(LoopNext, _e) { m_loop_iterations.back() += 1; } TU_ARMA(LoopEnd, _e) { assert(!m_loop_iterations.empty()); assert(!m_current_loops.empty()); auto loop_index = m_current_loops.back(); auto num_iter = m_loop_iterations.back(); m_loop_iterations.pop_back(); m_current_loops.pop_back(); // Save this iteration count if replaying if( m_condition_replay ) { m_loop_counts[loop_index].insert( std::make_pair(m_loop_iterations, num_iter) ); } } } } } void MacroPatternStream::if_succeeded() { assert(m_cur_pos > 0); assert(m_cur_pos <= m_simple_ents.size()); assert(m_last_was_cond); const auto& ent = m_simple_ents[m_cur_pos-1]; ASSERT_BUG(Span(), ent.is_If(), "Expected If when calling `if_succeeded`, got " << ent); const auto& e = ent.as_If(); ASSERT_BUG(Span(), e.jump_target < m_simple_ents.size(), "Jump target " << e.jump_target << " out of range " << m_simple_ents.size()); m_cur_pos = e.jump_target; m_condition_met = true; } // ---------------------------------------------------------------- /// State for MacroExpander and Macro_InvokeRules_CountSubstUses class MacroExpandState { const ::std::vector<MacroExpansionEnt>& m_root_contents; const ParameterMappings& m_mappings; struct t_offset { unsigned read_pos; unsigned loop_index; unsigned max_index; }; /// Layer states : Index and Iteration ::std::vector< t_offset > m_offsets; ::std::vector< unsigned int> m_iterations; /// Cached pointer to the current layer const ::std::vector<MacroExpansionEnt>* m_cur_ents; // For faster lookup. public: MacroExpandState(const ::std::vector<MacroExpansionEnt>& contents, const ParameterMappings& mappings): m_root_contents(contents), m_mappings(mappings), m_offsets({ {0,0,0} }), m_cur_ents(&m_root_contents) { } // Returns a pointer to the next entry to expand, or nullptr if the end is reached // - NOTE: When a Loop entry is returned, the separator token should be emitted const MacroExpansionEnt* next_ent(); const ::std::vector<unsigned int> iterations() const { return m_iterations; } unsigned int top_pos() const { if(m_offsets.empty()) return 0; return m_offsets[0].read_pos; } private: const MacroExpansionEnt& getCurLayerEnt() const; const ::std::vector<MacroExpansionEnt>* getCurLayer() const; }; // ---------------------------------------------------------------- class MacroExpander: public TokenStream { // Used to track a specific invocation for debugging static unsigned s_next_log_index; unsigned m_log_index; const RcString m_macro_filename; const RcString m_crate_name; Span m_invocation_span; AST::Edition m_invocation_edition; ParameterMappings m_mappings; MacroExpandState m_state; Token m_next_token; // used for inserting a single token into the stream ::std::unique_ptr<TTStreamO> m_ttstream; AST::Edition m_source_edition; Ident::Hygiene m_hygiene; public: MacroExpander(const MacroExpander& x) = delete; MacroExpander( const ::std::string& macro_name, const Span& sp, AST::Edition edition, const Ident::Hygiene& parent_hygiene, const ::std::vector<MacroExpansionEnt>& contents, ParameterMappings mappings, RcString crate_name, AST::Edition source_edition ): TokenStream(ParseState()), m_log_index(s_next_log_index++), m_macro_filename( FMT("Macro:" << macro_name) ), m_crate_name( mv$(crate_name) ), m_invocation_span( sp ), m_invocation_edition( edition ), m_mappings( mv$(mappings) ), m_state( contents, m_mappings ), m_source_edition( source_edition ), m_hygiene( Ident::Hygiene::new_scope_chained(parent_hygiene) ) { } Position getPosition() const override; Span outerSpan() const override { return m_invocation_span; } Ident::Hygiene realGetHygiene() const override; AST::Edition realGetEdition() const override; Token realGetToken() override; }; unsigned MacroExpander::s_next_log_index = 0; void Macro_InitDefaults() { } InterpolatedFragment Macro_HandlePatternCap(TokenStream& lex, MacroPatEnt::Type type) { Token tok; switch(type) { case MacroPatEnt::PAT_TOKEN: BUG(lex.point_span(), "Encountered PAT_TOKEN when handling capture"); case MacroPatEnt::PAT_LOOP: BUG(lex.point_span(), "Encountered PAT_LOOP when handling capture"); case MacroPatEnt::PAT_TT: if( GET_TOK(tok, lex) == TOK_EOF ) throw ParseError::Unexpected(lex, TOK_EOF); else PUTBACK(tok, lex); return InterpolatedFragment( Parse_TT(lex, false) ); case MacroPatEnt::PAT_PAT: return InterpolatedFragment( Parse_Pattern(lex, AllowOrPattern::No) ); case MacroPatEnt::PAT_TYPE: return InterpolatedFragment( Parse_Type(lex) ); case MacroPatEnt::PAT_EXPR: return InterpolatedFragment( InterpolatedFragment::EXPR, Parse_Expr0(lex).release() ); case MacroPatEnt::PAT_STMT: return InterpolatedFragment( InterpolatedFragment::STMT, Parse_Stmt(lex).release() ); case MacroPatEnt::PAT_PATH: return InterpolatedFragment( Parse_Path(lex, PATH_GENERIC_TYPE) ); // non-expr mode case MacroPatEnt::PAT_BLOCK: return InterpolatedFragment( InterpolatedFragment::BLOCK, Parse_ExprBlockNode(lex).release() ); case MacroPatEnt::PAT_META: return InterpolatedFragment( Parse_MetaItem(lex) ); case MacroPatEnt::PAT_ITEM: { assert( lex.parse_state().module ); const auto& cur_mod = *lex.parse_state().module; return InterpolatedFragment( Parse_Mod_Item_S(lex, cur_mod.m_file_info, cur_mod.path(), AST::AttributeList{}) ); } break; case MacroPatEnt::PAT_IDENT: // NOTE: Any reserved word is also valid as an ident GET_TOK(tok, lex); if( Token::type_is_rword(tok.type()) ) return InterpolatedFragment( TokenTree(lex.get_edition(), lex.get_hygiene(), tok) ); else { CHECK_TOK(tok, TOK_IDENT); return InterpolatedFragment( TokenTree(lex.get_edition(), lex.get_hygiene(), tok) ); } case MacroPatEnt::PAT_VIS: return InterpolatedFragment( Parse_Publicity(lex, /*allow_restricted=*/true) ); case MacroPatEnt::PAT_LIFETIME: GET_CHECK_TOK(tok, lex, TOK_LIFETIME); return InterpolatedFragment( TokenTree(lex.get_edition(), lex.get_hygiene(), tok) ); case MacroPatEnt::PAT_LITERAL: GET_TOK(tok, lex); switch(tok.type()) { case TOK_INTEGER: case TOK_FLOAT: case TOK_STRING: case TOK_BYTESTRING: case TOK_RWORD_TRUE: case TOK_RWORD_FALSE: break; default: throw ParseError::Unexpected(lex, tok, {TOK_INTEGER, TOK_FLOAT, TOK_STRING, TOK_BYTESTRING, TOK_RWORD_TRUE, TOK_RWORD_FALSE}); } return InterpolatedFragment( TokenTree(lex.get_edition(), lex.get_hygiene(), tok) ); } throw ""; } /// Parse the input TokenTree according to the `macro_rules!` patterns and return a token stream of the replacement ::std::unique_ptr<TokenStream> Macro_InvokeRules(const char *name, const MacroRules& rules, const Span& sp, TokenTree input, const AST::Crate& crate, AST::Module& mod) { TRACE_FUNCTION_F("'" << name << "', " << input); DEBUG("rules.m_hygiene = " << rules.m_hygiene); ParameterMappings bound_tts; unsigned int rule_index = Macro_InvokeRules_MatchPattern(sp, rules, mv$(input), crate, mod, bound_tts); const auto& rule = rules.m_rules.at(rule_index); DEBUG( "Using macro '" << name << "' #" << rule_index << " - " << rule.m_contents.size() << " rule contents with " << bound_tts.mappings().size() << " bound values"); for( unsigned int i = 0; i < ::std::min( bound_tts.mappings().size(), rule.m_param_names.size() ); i ++ ) { DEBUG("- #" << i << " " << rule.m_param_names.at(i) << " = [" << bound_tts.mappings()[i] << "]"); } //bound_tts.dump(); // Run through the expansion counting the number of times each fragment is used Macro_InvokeRules_CountSubstUses(bound_tts, rule.m_contents); TokenStream* ret_ptr = new MacroExpander( name, sp, crate.m_edition, rules.m_hygiene, rule.m_contents, mv$(bound_tts), rules.m_source_crate == "" ? crate.m_crate_name_real : rules.m_source_crate, rules.m_source_crate == "" ? crate.m_edition : crate.m_extern_crates.at(rules.m_source_crate).m_hir->m_edition ); return ::std::unique_ptr<TokenStream>( ret_ptr ); } // Collection of functions that consume a specific fragment type from a token stream // - Does very loose consuming namespace { // Class that provides read-only iteration over a TokenTree class TokenStreamRO { const TokenTree& m_tt; ::std::vector<size_t> m_offsets; size_t m_active_offset; Token m_faked_next; size_t m_consume_count; public: TokenStreamRO(const TokenTree& tt): m_tt(tt), m_active_offset(0), m_consume_count(0) { assert( ! m_tt.is_token() ); if( m_tt.size() == 0 ) { m_active_offset = 0; DEBUG("TOK_EOF"); } else { const auto* cur_tree = &m_tt; while( !cur_tree->is_token() ) { cur_tree = &(*cur_tree)[0]; m_offsets.push_back(0); } assert(m_offsets.size() > 0); m_offsets.pop_back(); m_active_offset = 0; DEBUG(next_tok()); } } TokenStreamRO clone() const { return TokenStreamRO(*this); } enum eTokenType next() const { return next_tok().type(); } const Token& next_tok() const { static Token eof_token = TOK_EOF; if( m_faked_next.type() != TOK_NULL ) { return m_faked_next; } if( m_offsets.empty() && m_active_offset == m_tt.size() ) { //DEBUG(m_consume_count << " " << eof_token << "(EOF)"); return eof_token; } else { const auto* cur_tree = &m_tt; for(auto idx : m_offsets) cur_tree = &(*cur_tree)[idx]; const auto& rv = (*cur_tree)[m_active_offset].tok(); //DEBUG(m_consume_count << " " << rv); return rv; } } void consume() { if( m_faked_next.type() != TOK_NULL ) { m_faked_next = Token(TOK_NULL); return ; } if( m_offsets.empty() && m_active_offset == m_tt.size() ) throw ::std::runtime_error("Attempting to consume EOS"); DEBUG(m_consume_count << " " << next_tok()); m_consume_count ++; for(;;) { const auto* cur_tree = &m_tt; for(auto idx : m_offsets) cur_tree = &(*cur_tree)[idx]; m_active_offset ++; // If reached the end of a tree... if(m_active_offset == cur_tree->size()) { // If the end of the root is reached, return (leaving the state indicating EOS) if( m_offsets.empty() ) return ; // Pop and continue m_active_offset = m_offsets.back(); m_offsets.pop_back(); } else { // Dig into nested trees while( !(*cur_tree)[m_active_offset].is_token() ) { cur_tree = &(*cur_tree)[m_active_offset]; m_offsets.push_back(m_active_offset); m_active_offset = 0; } DEBUG("-> " << next_tok()); return ; } } } void consume_and_push(eTokenType ty) { consume(); m_faked_next = Token(ty); } // Consumes if the current token is `ty`, otherwise doesn't and returns false bool consume_if(eTokenType ty) { if(next() == ty) { consume(); return true; } else { return false; } } /// Returns the position in the stream (number of tokens that have been consumed) size_t position() const { return m_consume_count; } }; // Consume an entire TT bool consume_tt(TokenStreamRO& lex) { TRACE_FUNCTION; switch(lex.next()) { case TOK_EOF: case TOK_PAREN_CLOSE: case TOK_BRACE_CLOSE: case TOK_SQUARE_CLOSE: return false; case TOK_PAREN_OPEN: lex.consume(); while(lex.next() != TOK_PAREN_CLOSE) consume_tt(lex); lex.consume(); break; case TOK_SQUARE_OPEN: lex.consume(); while(lex.next() != TOK_SQUARE_CLOSE) consume_tt(lex); lex.consume(); break; case TOK_BRACE_OPEN: lex.consume(); while(lex.next() != TOK_BRACE_CLOSE) consume_tt(lex); lex.consume(); break; default: lex.consume(); break; } return true; } bool consume_tt_angle(TokenStreamRO& lex) { TRACE_FUNCTION; unsigned int level = (lex.next() == TOK_DOUBLE_LT ? 2 : 1); // Seek until enouh matching '>'s are seen // TODO: Can expressions show up on this context? lex.consume(); for(;;) { if( lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT ) { level += (lex.next() == TOK_DOUBLE_LT ? 2 : 1); } else if( lex.next() == TOK_GT || lex.next() == TOK_DOUBLE_GT ) { assert(level > 0); if( lex.next() == TOK_DOUBLE_GT ) { if( level == 1 ) { lex.consume_and_push(TOK_GT); return true; } level -= 2; } else { level -= 1; } if( level == 0 ) break; } else if( lex.next() == TOK_EOF ) { return false; } else { } // Consume TTs separately if( lex.next() == TOK_PAREN_OPEN ) { consume_tt(lex); } else { lex.consume(); } } // Consume closing token lex.consume(); return true; } // Consume a path bool consume_path(TokenStreamRO& lex, bool type_mode=false) { TRACE_FUNCTION; switch(lex.next()) { case TOK_INTERPOLATED_PATH: lex.consume(); return true; case TOK_RWORD_SELF: lex.consume(); // Allow a lone `self` (it's referring to the current object) if( lex.next() != TOK_DOUBLE_COLON ) return true; break; case TOK_RWORD_CRATE: lex.consume(); // Require `::` after `crate` break; case TOK_RWORD_SUPER: lex.consume(); if( lex.next() != TOK_DOUBLE_COLON ) return false; break; case TOK_DOUBLE_COLON: break; case TOK_IDENT: lex.consume(); if( type_mode && (lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT) ) ; // Allow a lone ident else if( lex.next() != TOK_DOUBLE_COLON ) return true; else ; break; case TOK_LT: case TOK_DOUBLE_LT: if( !consume_tt_angle(lex) ) return false; if( lex.next() != TOK_DOUBLE_COLON ) return false; break; default: return false; } if( type_mode && (lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT) ) { if( !consume_tt_angle(lex) ) return false; } while(lex.next() == TOK_DOUBLE_COLON) { lex.consume(); if( lex.next() == TOK_STRING ) { lex.consume(); } else if( !type_mode && (lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT) ) { if( !consume_tt_angle(lex) ) return false; } else if( lex.next() == TOK_IDENT ) { lex.consume(); if( type_mode && (lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT) ) { if( !consume_tt_angle(lex) ) return false; } } else { return false; } } return true; } bool consume_type(TokenStreamRO& lex) { TRACE_FUNCTION; switch(lex.next()) { case TOK_UNDERSCORE: lex.consume(); return true; case TOK_INTERPOLATED_TYPE: lex.consume(); return true; case TOK_PAREN_OPEN: case TOK_SQUARE_OPEN: return consume_tt(lex); case TOK_IDENT: if( TARGETVER_LEAST_1_29 && lex.next_tok().ident().name == "dyn" ) lex.consume(); if(0) case TOK_RWORD_DYN: lex.consume(); case TOK_RWORD_CRATE: case TOK_RWORD_SUPER: case TOK_RWORD_SELF: case TOK_DOUBLE_COLON: case TOK_INTERPOLATED_PATH: if( !consume_path(lex, true) ) return false; if( lex.consume_if(TOK_EXCLAM) ) { if( lex.next() != TOK_PAREN_OPEN && lex.next() != TOK_SQUARE_OPEN && lex.next() != TOK_BRACE_OPEN ) return false; if( !consume_tt(lex) ) return false; } return true; case TOK_AMP: case TOK_DOUBLE_AMP: lex.consume(); lex.consume_if(TOK_LIFETIME); lex.consume_if(TOK_RWORD_MUT); return consume_type(lex); case TOK_STAR: lex.consume(); if( lex.consume_if(TOK_RWORD_MUT) ) ; else if( lex.consume_if(TOK_RWORD_CONST) ) ; else return false; return consume_type(lex); case TOK_EXCLAM: lex.consume(); return true; case TOK_RWORD_UNSAFE: lex.consume(); if(lex.next() == TOK_RWORD_EXTERN) { case TOK_RWORD_EXTERN: lex.consume(); lex.consume_if(TOK_STRING); } if( lex.next() != TOK_RWORD_FN ) return false; case TOK_RWORD_FN: lex.consume(); if( lex.next() != TOK_PAREN_OPEN ) return false; if( !consume_tt(lex) ) return false; if( lex.consume_if(TOK_THINARROW) ) { consume_type(lex); } return true; default: return false; } } bool consume_pat(TokenStreamRO& lex) { TRACE_FUNCTION; if(lex.next() == TOK_RWORD_REF || lex.next() == TOK_RWORD_MUT ) { lex.consume_if(TOK_RWORD_REF); lex.consume_if(TOK_RWORD_MUT); if( !lex.consume_if(TOK_IDENT) ) return false; if( !lex.consume_if(TOK_AT) ) return true; } if( lex.consume_if(TOK_INTERPOLATED_PATTERN) ) return true; for(;;) { if( lex.consume_if(TOK_UNDERSCORE) ) return true; switch(lex.next()) { case TOK_IDENT: case TOK_RWORD_SUPER: case TOK_RWORD_SELF: case TOK_DOUBLE_COLON: case TOK_INTERPOLATED_PATH: consume_path(lex); if( lex.next() == TOK_BRACE_OPEN ) { return consume_tt(lex); } else if( lex.next() == TOK_PAREN_OPEN ) { return consume_tt(lex); } else if( lex.next() == TOK_EXCLAM ) { lex.consume(); return consume_tt(lex); } break; case TOK_RWORD_BOX: lex.consume(); return consume_pat(lex); case TOK_AMP: case TOK_DOUBLE_AMP: lex.consume(); lex.consume_if(TOK_RWORD_MUT); return consume_pat(lex); case TOK_PAREN_OPEN: case TOK_SQUARE_OPEN: return consume_tt(lex); case TOK_STRING: case TOK_INTEGER: case TOK_FLOAT: lex.consume(); break; default: return false; } if(lex.consume_if(TOK_AT)) continue; // ... or ..= if( lex.consume_if(TOK_TRIPLE_DOT) || lex.consume_if(TOK_DOUBLE_DOT_EQUAL) ) { switch(lex.next()) { case TOK_IDENT: case TOK_RWORD_SUPER: case TOK_RWORD_SELF: case TOK_DOUBLE_COLON: case TOK_INTERPOLATED_PATH: consume_path(lex); break; case TOK_STRING: case TOK_INTEGER: case TOK_FLOAT: lex.consume(); break; default: return false; } } return true; } } // Consume an expression bool consume_expr(TokenStreamRO& lex, bool no_struct_lit=false) { TRACE_FUNCTION; bool cont; // Closures if( lex.next() == TOK_RWORD_MOVE || lex.next() == TOK_PIPE || lex.next() == TOK_DOUBLE_PIPE ) { lex.consume_if(TOK_RWORD_MOVE); if( lex.consume_if(TOK_PIPE) ) { do { if( lex.next() == TOK_PIPE ) break; consume_pat(lex); if(lex.consume_if(TOK_COLON)) { consume_type(lex); } } while(lex.consume_if(TOK_COMMA)); if( !lex.consume_if(TOK_PIPE) ) return false; } else { lex.consume(); } if(lex.consume_if(TOK_THINARROW)) { if( !consume_type(lex) ) return false; } return consume_expr(lex); } do { bool inner_cont; do { inner_cont = true; switch(lex.next()) { case TOK_STAR: // Deref case TOK_DASH: // Negate case TOK_EXCLAM: // Invert case TOK_RWORD_BOX: // Box lex.consume(); break; case TOK_AMP: lex.consume(); lex.consume_if(TOK_RWORD_MUT); break; default: inner_cont = false; break; } } while(inner_cont); // :: -> path // ident -> path // '<' -> path // '(' -> tt // '[' -> tt switch(lex.next()) { case TOK_RWORD_CONTINUE: case TOK_RWORD_BREAK: lex.consume(); lex.consume_if(TOK_LIFETIME); if(0) case TOK_RWORD_RETURN: lex.consume(); switch(lex.next()) { case TOK_EOF: case TOK_SEMICOLON: case TOK_COMMA: case TOK_PAREN_CLOSE: case TOK_BRACE_CLOSE: case TOK_SQUARE_CLOSE: break; default: if( !consume_expr(lex) ) return false; break; } break; case TOK_IDENT: case TOK_INTERPOLATED_PATH: case TOK_DOUBLE_COLON: case TOK_RWORD_SELF: case TOK_RWORD_SUPER: case TOK_RWORD_CRATE: case TOK_LT: case TOK_DOUBLE_LT: if( !consume_path(lex) ) return false; if( lex.next() == TOK_BRACE_OPEN && !no_struct_lit ) consume_tt(lex); else if( lex.consume_if(TOK_EXCLAM) ) { if( lex.consume_if(TOK_IDENT) ) { // yay? } consume_tt(lex); } break; case TOK_INTERPOLATED_EXPR: lex.consume(); break; case TOK_INTEGER: case TOK_FLOAT: case TOK_STRING: case TOK_BYTESTRING: case TOK_RWORD_TRUE: case TOK_RWORD_FALSE: lex.consume(); break; // Possibly a left-open (or full-open) range literal case TOK_DOUBLE_DOT: case TOK_DOUBLE_DOT_EQUAL: case TOK_TRIPLE_DOT: break; case TOK_RWORD_UNSAFE: lex.consume(); if(lex.next() != TOK_BRACE_OPEN ) return false; case TOK_PAREN_OPEN: case TOK_SQUARE_OPEN: case TOK_BRACE_OPEN: consume_tt(lex); break; // TODO: Do these count for "expr"? case TOK_RWORD_FOR: lex.consume(); if( !consume_pat(lex) ) return false; if( !lex.consume_if(TOK_RWORD_IN) ) return false; if( !consume_expr(lex, true) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; if( !consume_tt(lex) ) return false; break; case TOK_RWORD_MATCH: lex.consume(); // TODO: Parse _without_ consuming a struct literal if( !consume_expr(lex, true) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; if( !consume_tt(lex) ) return false; break; case TOK_RWORD_WHILE: lex.consume(); if( !consume_expr(lex, true) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; if( !consume_tt(lex) ) return false; break; case TOK_RWORD_LOOP: lex.consume(); if( lex.next() != TOK_BRACE_OPEN ) return false; consume_tt(lex); break; case TOK_RWORD_IF: while(1) { assert(lex.next() == TOK_RWORD_IF); lex.consume(); if(lex.next() == TOK_RWORD_LET) { lex.consume(); if( !consume_pat(lex) ) return false; if( lex.next() != TOK_EQUAL ) return false; lex.consume(); } if( !consume_expr(lex, true) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; consume_tt(lex); if( lex.next() != TOK_RWORD_ELSE ) break; lex.consume(); if( lex.next() != TOK_RWORD_IF ) { if( lex.next() != TOK_BRACE_OPEN ) return false; consume_tt(lex); break; } } break; default: return false; } do { inner_cont = true; // '.' ident/int switch( lex.next() ) { case TOK_QMARK: lex.consume(); break; case TOK_DOT: lex.consume(); if( lex.consume_if(TOK_IDENT) ) { if( lex.consume_if(TOK_DOUBLE_COLON) ) { if( !(lex.next() == TOK_LT || lex.next() == TOK_DOUBLE_LT) ) return false; if( !consume_tt_angle(lex) ) return false; } } else if( lex.consume_if(TOK_INTEGER) ) ; else return false; break; // '[' -> tt case TOK_SQUARE_OPEN: // '(' -> tt case TOK_PAREN_OPEN: consume_tt(lex); break; default: inner_cont = false; break ; } } while(inner_cont); if( lex.consume_if(TOK_COLON) ) { consume_type(lex); } while( lex.consume_if(TOK_RWORD_AS) ) { consume_type(lex); } cont = true; switch(lex.next()) { case TOK_PLUS: case TOK_DASH: case TOK_SLASH: case TOK_STAR: case TOK_PERCENT: case TOK_DOUBLE_LT: case TOK_DOUBLE_GT: case TOK_PIPE: case TOK_AMP: case TOK_CARET: case TOK_LT: case TOK_GT: case TOK_LTE: case TOK_GTE: case TOK_DOUBLE_EQUAL: case TOK_EXCLAM_EQUAL: case TOK_DOUBLE_AMP: case TOK_DOUBLE_PIPE: case TOK_DOUBLE_DOT_EQUAL: case TOK_TRIPLE_DOT: lex.consume(); break; case TOK_DOUBLE_DOT: lex.consume(); DEBUG("TOK_DOUBLE_DOT => " << lex.next()); switch(lex.next()) { case TOK_EOF: return true; case TOK_COMMA: case TOK_SEMICOLON: case TOK_BRACE_CLOSE: case TOK_PAREN_CLOSE: case TOK_SQUARE_CLOSE: cont = false; break; default: break; } break; case TOK_EQUAL: case TOK_PLUS_EQUAL: case TOK_DASH_EQUAL: case TOK_SLASH_EQUAL: case TOK_STAR_EQUAL: case TOK_PERCENT_EQUAL: case TOK_AMP_EQUAL: case TOK_PIPE_EQUAL: lex.consume(); break; default: cont = false; break; } } while(cont); return true; } bool consume_stmt(TokenStreamRO& lex) { TRACE_FUNCTION; if( lex.consume_if(TOK_INTERPOLATED_STMT) ) { return true; } if( lex.consume_if(TOK_RWORD_LET) ) { if( !consume_pat(lex) ) return false; if( lex.consume_if(TOK_COLON) ) { if( !consume_type(lex) ) return false; } if( lex.consume_if(TOK_EQUAL) ) { if( !consume_expr(lex) ) return false; } return true; } else { if( !consume_expr(lex) ) return false; return true; } } bool consume_vis(TokenStreamRO& lex) { TRACE_FUNCTION; if( lex.consume_if(TOK_INTERPOLATED_VIS) || lex.consume_if(TOK_RWORD_CRATE) ) { return true; } else if( lex.consume_if(TOK_RWORD_PUB) ) { if( lex.next() == TOK_PAREN_OPEN ) { return consume_tt(lex); } return true; } else { // HACK: If the next character is nothing interesting, then force no match? // - TODO: Instead, have `:vis` force a deepeer check if( lex.next() == TOK_EOF || lex.next() == TOK_PAREN_CLOSE || lex.next() == TOK_BRACE_CLOSE || lex.next() == TOK_SQUARE_CLOSE ) { return false; } // NOTE: This is kinda true? return true; } } bool consume_item(TokenStreamRO& lex) { TRACE_FUNCTION; struct H { static bool maybe_generics(TokenStreamRO& lex) { if(lex.next() == TOK_LT) { if( !consume_tt_angle(lex) ) return false; } return true; } static bool maybe_where(TokenStreamRO& lex) { if(lex.next() == TOK_RWORD_WHERE) { TODO(Span(), "where in macro eval"); } return true; } }; while( lex.next() == TOK_HASH ) { lex.consume(); lex.consume_if(TOK_EXCLAM); consume_tt(lex); } // Interpolated items if( lex.consume_if(TOK_INTERPOLATED_ITEM) ) return true; // Macro invocation // TODO: What about `union!` as a macro? Needs to be handled below if( (lex.next() == TOK_IDENT && lex.next_tok().ident().name != "union") || lex.next() == TOK_RWORD_SELF || lex.next() == TOK_RWORD_SUPER || lex.next() == TOK_DOUBLE_COLON ) { if( !consume_path(lex) ) return false; if( !lex.consume_if(TOK_EXCLAM) ) return false; lex.consume_if(TOK_IDENT); bool need_semicolon = (lex.next() != TOK_BRACE_OPEN); consume_tt(lex); if( need_semicolon ) { if( !lex.consume_if(TOK_SEMICOLON) ) return false; } return true; } // Normal items if( !consume_vis(lex) ) return false; if(lex.next() == TOK_RWORD_UNSAFE) lex.consume(); DEBUG("Check item: " << lex.next_tok()); switch(lex.next()) { case TOK_RWORD_USE: // Lazy mode while( lex.next() != TOK_SEMICOLON ) lex.consume(); lex.consume(); break; case TOK_RWORD_MOD: lex.consume(); if( !lex.consume_if(TOK_IDENT) ) return false; if( lex.consume_if(TOK_SEMICOLON) ) ; else if( lex.next() == TOK_BRACE_OPEN ) { if( !consume_tt(lex) ) return false; } else { return false; } break; // impl [Foo for] Bar { ... } case TOK_RWORD_IMPL: lex.consume(); if( !H::maybe_generics(lex) ) return false; if( !consume_type(lex) ) return false; if( lex.consume_if(TOK_RWORD_FOR) ) { if( !consume_type(lex) ) return false; } if( !H::maybe_where(lex) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; return consume_tt(lex); // type Foo case TOK_RWORD_TYPE: lex.consume(); if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if( !lex.consume_if(TOK_EQUAL) ) return false; if( !consume_type(lex) ) return false; if( !lex.consume_if(TOK_SEMICOLON) ) return false; break; // static FOO case TOK_RWORD_STATIC: lex.consume(); if( !lex.consume_if(TOK_IDENT) ) return false; if( !lex.consume_if(TOK_COLON) ) return false; if( !consume_type(lex) ) return false; if( !lex.consume_if(TOK_EQUAL) ) return false; if( !consume_expr(lex) ) return false; if( !lex.consume_if(TOK_SEMICOLON) ) return false; break; case TOK_RWORD_STRUCT: lex.consume(); if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if( !H::maybe_where(lex) ) return false; if( lex.consume_if(TOK_SEMICOLON) ) ; else if( lex.next() == TOK_PAREN_OPEN ) { if( !consume_tt(lex) ) return false; if( !lex.consume_if(TOK_SEMICOLON) ) return false; } else if( lex.next() == TOK_BRACE_OPEN ) { if( !consume_tt(lex) ) return false; } else return false; break; case TOK_RWORD_ENUM: lex.consume(); if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if( !H::maybe_where(lex) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; return consume_tt(lex); case TOK_IDENT: if( lex.next_tok().ident().name == "union" ) { lex.consume(); if( lex.next() == TOK_EXCLAM ) { bool need_semicolon = (lex.next() != TOK_BRACE_OPEN); consume_tt(lex); if( need_semicolon ) { if( !lex.consume_if(TOK_SEMICOLON) ) return false; } return true; } else { if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if( !H::maybe_where(lex) ) return false; if( lex.next() != TOK_BRACE_OPEN ) return false; return consume_tt(lex); } } else if( lex.next_tok().ident().name == "auto" ) { lex.consume(); if( lex.consume_if(TOK_RWORD_TRAIT) ) { goto trait; } else { return false; } } else { return false; } break; // const [unsafe] [extern] fn // const FOO case TOK_RWORD_CONST: lex.consume(); if(lex.next() == TOK_RWORD_UNSAFE) lex.consume(); if(lex.next() == TOK_RWORD_EXTERN) lex.consume(); if( lex.consume_if(TOK_RWORD_FN) ) { goto fn; } else { if( !lex.consume_if(TOK_IDENT) ) return false; if( !lex.consume_if(TOK_COLON) ) return false; consume_type(lex); if( !lex.consume_if(TOK_EQUAL) ) return false; consume_expr(lex); if( !lex.consume_if(TOK_SEMICOLON) ) return false; } break; case TOK_RWORD_TRAIT: lex.consume(); trait: if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if(lex.next() != TOK_BRACE_OPEN) return false; if( !consume_tt(lex) ) return false; break; case TOK_RWORD_EXTERN: lex.consume(); if( lex.consume_if(TOK_RWORD_CRATE) ) { if( !lex.consume_if(TOK_IDENT) ) return false; if( lex.consume_if(TOK_RWORD_AS) ) { if( !lex.consume_if(TOK_IDENT) ) return false; } if( !lex.consume_if(TOK_SEMICOLON) ) return false; break; } lex.consume_if(TOK_STRING); if( lex.next() == TOK_BRACE_OPEN ) { return consume_tt(lex); } if( ! lex.consume_if(TOK_RWORD_FN) ) return false; goto fn; case TOK_RWORD_FN: lex.consume(); fn: if( !lex.consume_if(TOK_IDENT) ) return false; if( !H::maybe_generics(lex) ) return false; if(lex.next() != TOK_PAREN_OPEN) return false; if( !consume_tt(lex) ) return false; if( lex.consume_if(TOK_THINARROW) ) { if( !consume_type(lex) ) return false; } if( !H::maybe_where(lex) ) return false; if( lex.consume_if(TOK_SEMICOLON) ) { // TODO: Is this actually valid? break; } else if( lex.next() == TOK_BRACE_OPEN ) { if( !consume_tt(lex) ) return false; } else { return false; } break; default: return false; } return true; } bool consume_from_frag(TokenStreamRO& lex, MacroPatEnt::Type type) { TRACE_FUNCTION_F(type); switch(type) { case MacroPatEnt::PAT_TOKEN: case MacroPatEnt::PAT_LOOP: BUG(Span(), "Encountered " << type << " in consume_from_frag");; case MacroPatEnt::PAT_BLOCK: if( lex.next() == TOK_BRACE_OPEN ) { return consume_tt(lex); } else if( lex.next() == TOK_INTERPOLATED_BLOCK ) { lex.consume(); } else { return false; } break; case MacroPatEnt::PAT_IDENT: if( lex.next() == TOK_IDENT || Token::type_is_rword(lex.next()) ) { lex.consume(); } else { return false; } break; case MacroPatEnt::PAT_TT: return consume_tt(lex); case MacroPatEnt::PAT_PATH: return consume_path(lex, true); case MacroPatEnt::PAT_TYPE: return consume_type(lex); case MacroPatEnt::PAT_EXPR: return consume_expr(lex); case MacroPatEnt::PAT_STMT: return consume_stmt(lex); case MacroPatEnt::PAT_PAT: return consume_pat(lex); case MacroPatEnt::PAT_META: if( lex.next() == TOK_INTERPOLATED_META ) { lex.consume(); } else if( lex.next() == TOK_IDENT ) { lex.consume(); switch(lex.next()) { case TOK_PAREN_OPEN: return consume_tt(lex); case TOK_EQUAL: lex.consume(); return consume_expr(lex); default: break; } } else { return false; } break; case MacroPatEnt::PAT_ITEM: return consume_item(lex); case MacroPatEnt::PAT_VIS: return consume_vis(lex); case MacroPatEnt::PAT_LIFETIME: return lex.consume_if(TOK_LIFETIME); case MacroPatEnt::PAT_LITERAL: switch(lex.next()) { case TOK_INTEGER: case TOK_FLOAT: case TOK_STRING: case TOK_RWORD_TRUE: case TOK_RWORD_FALSE: lex.consume(); return true; default: return false; } } return true; } } unsigned int Macro_InvokeRules_MatchPattern(const Span& sp, const MacroRules& rules, TokenTree input, const AST::Crate& crate, AST::Module& mod, ParameterMappings& bound_tts) { TRACE_FUNCTION_F(rules.m_rules.size() << " options"); ASSERT_BUG(sp, rules.m_rules.size() > 0, "Empty macro_rules set"); ::std::vector< ::std::pair<size_t, ::std::vector<bool>> > matches; ::std::vector< std::pair<size_t, eTokenType> > fail_pos; for(size_t i = 0; i < rules.m_rules.size(); i ++) { auto lex = TokenStreamRO(input); auto arm_stream = MacroPatternStream(rules.m_rules[i].m_pattern); bool fail = false; for(;;) { const auto pos = arm_stream.cur_pos(); const auto& pat = arm_stream.next(); // NOTE: The positions seen by this aren't fully sequential, as `next` steps over jumps/loop control ops DEBUG("Arm " << i << " @" << pos << " " << pat); if(pat.is_End()) { if( lex.next() != TOK_EOF ) fail = true; break; } else if( const auto* e = pat.opt_If() ) { auto lc = lex.clone(); bool rv = true; for(const auto& check : e->ents) { if( check.ty != MacroPatEnt::PAT_TOKEN ) { if( !consume_from_frag(lc, check.ty) ) { rv = false; break; } } else { if( lc.next_tok() != check.tok ) { rv = false; break; } if( lc.next_tok() != TOK_EOF ) lc.consume(); } } if( rv == e->is_equal ) { DEBUG("- Succeeded"); arm_stream.if_succeeded(); } } else if( const auto* e = pat.opt_ExpectTok() ) { const auto& tok = lex.next_tok(); DEBUG("Arm " << i << " @" << pos << " ExpectTok(" << *e << ") == " << tok); if( tok != *e ) { fail = true; break; } lex.consume(); } else if( const auto* e = pat.opt_ExpectPat() ) { DEBUG("Arm " << i << " @" << pos << " ExpectPat(" << e->type << " => $" << e->idx << ")"); if( !consume_from_frag(lex, e->type) ) { fail = true; break; } } else { // Unreachable. } } if( ! fail ) { matches.push_back( ::std::make_pair(i, arm_stream.take_history()) ); DEBUG(i << " MATCHED"); } else { DEBUG(i << " FAILED"); fail_pos.push_back( std::make_pair(lex.position(), lex.next()) ); } } if( matches.size() == 0 ) { // ERROR! // TODO: Keep track of where each arm failed. TODO(sp, "No arm matched - " << fail_pos); } else { // yay! // NOTE: There can be multiple arms active, take the first. auto i = matches[0].first; const auto& history = matches[0].second; DEBUG("Evalulating arm " << i); auto lex = TTStreamO(sp, ParseState(), mv$(input)); lex.parse_state().crate = &crate; SET_MODULE(lex, mod); auto arm_stream = MacroPatternStream(rules.m_rules[i].m_pattern, &history); struct Capture { unsigned int binding_idx; ::std::vector<unsigned int> iterations; unsigned int cap_idx; }; ::std::vector<InterpolatedFragment> captures; ::std::vector<Capture> capture_info; for(;;) { const auto& pat = arm_stream.next(); DEBUG(i << " " << pat); if(pat.is_End()) { break; } else if( pat.is_If() ) { BUG(sp, "Unexpected If pattern during final matching - " << pat); } else if( const auto* e = pat.opt_ExpectTok() ) { auto tok = lex.getToken(); DEBUG(i << " ExpectTok(" << *e << ") == " << tok); if( tok != *e ) { ERROR(sp, E0000, "Expected token " << *e << " in match arm, got " << tok); break; } } else if( const auto* e = pat.opt_ExpectPat() ) { DEBUG(i << " ExpectPat(" << e->type << " => $" << e->idx << ")"); auto cap = Macro_HandlePatternCap(lex, e->type); unsigned int cap_idx = captures.size(); captures.push_back( mv$(cap) ); capture_info.push_back( Capture { e->idx, arm_stream.get_loop_iters(), cap_idx } ); } else { // Unreachable. } } for(const auto& cap : capture_info) { bound_tts.insert( cap.binding_idx, cap.iterations, mv$(captures[cap.cap_idx]) ); } bound_tts.set_loop_counts(arm_stream.take_loop_counts()); return i; } } void Macro_InvokeRules_CountSubstUses(ParameterMappings& bound_tts, const ::std::vector<MacroExpansionEnt>& contents) { TRACE_FUNCTION; MacroExpandState state(contents, bound_tts); while(const auto* ent_ptr = state.next_ent()) { DEBUG(*ent_ptr); TU_IFLET(MacroExpansionEnt, (*ent_ptr), NamedValue, e, if( e >> 30 ) { } else { // Increment a counter in `bound_tts` bound_tts.inc_count(state.iterations(), e); } ) } } Position MacroExpander::getPosition() const { // TODO: Return the attached position of the last fetched token return Position(m_macro_filename, 0, m_state.top_pos()); } AST::Edition MacroExpander::realGetEdition() const { if( m_ttstream ) { return m_ttstream->get_edition(); } else { return m_source_edition; } } Ident::Hygiene MacroExpander::realGetHygiene() const { if( m_ttstream ) { return m_ttstream->get_hygiene(); } else { return m_hygiene; } } Token MacroExpander::realGetToken() { // Use m_next_token first if( m_next_token.type() != TOK_NULL ) { DEBUG("[" << m_log_index << "] m_next_token = " << m_next_token); return mv$(m_next_token); } // Then try m_ttstream if( m_ttstream.get() ) { Token rv = m_ttstream->getToken(); DEBUG("[" << m_log_index << "] TTStream present: " << rv); if( rv.type() != TOK_EOF ) return rv; m_ttstream.reset(); } // Loop to handle case where $crate expands to nothing while( const auto* next_ent_ptr = m_state.next_ent() ) { const auto& ent = *next_ent_ptr; TU_MATCH_HDRA( (ent), {) TU_ARMA(Token, e) { switch(e.type()) { case TOK_IDENT: case TOK_LIFETIME: { // Rewrite the hygiene of an ident such that idents in the macro explicitly are unique for each expansion // - Appears to be a valid option. auto ident = e.ident(); if( ident.hygiene == m_hygiene.get_parent() ) { ident.hygiene = m_hygiene; } auto rv = Token(e.type(), std::move(ident)); DEBUG("[" << m_log_index << "] Updated hygine: " << rv); return rv; break; } default: DEBUG("[" << m_log_index << "] Raw token: " << e); return e.clone(); } } TU_ARMA(NamedValue, e) { if( e >> 30 ) { switch( e & 0x3FFFFFFF ) { // - XXX: Hack for $crate special name case 0: DEBUG("[" << m_log_index << "] Crate name hack"); if( m_crate_name == "" ) { if( this->edition_after(AST::Edition::Rust2018) ) { return Token(TOK_RWORD_CRATE); } } else { m_next_token = Token(TOK_STRING, ::std::string(m_crate_name.c_str())); return Token(TOK_DOUBLE_COLON); } break; default: BUG(Span(), "Unknown macro metavar"); } } else { auto* frag = m_mappings.get(m_state.iterations(), e); ASSERT_BUG(this->point_span(), frag, "Cannot find '" << e << "' for " << m_state.iterations()); bool can_steal = ( m_mappings.dec_count(m_state.iterations(), e) == false ); DEBUG("[" << m_log_index << "] Insert replacement #" << e << " = " << *frag); if( frag->m_type == InterpolatedFragment::TT ) { auto res_tt = can_steal ? mv$(frag->as_tt()) : frag->as_tt().clone(); m_ttstream.reset( new TTStreamO(this->outerSpan(), ParseState(), mv$(res_tt)) ); return m_ttstream->getToken(); } else { if( can_steal ) { return Token(Token::TagTakeIP(), mv$(*frag) ); } else { // Clones return Token( *frag ); } } } } TU_ARMA(Loop, e) { //assert( e.joiner.tok() != TOK_NULL ); DEBUG("[" << m_log_index << "] Loop joiner " << e.joiner); return e.joiner; } } } DEBUG("EOF"); return Token(TOK_EOF); } const MacroExpansionEnt* MacroExpandState::next_ent() { //DEBUG("ofs " << m_offsets << " < " << m_root_contents.size()); // Check offset of lowest layer while(m_offsets.size() > 0) { unsigned int layer = m_offsets.size() - 1; const auto& ents = *m_cur_ents; // Obtain current read position in layer, and increment size_t idx = m_offsets.back().read_pos++; // Check if limit has been reached if( idx < ents.size() ) { // - If not, just handle the next entry const auto& ent = ents[idx]; TU_MATCH_HDRA( (ent), {) TU_ARMA(Token, e) { return &ent; } TU_ARMA(NamedValue, e) { return &ent; } TU_ARMA(Loop, e) { assert( !e.controlling_input_loops.empty() ); unsigned int num_repeats = m_mappings.get_loop_repeats(m_iterations, *e.controlling_input_loops.begin()); for(auto loop_ident : e.controlling_input_loops) { if( loop_ident == *e.controlling_input_loops.begin() ) continue ; unsigned int this_repeats = m_mappings.get_loop_repeats(m_iterations, loop_ident); if( this_repeats != num_repeats ) { // TODO: Get the variables involved, or the pattern+output spans ERROR(Span(), E0000, "Mismatch in loop iterations: " << this_repeats << " != " << num_repeats); } } DEBUG("Looping " << num_repeats << " times based on {" << e.controlling_input_loops << "}"); // 2. If it's going to repeat, start the loop if( num_repeats > 0 ) { m_offsets.push_back( {0, 0, num_repeats} ); m_iterations.push_back( 0 ); m_cur_ents = getCurLayer(); } } } // Fall through for loop } else if( layer > 0 ) { // - Otherwise, restart/end loop and fall through DEBUG("layer = " << layer << ", m_iterations = " << m_iterations); auto& cur_ofs = m_offsets.back(); DEBUG("Layer #" << layer << " Cur: " << cur_ofs.loop_index << ", Max: " << cur_ofs.max_index); if( cur_ofs.loop_index + 1 < cur_ofs.max_index ) { m_iterations.back() ++; DEBUG("Restart layer"); cur_ofs.read_pos = 0; cur_ofs.loop_index ++; auto& loop_layer = getCurLayerEnt(); if( loop_layer.as_Loop().joiner.type() != TOK_NULL ) { DEBUG("- Separator token = " << loop_layer.as_Loop().joiner); return &loop_layer; } // Fall through and restart layer } else { DEBUG("Terminate layer"); // Terminate loop, fall through to lower layers m_offsets.pop_back(); m_iterations.pop_back(); // - Special case: End of macro, avoid issues if( m_offsets.size() == 0 ) break; m_cur_ents = getCurLayer(); } } else { DEBUG("Terminate evaluation"); m_offsets.pop_back(); assert( m_offsets.size() == 0 ); } } // while( m_offsets NONEMPTY ) return nullptr; } const MacroExpansionEnt& MacroExpandState::getCurLayerEnt() const { assert( m_offsets.size() > 1 ); const auto* ents = &m_root_contents; for( unsigned int i = 0; i < m_offsets.size()-2; i ++ ) { unsigned int ofs = m_offsets[i].read_pos; assert( ofs > 0 && ofs <= ents->size() ); ents = &(*ents)[ofs-1].as_Loop().entries; } return (*ents)[m_offsets[m_offsets.size()-2].read_pos-1]; } const ::std::vector<MacroExpansionEnt>* MacroExpandState::getCurLayer() const { assert( m_offsets.size() > 0 ); const auto* ents = &m_root_contents; for( unsigned int i = 0; i < m_offsets.size()-1; i ++ ) { unsigned int ofs = m_offsets[i].read_pos; //DEBUG(i << " ofs=" << ofs << " / " << ents->size()); assert( ofs > 0 && ofs <= ents->size() ); ents = &(*ents)[ofs-1].as_Loop().entries; //DEBUG("ents = " << ents); } return ents; }
; A088923: Duplicate of A011539. ; 9,19,29,39,49,59,69,79,89,90,91,92,93,94,95,96,97,98,99,109,119,129 mov $1,$0 mov $2,10 mov $3,$0 sub $3,4 mul $3,2 mov $4,$3 trn $4,$0 trn $2,$4 add $1,$2 mul $1,9 sub $1,81 add $1,$0
/****************************************************************************** @File PVRTModelPOD.cpp @Title PVRTModelPOD @Version @Copyright Copyright (c) Imagination Technologies Limited. @Platform ANSI compatible @Description Code to load POD files - models exported from MAX. ******************************************************************************/ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "PVRTGlobal.h" #if defined(BUILD_DX9) || defined(BUILD_DX10) || defined(BUILD_DX11) //#include "PVRTContext.h" // patched for cocos3d by Bill Hollings #endif #include "PVRTFixedPoint.h" #include "PVRTMatrix.h" #include "PVRTQuaternion.h" #include "PVRTVertex.h" #include "PVRTBoneBatch.h" #include "PVRTModelPOD.h" //#include "PVRTMisc.h" // patched for cocos3d by Bill Hollings #include "PVRTResourceFile.h" #include "PVRTTrans.h" /**************************************************************************** ** Defines ****************************************************************************/ #define PVRTMODELPOD_TAG_MASK (0x80000000) #define PVRTMODELPOD_TAG_START (0x00000000) #define PVRTMODELPOD_TAG_END (0x80000000) #define CFAH (1024) /**************************************************************************** ** Enumerations ****************************************************************************/ /*!**************************************************************************** @Struct EPODFileName @Brief Enum for the binary pod blocks ******************************************************************************/ enum EPODFileName { ePODFileVersion = 1000, ePODFileScene, ePODFileExpOpt, ePODFileHistory, ePODFileEndiannessMisMatch = -402456576, ePODFileColourBackground = 2000, ePODFileColourAmbient, ePODFileNumCamera, ePODFileNumLight, ePODFileNumMesh, ePODFileNumNode, ePODFileNumMeshNode, ePODFileNumTexture, ePODFileNumMaterial, ePODFileNumFrame, ePODFileCamera, // Will come multiple times ePODFileLight, // Will come multiple times ePODFileMesh, // Will come multiple times ePODFileNode, // Will come multiple times ePODFileTexture, // Will come multiple times ePODFileMaterial, // Will come multiple times ePODFileFlags, ePODFileFPS, ePODFileUserData, ePODFileMatName = 3000, ePODFileMatIdxTexDiffuse, ePODFileMatOpacity, ePODFileMatAmbient, ePODFileMatDiffuse, ePODFileMatSpecular, ePODFileMatShininess, ePODFileMatEffectFile, ePODFileMatEffectName, ePODFileMatIdxTexAmbient, ePODFileMatIdxTexSpecularColour, ePODFileMatIdxTexSpecularLevel, ePODFileMatIdxTexBump, ePODFileMatIdxTexEmissive, ePODFileMatIdxTexGlossiness, ePODFileMatIdxTexOpacity, ePODFileMatIdxTexReflection, ePODFileMatIdxTexRefraction, ePODFileMatBlendSrcRGB, ePODFileMatBlendSrcA, ePODFileMatBlendDstRGB, ePODFileMatBlendDstA, ePODFileMatBlendOpRGB, ePODFileMatBlendOpA, ePODFileMatBlendColour, ePODFileMatBlendFactor, ePODFileMatFlags, ePODFileMatUserData, ePODFileTexName = 4000, ePODFileNodeIdx = 5000, ePODFileNodeName, ePODFileNodeIdxMat, ePODFileNodeIdxParent, ePODFileNodePos, ePODFileNodeRot, ePODFileNodeScale, ePODFileNodeAnimPos, ePODFileNodeAnimRot, ePODFileNodeAnimScale, ePODFileNodeMatrix, ePODFileNodeAnimMatrix, ePODFileNodeAnimFlags, ePODFileNodeAnimPosIdx, ePODFileNodeAnimRotIdx, ePODFileNodeAnimScaleIdx, ePODFileNodeAnimMatrixIdx, ePODFileNodeUserData, ePODFileMeshNumVtx = 6000, ePODFileMeshNumFaces, ePODFileMeshNumUVW, ePODFileMeshFaces, ePODFileMeshStripLength, ePODFileMeshNumStrips, ePODFileMeshVtx, ePODFileMeshNor, ePODFileMeshTan, ePODFileMeshBin, ePODFileMeshUVW, // Will come multiple times ePODFileMeshVtxCol, ePODFileMeshBoneIdx, ePODFileMeshBoneWeight, ePODFileMeshInterleaved, ePODFileMeshBoneBatches, ePODFileMeshBoneBatchBoneCnts, ePODFileMeshBoneBatchOffsets, ePODFileMeshBoneBatchBoneMax, ePODFileMeshBoneBatchCnt, ePODFileMeshUnpackMatrix, ePODFileLightIdxTgt = 7000, ePODFileLightColour, ePODFileLightType, ePODFileLightConstantAttenuation, ePODFileLightLinearAttenuation, ePODFileLightQuadraticAttenuation, ePODFileLightFalloffAngle, ePODFileLightFalloffExponent, ePODFileCamIdxTgt = 8000, ePODFileCamFOV, ePODFileCamFar, ePODFileCamNear, ePODFileCamAnimFOV, ePODFileDataType = 9000, ePODFileN, ePODFileStride, ePODFileData }; /**************************************************************************** ** Structures ****************************************************************************/ struct SPVRTPODImpl { VERTTYPE fFrame; /*!< Frame number */ VERTTYPE fBlend; /*!< Frame blend (AKA fractional part of animation frame number) */ int nFrame; /*!< Frame number (AKA integer part of animation frame number) */ VERTTYPE *pfCache; /*!< Cache indicating the frames at which the matrix cache was filled */ PVRTMATRIX *pWmCache; /*!< Cache of world matrices */ PVRTMATRIX *pWmZeroCache; /*!< Pre-calculated frame 0 matrices */ bool bFromMemory; /*!< Was the mesh data loaded from memory? */ #ifdef _DEBUG PVRTint64 nWmTotal, nWmCacheHit, nWmZeroCacheHit; float fHitPerc, fHitPercZero; #endif }; /**************************************************************************** ** Local code: Memory allocation ****************************************************************************/ /*!*************************************************************************** @Function SafeAlloc @Input cnt @Output ptr @Return false if memory allocation failed @Description Allocates a block of memory. *****************************************************************************/ template <typename T> bool SafeAlloc(T* &ptr, size_t cnt) { _ASSERT(!ptr); if(cnt) { ptr = (T*)calloc(cnt, sizeof(T)); _ASSERT(ptr); if(!ptr) return false; } return true; } /*!*************************************************************************** @Function SafeRealloc @Modified ptr @Input cnt @Description Changes the size of a memory allocation. *****************************************************************************/ template <typename T> void SafeRealloc(T* &ptr, size_t cnt) { ptr = (T*)realloc(ptr, cnt * sizeof(T)); _ASSERT(ptr); } /**************************************************************************** ** Class: CPODData ****************************************************************************/ /*!*************************************************************************** @Function Reset @Description Resets the POD Data to NULL *****************************************************************************/ void CPODData::Reset() { eType = EPODDataFloat; n = 0; nStride = 0; FREE(pData); } // check32BitType and check16BitType are structs where only the specialisations have a standard declaration (complete type) // if this struct is instantiated with a different type then the compiler will choke on it // Place a line like: " check32BitType<channelType>(); " in a template function // to ensure it won't be called using a type of the wrong size. template<class T> struct check32BitType; template<> struct check32BitType<unsigned int> {}; template<> struct check32BitType<int> {}; template<> struct check32BitType<float> {}; template<class T> struct check16BitType; template<> struct check16BitType<unsigned short> {}; template<> struct check16BitType<short> {}; /*!*************************************************************************** Class: CSource *****************************************************************************/ class CSource { public: /*!*************************************************************************** @Function ~CSource @Description Destructor *****************************************************************************/ virtual ~CSource() {}; virtual bool Read(void* lpBuffer, const unsigned int dwNumberOfBytesToRead) = 0; virtual bool Skip(const unsigned int nBytes) = 0; template <typename T> bool Read(T &n) { return Read(&n, sizeof(T)); } template <typename T> bool Read32(T &n) { unsigned char ub[4]; if(Read(&ub, 4)) { unsigned int *pn = (unsigned int*) &n; *pn = (unsigned int) ((ub[3] << 24) | (ub[2] << 16) | (ub[1] << 8) | ub[0]); return true; } return false; } template <typename T> bool Read16(T &n) { unsigned char ub[2]; if(Read(&ub, 2)) { unsigned short *pn = (unsigned short*) &n; *pn = (unsigned short) ((ub[1] << 8) | ub[0]); return true; } return false; } bool ReadMarker(unsigned int &nName, unsigned int &nLen); template <typename T> bool ReadAfterAlloc(T* &lpBuffer, const unsigned int dwNumberOfBytesToRead) { if(!SafeAlloc(lpBuffer, dwNumberOfBytesToRead)) return false; return Read(lpBuffer, dwNumberOfBytesToRead); } template <typename T> bool ReadAfterAlloc32(T* &lpBuffer, const unsigned int dwNumberOfBytesToRead) { check32BitType<T>(); if(!SafeAlloc(lpBuffer, dwNumberOfBytesToRead/4)) return false; return ReadArray32((unsigned int*) lpBuffer, dwNumberOfBytesToRead / 4); } template <typename T> bool ReadArray32(T* pn, const unsigned int i32Size) { check32BitType<T>(); bool bRet = true; for(unsigned int i = 0; i < i32Size; ++i) bRet &= Read32(pn[i]); return bRet; } template <typename T> bool ReadAfterAlloc16(T* &lpBuffer, const unsigned int dwNumberOfBytesToRead) { check16BitType<T>(); if(!SafeAlloc(lpBuffer, dwNumberOfBytesToRead/2 )) return false; return ReadArray16((unsigned short*) lpBuffer, dwNumberOfBytesToRead / 2); } bool ReadArray16(unsigned short* pn, unsigned int i32Size) { bool bRet = true; for(unsigned int i = 0; i < i32Size; ++i) bRet &= Read16(pn[i]); return bRet; } }; bool CSource::ReadMarker(unsigned int &nName, unsigned int &nLen) { if(!Read32(nName)) return false; if(!Read32(nLen)) return false; return true; } /*!*************************************************************************** Class: CSourceStream *****************************************************************************/ class CSourceStream : public CSource { protected: CPVRTResourceFile* m_pFile; size_t m_BytesReadCount; public: /*!*************************************************************************** @Function CSourceStream @Description Constructor *****************************************************************************/ CSourceStream() : m_pFile(0), m_BytesReadCount(0) {} /*!*************************************************************************** @Function ~CSourceStream @Description Destructor *****************************************************************************/ virtual ~CSourceStream(); bool Init(const char * const pszFileName); bool Init(const char * const pData, const size_t i32Size); virtual bool Read(void* lpBuffer, const unsigned int dwNumberOfBytesToRead); virtual bool Skip(const unsigned int nBytes); }; /*!*************************************************************************** @Function ~CSourceStream @Description Destructor *****************************************************************************/ CSourceStream::~CSourceStream() { delete m_pFile; } /*!*************************************************************************** @Function Init @Input pszFileName Source file @Description Initialises the source stream with a file at the specified directory. *****************************************************************************/ bool CSourceStream::Init(const char * const pszFileName) { m_BytesReadCount = 0; if (m_pFile) { delete m_pFile; m_pFile = 0; } if(!pszFileName) return false; m_pFile = new CPVRTResourceFile(pszFileName); if (!m_pFile->IsOpen()) { delete m_pFile; m_pFile = 0; return false; } return true; } /*!*************************************************************************** @Function Init @Input pData Address of the source data @Input i32Size Size of the data (in bytes) @Description Initialises the source stream with the data at the specified directory. *****************************************************************************/ bool CSourceStream::Init(const char * pData, size_t i32Size) { m_BytesReadCount = 0; if (m_pFile) delete m_pFile; m_pFile = new CPVRTResourceFile(pData, i32Size); if (!m_pFile->IsOpen()) { delete m_pFile; m_pFile = 0; return false; } return true; } /*!*************************************************************************** @Function Read @Modified lpBuffer Buffer to write the data into @Input dwNumberOfBytesToRead Number of bytes to read @Description Reads specified number of bytes from the source stream into the output buffer. *****************************************************************************/ bool CSourceStream::Read(void* lpBuffer, const unsigned int dwNumberOfBytesToRead) { _ASSERT(lpBuffer); _ASSERT(m_pFile); if (m_BytesReadCount + dwNumberOfBytesToRead > m_pFile->Size()) return false; memcpy(lpBuffer, &((char*) m_pFile->DataPtr())[m_BytesReadCount], dwNumberOfBytesToRead); m_BytesReadCount += dwNumberOfBytesToRead; return true; } /*!*************************************************************************** @Function Skip @Input nBytes The number of bytes to skip @Description Skips the specified number of bytes of the source stream. *****************************************************************************/ bool CSourceStream::Skip(const unsigned int nBytes) { if (m_BytesReadCount + nBytes > m_pFile->Size()) return false; m_BytesReadCount += nBytes; return true; } #if defined(_WIN32) /*!*************************************************************************** Class: CSourceResource *****************************************************************************/ class CSourceResource : public CSource { protected: const unsigned char *m_pData; unsigned int m_nSize, m_nReadPos; public: bool Init(const TCHAR * const pszName); virtual bool Read(void* lpBuffer, const unsigned int dwNumberOfBytesToRead); virtual bool Skip(const unsigned int nBytes); }; /*!*************************************************************************** @Function Init @Input pszName The file extension of the resource file @Description Initialises the source resource from the data at the specified file extension. *****************************************************************************/ bool CSourceResource::Init(const TCHAR * const pszName) { HRSRC hR; HGLOBAL hG; // Find the resource hR = FindResource(GetModuleHandle(NULL), pszName, RT_RCDATA); if(!hR) return false; // How big is the resource? m_nSize = SizeofResource(NULL, hR); if(!m_nSize) return false; // Get a pointer to the resource data hG = LoadResource(NULL, hR); if(!hG) return false; m_pData = (unsigned char*)LockResource(hG); if(!m_pData) return false; m_nReadPos = 0; return true; } /*!*************************************************************************** @Function Read @Modified lpBuffer The buffer to write to @Input dwNumberOfBytesToRead The number of bytes to read @Description Reads data from the resource to the specified output buffer. *****************************************************************************/ bool CSourceResource::Read(void* lpBuffer, const unsigned int dwNumberOfBytesToRead) { if(m_nReadPos + dwNumberOfBytesToRead > m_nSize) return false; _ASSERT(lpBuffer); memcpy(lpBuffer, &m_pData[m_nReadPos], dwNumberOfBytesToRead); m_nReadPos += dwNumberOfBytesToRead; return true; } bool CSourceResource::Skip(const unsigned int nBytes) { if(m_nReadPos + nBytes > m_nSize) return false; m_nReadPos += nBytes; return true; } #endif /* _WIN32 */ /**************************************************************************** ** Local code: File writing ****************************************************************************/ /*!*************************************************************************** @Function WriteFileSafe @Input pFile @Input lpBuffer @Input nNumberOfBytesToWrite @Return true if successful @Description Writes data to a file, checking return codes. *****************************************************************************/ static bool WriteFileSafe(FILE *pFile, const void * const lpBuffer, const unsigned int nNumberOfBytesToWrite) { if(nNumberOfBytesToWrite) { size_t count = fwrite(lpBuffer, nNumberOfBytesToWrite, 1, pFile); return count == 1; } return true; } static bool WriteFileSafe16(FILE *pFile, const unsigned short * const lpBuffer, const unsigned int nSize) { if(nSize) { unsigned char ub[2]; bool bRet = true; for(unsigned int i = 0; i < nSize; ++i) { ub[0] = (unsigned char) lpBuffer[i]; ub[1] = lpBuffer[i] >> 8; bRet &= (fwrite(ub, 2, 1, pFile) == 1); } return bRet; } return true; } static bool WriteFileSafe32(FILE *pFile, const unsigned int * const lpBuffer, const unsigned int nSize) { if(nSize) { unsigned char ub[4]; bool bRet = true; for(unsigned int i = 0; i < nSize; ++i) { ub[0] = (unsigned char) (lpBuffer[i]); ub[1] = (unsigned char) (lpBuffer[i] >> 8); ub[2] = (unsigned char) (lpBuffer[i] >> 16); ub[3] = (unsigned char) (lpBuffer[i] >> 24); bRet &= (fwrite(ub, 4, 1, pFile) == 1); } return bRet; } return true; } /*!*************************************************************************** @Function WriteMarker @Input pFile @Input nName @Input bEnd @Input nLen Return true if successful @Description Write a marker to a POD file. If bEnd if false, it's a beginning marker, otherwise it's an end marker. *****************************************************************************/ static bool WriteMarker( FILE * const pFile, const unsigned int nName, const bool bEnd, const unsigned int nLen = 0) { unsigned int nMarker; bool bRet; _ASSERT((nName & ~PVRTMODELPOD_TAG_MASK) == nName); nMarker = nName | (bEnd ? PVRTMODELPOD_TAG_END : PVRTMODELPOD_TAG_START); bRet = WriteFileSafe32(pFile, &nMarker, 1); bRet &= WriteFileSafe32(pFile, &nLen, 1); return bRet; } /*!*************************************************************************** @Function WriteData @Input pFile @Input nName @Input pData @Input nLen @Return true if successful @Description Write nLen bytes of data from pData, bracketed by an nName begin/end markers. *****************************************************************************/ static bool WriteData( FILE * const pFile, const unsigned int nName, const void * const pData, const unsigned int nLen) { if(pData) { _ASSERT(nLen); if(!WriteMarker(pFile, nName, false, nLen)) return false; if(!WriteFileSafe(pFile, pData, nLen)) return false; if(!WriteMarker(pFile, nName, true)) return false; } return true; } /*!*************************************************************************** @Function WriteData16 @Input pFile @Input nName @Input pData @Input i32Size @Return true if successful @Description Write i32Size no. of unsigned shorts from pData, bracketed by an nName begin/end markers. *****************************************************************************/ template <typename T> static bool WriteData16( FILE * const pFile, const unsigned int nName, const T * const pData, int i32Size = 1) { if(pData) { if(!WriteMarker(pFile, nName, false, 2 * i32Size)) return false; if(!WriteFileSafe16(pFile, (unsigned short*) pData, i32Size)) return false; if(!WriteMarker(pFile, nName, true)) return false; } return true; } /*!*************************************************************************** @Function WriteData32 @Input pFile @Input nName @Input pData @Input i32Size @Return true if successful @Description Write i32Size no. of unsigned ints from pData, bracketed by an nName begin/end markers. *****************************************************************************/ template <typename T> static bool WriteData32( FILE * const pFile, const unsigned int nName, const T * const pData, int i32Size = 1) { if(pData) { if(!WriteMarker(pFile, nName, false, 4 * i32Size)) return false; if(!WriteFileSafe32(pFile, (unsigned int*) pData, i32Size)) return false; if(!WriteMarker(pFile, nName, true)) return false; } return true; } /*!*************************************************************************** @Function WriteData @Input pFile @Input nName @Input n @Return true if successful @Description Write the value n, bracketed by an nName begin/end markers. *****************************************************************************/ template <typename T> static bool WriteData( FILE * const pFile, const unsigned int nName, const T &n) { unsigned int nSize = sizeof(T); bool bRet = WriteData(pFile, nName, (void*)&n, nSize); return bRet; } /*!*************************************************************************** @Function WriteCPODData @Input pFile @Input nName @Input n @Input nEntries @Input bValidData @Return true if successful @Description Write the value n, bracketed by an nName begin/end markers. *****************************************************************************/ static bool WriteCPODData( FILE * const pFile, const unsigned int nName, const CPODData &n, const unsigned int nEntries, const bool bValidData) { if(!WriteMarker(pFile, nName, false)) return false; if(!WriteData32(pFile, ePODFileDataType, &n.eType)) return false; if(!WriteData32(pFile, ePODFileN, &n.n)) return false; if(!WriteData32(pFile, ePODFileStride, &n.nStride)) return false; if(bValidData) { switch(PVRTModelPODDataTypeSize(n.eType)) { case 1: if(!WriteData(pFile, ePODFileData, n.pData, nEntries * n.nStride)) return false; break; case 2: if(!WriteData16(pFile, ePODFileData, n.pData, nEntries * (n.nStride / 2))) return false; break; case 4: if(!WriteData32(pFile, ePODFileData, n.pData, nEntries * (n.nStride / 4))) return false; break; default: { _ASSERT(false); } }; } else { unsigned int offset = (unsigned int) (size_t) n.pData; if(!WriteData32(pFile, ePODFileData, &offset)) return false; } if(!WriteMarker(pFile, nName, true)) return false; return true; } /*!*************************************************************************** @Function WriteInterleaved @Input pFile @Input mesh @Return true if successful @Description Write out the interleaved data to file. *****************************************************************************/ static bool WriteInterleaved(FILE * const pFile, SPODMesh &mesh) { if(!mesh.pInterleaved) return true; unsigned int i; unsigned int ui32CPODDataSize = 0; CPODData **pCPODData = new CPODData*[7 + mesh.nNumUVW]; if(mesh.sVertex.n) pCPODData[ui32CPODDataSize++] = &mesh.sVertex; if(mesh.sNormals.n) pCPODData[ui32CPODDataSize++] = &mesh.sNormals; if(mesh.sTangents.n) pCPODData[ui32CPODDataSize++] = &mesh.sTangents; if(mesh.sBinormals.n) pCPODData[ui32CPODDataSize++] = &mesh.sBinormals; if(mesh.sVtxColours.n) pCPODData[ui32CPODDataSize++] = &mesh.sVtxColours; if(mesh.sBoneIdx.n) pCPODData[ui32CPODDataSize++] = &mesh.sBoneIdx; if(mesh.sBoneWeight.n) pCPODData[ui32CPODDataSize++] = &mesh.sBoneWeight; for(i = 0; i < mesh.nNumUVW; ++i) if(mesh.psUVW[i].n) pCPODData[ui32CPODDataSize++] = &mesh.psUVW[i]; // Bubble sort pCPODData based on the vertex element offsets bool bSwap = true; unsigned int ui32Size = ui32CPODDataSize; while(bSwap) { bSwap = false; for(i = 0; i < ui32Size - 1; ++i) { if(pCPODData[i]->pData > pCPODData[i + 1]->pData) { PVRTswap(pCPODData[i], pCPODData[i + 1]); bSwap = true; } } --ui32Size; } // Write out the data if(!WriteMarker(pFile, ePODFileMeshInterleaved, false, mesh.nNumVertex * mesh.sVertex.nStride)) return false; for(i = 0; i < mesh.nNumVertex; ++i) { unsigned char* pVtxStart = mesh.pInterleaved + (i * mesh.sVertex.nStride); for(unsigned int j = 0; j < ui32CPODDataSize; ++j) { unsigned char* pData = pVtxStart + (size_t) pCPODData[j]->pData; switch(PVRTModelPODDataTypeSize(pCPODData[j]->eType)) { case 1: if(!WriteFileSafe(pFile, pData, pCPODData[j]->n)) return false; break; case 2: if(!WriteFileSafe16(pFile, (unsigned short*) pData, pCPODData[j]->n)) return false; break; case 4: if(!WriteFileSafe32(pFile, (unsigned int*) pData, pCPODData[j]->n)) return false; break; default: { _ASSERT(false); } }; // Write out the padding size_t padding; if(j != ui32CPODDataSize - 1) padding = ((size_t)pCPODData[j + 1]->pData - (size_t)pCPODData[j]->pData) - PVRTModelPODDataStride(*pCPODData[j]); else padding = (pCPODData[j]->nStride - (size_t)pCPODData[j]->pData) - PVRTModelPODDataStride(*pCPODData[j]); fwrite("\0\0\0\0", padding, 1, pFile); } } if(!WriteMarker(pFile, ePODFileMeshInterleaved, true)) return false; // Delete our CPOD data array delete[] pCPODData; return true; } /*!*************************************************************************** @Function PVRTModelPODGetAnimArraySize @Input pAnimDataIdx @Input ui32Frames @Input ui32Components @Return Size of the animation array @Description Calculates the size of an animation array *****************************************************************************/ PVRTuint32 PVRTModelPODGetAnimArraySize(PVRTuint32 *pAnimDataIdx, PVRTuint32 ui32Frames, PVRTuint32 ui32Components) { if(pAnimDataIdx) { // Find the largest index value PVRTuint32 ui32Max = 0; for(unsigned int i = 0; i < ui32Frames; ++i) { if(ui32Max < pAnimDataIdx[i]) ui32Max = pAnimDataIdx[i]; } return ui32Max + ui32Components; } return ui32Frames * ui32Components; } /*!*************************************************************************** @Function WritePOD @Output The file referenced by pFile @Input s The POD Scene to write @Input pszExpOpt Exporter options @Return true if successful @Description Write a POD file *****************************************************************************/ static bool WritePOD( FILE * const pFile, const char * const pszExpOpt, const char * const pszHistory, const SPODScene &s) { unsigned int i, j; // Save: file version { char *pszVersion = (char*)PVRTMODELPOD_VERSION; if(!WriteData(pFile, ePODFileVersion, pszVersion, (unsigned int)strlen(pszVersion) + 1)) return false; } // Save: exporter options if(pszExpOpt && *pszExpOpt) { if(!WriteData(pFile, ePODFileExpOpt, pszExpOpt, (unsigned int)strlen(pszExpOpt) + 1)) return false; } // Save: .pod file history if(pszHistory && *pszHistory) { if(!WriteData(pFile, ePODFileHistory, pszHistory, (unsigned int)strlen(pszHistory) + 1)) return false; } // Save: scene descriptor if(!WriteMarker(pFile, ePODFileScene, false)) return false; { if(!WriteData32(pFile, ePODFileColourBackground, s.pfColourBackground, sizeof(s.pfColourBackground) / sizeof(*s.pfColourBackground))) return false; if(!WriteData32(pFile, ePODFileColourAmbient, s.pfColourAmbient, sizeof(s.pfColourAmbient) / sizeof(*s.pfColourAmbient))) return false; if(!WriteData32(pFile, ePODFileNumCamera, &s.nNumCamera)) return false; if(!WriteData32(pFile, ePODFileNumLight, &s.nNumLight)) return false; if(!WriteData32(pFile, ePODFileNumMesh, &s.nNumMesh)) return false; if(!WriteData32(pFile, ePODFileNumNode, &s.nNumNode)) return false; if(!WriteData32(pFile, ePODFileNumMeshNode, &s.nNumMeshNode)) return false; if(!WriteData32(pFile, ePODFileNumTexture, &s.nNumTexture)) return false; if(!WriteData32(pFile, ePODFileNumMaterial, &s.nNumMaterial)) return false; if(!WriteData32(pFile, ePODFileNumFrame, &s.nNumFrame)) return false; if(s.nNumFrame) { if(!WriteData32(pFile, ePODFileFPS, &s.nFPS)) return false; } if(!WriteData32(pFile, ePODFileFlags, &s.nFlags)) return false; if(!WriteData(pFile, ePODFileUserData, s.pUserData, s.nUserDataSize)) return false; // Save: cameras for(i = 0; i < s.nNumCamera; ++i) { if(!WriteMarker(pFile, ePODFileCamera, false)) return false; if(!WriteData32(pFile, ePODFileCamIdxTgt, &s.pCamera[i].nIdxTarget)) return false; if(!WriteData32(pFile, ePODFileCamFOV, &s.pCamera[i].fFOV)) return false; if(!WriteData32(pFile, ePODFileCamFar, &s.pCamera[i].fFar)) return false; if(!WriteData32(pFile, ePODFileCamNear, &s.pCamera[i].fNear)) return false; if(!WriteData32(pFile, ePODFileCamAnimFOV, s.pCamera[i].pfAnimFOV, s.nNumFrame)) return false; if(!WriteMarker(pFile, ePODFileCamera, true)) return false; } // Save: lights for(i = 0; i < s.nNumLight; ++i) { if(!WriteMarker(pFile, ePODFileLight, false)) return false; if(!WriteData32(pFile, ePODFileLightIdxTgt, &s.pLight[i].nIdxTarget)) return false; if(!WriteData32(pFile, ePODFileLightColour, s.pLight[i].pfColour, sizeof(s.pLight[i].pfColour) / sizeof(*s.pLight[i].pfColour))) return false; if(!WriteData32(pFile, ePODFileLightType, &s.pLight[i].eType)) return false; if(s.pLight[i].eType != ePODDirectional) { if(!WriteData32(pFile, ePODFileLightConstantAttenuation, &s.pLight[i].fConstantAttenuation)) return false; if(!WriteData32(pFile, ePODFileLightLinearAttenuation, &s.pLight[i].fLinearAttenuation)) return false; if(!WriteData32(pFile, ePODFileLightQuadraticAttenuation, &s.pLight[i].fQuadraticAttenuation)) return false; } if(s.pLight[i].eType == ePODSpot) { if(!WriteData32(pFile, ePODFileLightFalloffAngle, &s.pLight[i].fFalloffAngle)) return false; if(!WriteData32(pFile, ePODFileLightFalloffExponent, &s.pLight[i].fFalloffExponent)) return false; } if(!WriteMarker(pFile, ePODFileLight, true)) return false; } // Save: materials for(i = 0; i < s.nNumMaterial; ++i) { if(!WriteMarker(pFile, ePODFileMaterial, false)) return false; if(!WriteData32(pFile, ePODFileMatFlags, &s.pMaterial[i].nFlags)) return false; if(!WriteData(pFile, ePODFileMatName, s.pMaterial[i].pszName, (unsigned int)strlen(s.pMaterial[i].pszName)+1)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexDiffuse, &s.pMaterial[i].nIdxTexDiffuse)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexAmbient, &s.pMaterial[i].nIdxTexAmbient)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexSpecularColour, &s.pMaterial[i].nIdxTexSpecularColour)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexSpecularLevel, &s.pMaterial[i].nIdxTexSpecularLevel)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexBump, &s.pMaterial[i].nIdxTexBump)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexEmissive, &s.pMaterial[i].nIdxTexEmissive)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexGlossiness, &s.pMaterial[i].nIdxTexGlossiness)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexOpacity, &s.pMaterial[i].nIdxTexOpacity)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexReflection, &s.pMaterial[i].nIdxTexReflection)) return false; if(!WriteData32(pFile, ePODFileMatIdxTexRefraction, &s.pMaterial[i].nIdxTexRefraction)) return false; if(!WriteData32(pFile, ePODFileMatOpacity, &s.pMaterial[i].fMatOpacity)) return false; if(!WriteData32(pFile, ePODFileMatAmbient, s.pMaterial[i].pfMatAmbient, sizeof(s.pMaterial[i].pfMatAmbient) / sizeof(*s.pMaterial[i].pfMatAmbient))) return false; if(!WriteData32(pFile, ePODFileMatDiffuse, s.pMaterial[i].pfMatDiffuse, sizeof(s.pMaterial[i].pfMatDiffuse) / sizeof(*s.pMaterial[i].pfMatDiffuse))) return false; if(!WriteData32(pFile, ePODFileMatSpecular, s.pMaterial[i].pfMatSpecular, sizeof(s.pMaterial[i].pfMatSpecular) / sizeof(*s.pMaterial[i].pfMatSpecular))) return false; if(!WriteData32(pFile, ePODFileMatShininess, &s.pMaterial[i].fMatShininess)) return false; if(!WriteData(pFile, ePODFileMatEffectFile, s.pMaterial[i].pszEffectFile, s.pMaterial[i].pszEffectFile ? ((unsigned int)strlen(s.pMaterial[i].pszEffectFile)+1) : 0)) return false; if(!WriteData(pFile, ePODFileMatEffectName, s.pMaterial[i].pszEffectName, s.pMaterial[i].pszEffectName ? ((unsigned int)strlen(s.pMaterial[i].pszEffectName)+1) : 0)) return false; if(!WriteData32(pFile, ePODFileMatBlendSrcRGB, &s.pMaterial[i].eBlendSrcRGB))return false; if(!WriteData32(pFile, ePODFileMatBlendSrcA, &s.pMaterial[i].eBlendSrcA)) return false; if(!WriteData32(pFile, ePODFileMatBlendDstRGB, &s.pMaterial[i].eBlendDstRGB))return false; if(!WriteData32(pFile, ePODFileMatBlendDstA, &s.pMaterial[i].eBlendDstA)) return false; if(!WriteData32(pFile, ePODFileMatBlendOpRGB, &s.pMaterial[i].eBlendOpRGB)) return false; if(!WriteData32(pFile, ePODFileMatBlendOpA, &s.pMaterial[i].eBlendOpA)) return false; if(!WriteData32(pFile, ePODFileMatBlendColour, s.pMaterial[i].pfBlendColour, sizeof(s.pMaterial[i].pfBlendColour) / sizeof(*s.pMaterial[i].pfBlendColour))) return false; if(!WriteData32(pFile, ePODFileMatBlendFactor, s.pMaterial[i].pfBlendFactor, sizeof(s.pMaterial[i].pfBlendFactor) / sizeof(*s.pMaterial[i].pfBlendFactor))) return false; if(!WriteData(pFile, ePODFileMatUserData, s.pMaterial[i].pUserData, s.pMaterial[i].nUserDataSize)) return false; if(!WriteMarker(pFile, ePODFileMaterial, true)) return false; } // Save: meshes for(i = 0; i < s.nNumMesh; ++i) { if(!WriteMarker(pFile, ePODFileMesh, false)) return false; if(!WriteData32(pFile, ePODFileMeshNumVtx, &s.pMesh[i].nNumVertex)) return false; if(!WriteData32(pFile, ePODFileMeshNumFaces, &s.pMesh[i].nNumFaces)) return false; if(!WriteData32(pFile, ePODFileMeshNumUVW, &s.pMesh[i].nNumUVW)) return false; if(!WriteData32(pFile, ePODFileMeshStripLength, s.pMesh[i].pnStripLength, s.pMesh[i].nNumStrips)) return false; if(!WriteData32(pFile, ePODFileMeshNumStrips, &s.pMesh[i].nNumStrips)) return false; if(!WriteInterleaved(pFile, s.pMesh[i])) return false; if(!WriteData32(pFile, ePODFileMeshBoneBatchBoneMax,&s.pMesh[i].sBoneBatches.nBatchBoneMax)) return false; if(!WriteData32(pFile, ePODFileMeshBoneBatchCnt, &s.pMesh[i].sBoneBatches.nBatchCnt)) return false; if(!WriteData32(pFile, ePODFileMeshBoneBatches, s.pMesh[i].sBoneBatches.pnBatches, s.pMesh[i].sBoneBatches.nBatchBoneMax * s.pMesh[i].sBoneBatches.nBatchCnt)) return false; if(!WriteData32(pFile, ePODFileMeshBoneBatchBoneCnts, s.pMesh[i].sBoneBatches.pnBatchBoneCnt, s.pMesh[i].sBoneBatches.nBatchCnt)) return false; if(!WriteData32(pFile, ePODFileMeshBoneBatchOffsets, s.pMesh[i].sBoneBatches.pnBatchOffset,s.pMesh[i].sBoneBatches.nBatchCnt)) return false; if(!WriteData32(pFile, ePODFileMeshUnpackMatrix, s.pMesh[i].mUnpackMatrix.f, 16)) return false; if(!WriteCPODData(pFile, ePODFileMeshFaces, s.pMesh[i].sFaces, PVRTModelPODCountIndices(s.pMesh[i]), true)) return false; if(!WriteCPODData(pFile, ePODFileMeshVtx, s.pMesh[i].sVertex, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshNor, s.pMesh[i].sNormals, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshTan, s.pMesh[i].sTangents, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshBin, s.pMesh[i].sBinormals, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; for(j = 0; j < s.pMesh[i].nNumUVW; ++j) if(!WriteCPODData(pFile, ePODFileMeshUVW, s.pMesh[i].psUVW[j], s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshVtxCol, s.pMesh[i].sVtxColours, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshBoneIdx, s.pMesh[i].sBoneIdx, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteCPODData(pFile, ePODFileMeshBoneWeight, s.pMesh[i].sBoneWeight, s.pMesh[i].nNumVertex, s.pMesh[i].pInterleaved == 0)) return false; if(!WriteMarker(pFile, ePODFileMesh, true)) return false; } int iTransformationNo; // Save: node for(i = 0; i < s.nNumNode; ++i) { if(!WriteMarker(pFile, ePODFileNode, false)) return false; { if(!WriteData32(pFile, ePODFileNodeIdx, &s.pNode[i].nIdx)) return false; if(!WriteData(pFile, ePODFileNodeName, s.pNode[i].pszName, (unsigned int)strlen(s.pNode[i].pszName)+1)) return false; if(!WriteData32(pFile, ePODFileNodeIdxMat, &s.pNode[i].nIdxMaterial)) return false; if(!WriteData32(pFile, ePODFileNodeIdxParent, &s.pNode[i].nIdxParent)) return false; if(!WriteData32(pFile, ePODFileNodeAnimFlags, &s.pNode[i].nAnimFlags)) return false; if(s.pNode[i].pnAnimPositionIdx) { if(!WriteData32(pFile, ePODFileNodeAnimPosIdx, s.pNode[i].pnAnimPositionIdx, s.nNumFrame)) return false; } iTransformationNo = s.pNode[i].nAnimFlags & ePODHasPositionAni ? PVRTModelPODGetAnimArraySize(s.pNode[i].pnAnimPositionIdx, s.nNumFrame, 3) : 3; if(!WriteData32(pFile, ePODFileNodeAnimPos, s.pNode[i].pfAnimPosition, iTransformationNo)) return false; if(s.pNode[i].pnAnimRotationIdx) { if(!WriteData32(pFile, ePODFileNodeAnimRotIdx, s.pNode[i].pnAnimRotationIdx, s.nNumFrame)) return false; } iTransformationNo = s.pNode[i].nAnimFlags & ePODHasRotationAni ? PVRTModelPODGetAnimArraySize(s.pNode[i].pnAnimRotationIdx, s.nNumFrame, 4) : 4; if(!WriteData32(pFile, ePODFileNodeAnimRot, s.pNode[i].pfAnimRotation, iTransformationNo)) return false; if(s.pNode[i].pnAnimScaleIdx) { if(!WriteData32(pFile, ePODFileNodeAnimScaleIdx, s.pNode[i].pnAnimScaleIdx, s.nNumFrame)) return false; } iTransformationNo = s.pNode[i].nAnimFlags & ePODHasScaleAni ? PVRTModelPODGetAnimArraySize(s.pNode[i].pnAnimScaleIdx, s.nNumFrame, 7) : 7; if(!WriteData32(pFile, ePODFileNodeAnimScale, s.pNode[i].pfAnimScale, iTransformationNo)) return false; if(s.pNode[i].pnAnimMatrixIdx) { if(!WriteData32(pFile, ePODFileNodeAnimMatrixIdx, s.pNode[i].pnAnimMatrixIdx, s.nNumFrame)) return false; } iTransformationNo = s.pNode[i].nAnimFlags & ePODHasMatrixAni ? PVRTModelPODGetAnimArraySize(s.pNode[i].pnAnimMatrixIdx, s.nNumFrame, 16) : 16; if(!WriteData32(pFile, ePODFileNodeAnimMatrix,s.pNode[i].pfAnimMatrix, iTransformationNo)) return false; if(!WriteData(pFile, ePODFileNodeUserData, s.pNode[i].pUserData, s.pNode[i].nUserDataSize)) return false; } if(!WriteMarker(pFile, ePODFileNode, true)) return false; } // Save: texture for(i = 0; i < s.nNumTexture; ++i) { if(!WriteMarker(pFile, ePODFileTexture, false)) return false; if(!WriteData(pFile, ePODFileTexName, s.pTexture[i].pszName, (unsigned int)strlen(s.pTexture[i].pszName)+1)) return false; if(!WriteMarker(pFile, ePODFileTexture, true)) return false; } } if(!WriteMarker(pFile, ePODFileScene, true)) return false; return true; } /**************************************************************************** ** Local code: File reading ****************************************************************************/ /*!*************************************************************************** @Function ReadCPODData @Modified s The CPODData to read into @Input src CSource object to read data from. @Input nSpec @Input bValidData @Return true if successful @Description Read a CPODData block in from a pod file *****************************************************************************/ static bool ReadCPODData( CPODData &s, CSource &src, const unsigned int nSpec, const bool bValidData) { unsigned int nName, nLen, nBuff; while(src.ReadMarker(nName, nLen)) { if(nName == (nSpec | PVRTMODELPOD_TAG_END)) return true; switch(nName) { case ePODFileDataType: if(!src.Read32(s.eType)) return false; break; case ePODFileN: if(!src.Read32(s.n)) return false; break; case ePODFileStride: if(!src.Read32(s.nStride)) return false; break; case ePODFileData: if(bValidData) { switch(PVRTModelPODDataTypeSize(s.eType)) { case 1: if(!src.ReadAfterAlloc(s.pData, nLen)) return false; break; case 2: { // reading 16bit data but have 8bit pointer PVRTuint16 *p16Pointer=NULL; if(!src.ReadAfterAlloc16(p16Pointer, nLen)) return false; s.pData = (unsigned char*)p16Pointer; break; } case 4: { // reading 32bit data but have 8bit pointer PVRTuint32 *p32Pointer=NULL; if(!src.ReadAfterAlloc32(p32Pointer, nLen)) return false; s.pData = (unsigned char*)p32Pointer; break; } default: { _ASSERT(false);} } } else { if(src.Read32(nBuff)) { s.pData = (unsigned char*) (size_t) nBuff; } else { return false; } } break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadCamera @Modified s The SPODCamera to read into @Input src CSource object to read data from. @Return true if successful @Description Read a camera block in from a pod file *****************************************************************************/ static bool ReadCamera( SPODCamera &s, CSource &src) { unsigned int nName, nLen; s.pfAnimFOV = 0; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileCamera | PVRTMODELPOD_TAG_END: return true; case ePODFileCamIdxTgt: if(!src.Read32(s.nIdxTarget)) return false; break; case ePODFileCamFOV: if(!src.Read32(s.fFOV)) return false; break; case ePODFileCamFar: if(!src.Read32(s.fFar)) return false; break; case ePODFileCamNear: if(!src.Read32(s.fNear)) return false; break; case ePODFileCamAnimFOV: if(!src.ReadAfterAlloc32(s.pfAnimFOV, nLen)) return false; break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadLight @Modified s The SPODLight to read into @Input src CSource object to read data from. @Return true if successful @Description Read a light block in from a pod file *****************************************************************************/ static bool ReadLight( SPODLight &s, CSource &src) { unsigned int nName, nLen; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileLight | PVRTMODELPOD_TAG_END: return true; case ePODFileLightIdxTgt: if(!src.Read32(s.nIdxTarget)) return false; break; case ePODFileLightColour: if(!src.ReadArray32(s.pfColour, 3)) return false; break; case ePODFileLightType: if(!src.Read32(s.eType)) return false; break; case ePODFileLightConstantAttenuation: if(!src.Read32(s.fConstantAttenuation)) return false; break; case ePODFileLightLinearAttenuation: if(!src.Read32(s.fLinearAttenuation)) return false; break; case ePODFileLightQuadraticAttenuation: if(!src.Read32(s.fQuadraticAttenuation)) return false; break; case ePODFileLightFalloffAngle: if(!src.Read32(s.fFalloffAngle)) return false; break; case ePODFileLightFalloffExponent: if(!src.Read32(s.fFalloffExponent)) return false; break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadMaterial @Modified s The SPODMaterial to read into @Input src CSource object to read data from. @Return true if successful @Description Read a material block in from a pod file *****************************************************************************/ static bool ReadMaterial( SPODMaterial &s, CSource &src) { unsigned int nName, nLen; // Set texture IDs to -1 s.nIdxTexDiffuse = -1; s.nIdxTexAmbient = -1; s.nIdxTexSpecularColour = -1; s.nIdxTexSpecularLevel = -1; s.nIdxTexBump = -1; s.nIdxTexEmissive = -1; s.nIdxTexGlossiness = -1; s.nIdxTexOpacity = -1; s.nIdxTexReflection = -1; s.nIdxTexRefraction = -1; // Set defaults for blend modes s.eBlendSrcRGB = s.eBlendSrcA = ePODBlendFunc_ONE; s.eBlendDstRGB = s.eBlendDstA = ePODBlendFunc_ZERO; s.eBlendOpRGB = s.eBlendOpA = ePODBlendOp_ADD; memset(s.pfBlendColour, 0, sizeof(s.pfBlendColour)); memset(s.pfBlendFactor, 0, sizeof(s.pfBlendFactor)); // Set default for material flags s.nFlags = 0; // Set default for user data s.pUserData = 0; s.nUserDataSize = 0; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileMaterial | PVRTMODELPOD_TAG_END: return true; case ePODFileMatFlags: if(!src.Read32(s.nFlags)) return false; break; case ePODFileMatName: if(!src.ReadAfterAlloc(s.pszName, nLen)) return false; break; case ePODFileMatIdxTexDiffuse: if(!src.Read32(s.nIdxTexDiffuse)) return false; break; case ePODFileMatIdxTexAmbient: if(!src.Read32(s.nIdxTexAmbient)) return false; break; case ePODFileMatIdxTexSpecularColour: if(!src.Read32(s.nIdxTexSpecularColour)) return false; break; case ePODFileMatIdxTexSpecularLevel: if(!src.Read32(s.nIdxTexSpecularLevel)) return false; break; case ePODFileMatIdxTexBump: if(!src.Read32(s.nIdxTexBump)) return false; break; case ePODFileMatIdxTexEmissive: if(!src.Read32(s.nIdxTexEmissive)) return false; break; case ePODFileMatIdxTexGlossiness: if(!src.Read32(s.nIdxTexGlossiness)) return false; break; case ePODFileMatIdxTexOpacity: if(!src.Read32(s.nIdxTexOpacity)) return false; break; case ePODFileMatIdxTexReflection: if(!src.Read32(s.nIdxTexReflection)) return false; break; case ePODFileMatIdxTexRefraction: if(!src.Read32(s.nIdxTexRefraction)) return false; break; case ePODFileMatOpacity: if(!src.Read32(s.fMatOpacity)) return false; break; case ePODFileMatAmbient: if(!src.ReadArray32(s.pfMatAmbient, sizeof(s.pfMatAmbient) / sizeof(*s.pfMatAmbient))) return false; break; case ePODFileMatDiffuse: if(!src.ReadArray32(s.pfMatDiffuse, sizeof(s.pfMatDiffuse) / sizeof(*s.pfMatDiffuse))) return false; break; case ePODFileMatSpecular: if(!src.ReadArray32(s.pfMatSpecular, sizeof(s.pfMatSpecular) / sizeof(*s.pfMatSpecular))) return false; break; case ePODFileMatShininess: if(!src.Read32(s.fMatShininess)) return false; break; case ePODFileMatEffectFile: if(!src.ReadAfterAlloc(s.pszEffectFile, nLen)) return false; break; case ePODFileMatEffectName: if(!src.ReadAfterAlloc(s.pszEffectName, nLen)) return false; break; case ePODFileMatBlendSrcRGB: if(!src.Read32(s.eBlendSrcRGB)) return false; break; case ePODFileMatBlendSrcA: if(!src.Read32(s.eBlendSrcA)) return false; break; case ePODFileMatBlendDstRGB: if(!src.Read32(s.eBlendDstRGB)) return false; break; case ePODFileMatBlendDstA: if(!src.Read32(s.eBlendDstA)) return false; break; case ePODFileMatBlendOpRGB: if(!src.Read32(s.eBlendOpRGB)) return false; break; case ePODFileMatBlendOpA: if(!src.Read32(s.eBlendOpA)) return false; break; case ePODFileMatBlendColour: if(!src.ReadArray32(s.pfBlendColour, sizeof(s.pfBlendColour) / sizeof(*s.pfBlendColour))) return false; break; case ePODFileMatBlendFactor: if(!src.ReadArray32(s.pfBlendFactor, sizeof(s.pfBlendFactor) / sizeof(*s.pfBlendFactor))) return false; break; case ePODFileMatUserData: if(!src.ReadAfterAlloc(s.pUserData, nLen)) return false; else { s.nUserDataSize = nLen; break; } default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function PVRTFixInterleavedEndiannessUsingCPODData @Modified pInterleaved - The interleaved data @Input data - The CPODData. @Return ui32Size - Number of elements in pInterleaved @Description Called multiple times and goes through the interleaved data correcting the endianness. *****************************************************************************/ static void PVRTFixInterleavedEndiannessUsingCPODData(unsigned char* pInterleaved, CPODData &data, unsigned int ui32Size) { if(!data.n) return; size_t ui32TypeSize = PVRTModelPODDataTypeSize(data.eType); unsigned char ub[4]; unsigned char *pData = pInterleaved + (size_t) data.pData; switch(ui32TypeSize) { case 1: return; case 2: { for(unsigned int i = 0; i < ui32Size; ++i) { for(unsigned int j = 0; j < data.n; ++j) { ub[0] = pData[ui32TypeSize * j + 0]; ub[1] = pData[ui32TypeSize * j + 1]; ((unsigned short*) pData)[j] = (unsigned short) ((ub[1] << 8) | ub[0]); } pData += data.nStride; } } break; case 4: { for(unsigned int i = 0; i < ui32Size; ++i) { for(unsigned int j = 0; j < data.n; ++j) { ub[0] = pData[ui32TypeSize * j + 0]; ub[1] = pData[ui32TypeSize * j + 1]; ub[2] = pData[ui32TypeSize * j + 2]; ub[3] = pData[ui32TypeSize * j + 3]; ((unsigned int*) pData)[j] = (unsigned int) ((ub[3] << 24) | (ub[2] << 16) | (ub[1] << 8) | ub[0]); } pData += data.nStride; } } break; default: { _ASSERT(false); } }; } static void PVRTFixInterleavedEndianness(SPODMesh &s) { if(!s.pInterleaved || PVRTIsLittleEndian()) return; PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sVertex, s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sNormals, s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sTangents, s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sBinormals, s.nNumVertex); for(unsigned int i = 0; i < s.nNumUVW; ++i) PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.psUVW[i], s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sVtxColours, s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sBoneIdx, s.nNumVertex); PVRTFixInterleavedEndiannessUsingCPODData(s.pInterleaved, s.sBoneWeight, s.nNumVertex); } /*!*************************************************************************** @Function ReadMesh @Modified s The SPODMesh to read into @Input src CSource object to read data from. @Return true if successful @Description Read a mesh block in from a pod file *****************************************************************************/ static bool ReadMesh( SPODMesh &s, CSource &src) { unsigned int nName, nLen; unsigned int nUVWs=0; PVRTMatrixIdentity(s.mUnpackMatrix); while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileMesh | PVRTMODELPOD_TAG_END: if(nUVWs != s.nNumUVW) return false; PVRTFixInterleavedEndianness(s); return true; case ePODFileMeshNumVtx: if(!src.Read32(s.nNumVertex)) return false; break; case ePODFileMeshNumFaces: if(!src.Read32(s.nNumFaces)) return false; break; case ePODFileMeshNumUVW: if(!src.Read32(s.nNumUVW)) return false; if(!SafeAlloc(s.psUVW, s.nNumUVW)) return false; break; case ePODFileMeshStripLength: if(!src.ReadAfterAlloc32(s.pnStripLength, nLen)) return false; break; case ePODFileMeshNumStrips: if(!src.Read32(s.nNumStrips)) return false; break; case ePODFileMeshInterleaved: if(!src.ReadAfterAlloc(s.pInterleaved, nLen)) return false; break; case ePODFileMeshBoneBatches: if(!src.ReadAfterAlloc32(s.sBoneBatches.pnBatches, nLen)) return false; break; case ePODFileMeshBoneBatchBoneCnts: if(!src.ReadAfterAlloc32(s.sBoneBatches.pnBatchBoneCnt, nLen)) return false; break; case ePODFileMeshBoneBatchOffsets: if(!src.ReadAfterAlloc32(s.sBoneBatches.pnBatchOffset, nLen)) return false; break; case ePODFileMeshBoneBatchBoneMax: if(!src.Read32(s.sBoneBatches.nBatchBoneMax)) return false; break; case ePODFileMeshBoneBatchCnt: if(!src.Read32(s.sBoneBatches.nBatchCnt)) return false; break; case ePODFileMeshUnpackMatrix: if(!src.ReadArray32(&s.mUnpackMatrix.f[0], 16)) return false; break; case ePODFileMeshFaces: if(!ReadCPODData(s.sFaces, src, ePODFileMeshFaces, true)) return false; break; case ePODFileMeshVtx: if(!ReadCPODData(s.sVertex, src, ePODFileMeshVtx, s.pInterleaved == 0)) return false; break; case ePODFileMeshNor: if(!ReadCPODData(s.sNormals, src, ePODFileMeshNor, s.pInterleaved == 0)) return false; break; case ePODFileMeshTan: if(!ReadCPODData(s.sTangents, src, ePODFileMeshTan, s.pInterleaved == 0)) return false; break; case ePODFileMeshBin: if(!ReadCPODData(s.sBinormals, src, ePODFileMeshBin, s.pInterleaved == 0)) return false; break; case ePODFileMeshUVW: if(!ReadCPODData(s.psUVW[nUVWs++], src, ePODFileMeshUVW, s.pInterleaved == 0)) return false; break; case ePODFileMeshVtxCol: if(!ReadCPODData(s.sVtxColours, src, ePODFileMeshVtxCol, s.pInterleaved == 0)) return false; break; case ePODFileMeshBoneIdx: if(!ReadCPODData(s.sBoneIdx, src, ePODFileMeshBoneIdx, s.pInterleaved == 0)) return false; break; case ePODFileMeshBoneWeight: if(!ReadCPODData(s.sBoneWeight, src, ePODFileMeshBoneWeight, s.pInterleaved == 0)) return false; break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadNode @Modified s The SPODNode to read into @Input src CSource object to read data from. @Return true if successful @Description Read a node block in from a pod file *****************************************************************************/ static bool ReadNode( SPODNode &s, CSource &src) { unsigned int nName, nLen; bool bOldNodeFormat = false; VERTTYPE fPos[3] = {0,0,0}; VERTTYPE fQuat[4] = {0,0,0,f2vt(1)}; VERTTYPE fScale[7] = {f2vt(1),f2vt(1),f2vt(1),0,0,0,0}; // Set default for user data s.pUserData = 0; s.nUserDataSize = 0; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileNode | PVRTMODELPOD_TAG_END: if(bOldNodeFormat) { if(s.pfAnimPosition) s.nAnimFlags |= ePODHasPositionAni; else { s.pfAnimPosition = (VERTTYPE*) malloc(sizeof(fPos)); memcpy(s.pfAnimPosition, fPos, sizeof(fPos)); } if(s.pfAnimRotation) s.nAnimFlags |= ePODHasRotationAni; else { s.pfAnimRotation = (VERTTYPE*) malloc(sizeof(fQuat)); memcpy(s.pfAnimRotation, fQuat, sizeof(fQuat)); } if(s.pfAnimScale) s.nAnimFlags |= ePODHasScaleAni; else { s.pfAnimScale = (VERTTYPE*) malloc(sizeof(fScale)); memcpy(s.pfAnimScale, fScale, sizeof(fScale)); } } return true; case ePODFileNodeIdx: if(!src.Read32(s.nIdx)) return false; break; case ePODFileNodeName: if(!src.ReadAfterAlloc(s.pszName, nLen)) return false; break; case ePODFileNodeIdxMat: if(!src.Read32(s.nIdxMaterial)) return false; break; case ePODFileNodeIdxParent: if(!src.Read32(s.nIdxParent)) return false; break; case ePODFileNodeAnimFlags:if(!src.Read32(s.nAnimFlags))return false; break; case ePODFileNodeAnimPosIdx: if(!src.ReadAfterAlloc32(s.pnAnimPositionIdx, nLen)) return false; break; case ePODFileNodeAnimPos: if(!src.ReadAfterAlloc32(s.pfAnimPosition, nLen)) return false; break; case ePODFileNodeAnimRotIdx: if(!src.ReadAfterAlloc32(s.pnAnimRotationIdx, nLen)) return false; break; case ePODFileNodeAnimRot: if(!src.ReadAfterAlloc32(s.pfAnimRotation, nLen)) return false; break; case ePODFileNodeAnimScaleIdx: if(!src.ReadAfterAlloc32(s.pnAnimScaleIdx, nLen)) return false; break; case ePODFileNodeAnimScale: if(!src.ReadAfterAlloc32(s.pfAnimScale, nLen)) return false; break; case ePODFileNodeAnimMatrixIdx: if(!src.ReadAfterAlloc32(s.pnAnimMatrixIdx, nLen)) return false; break; case ePODFileNodeAnimMatrix:if(!src.ReadAfterAlloc32(s.pfAnimMatrix, nLen)) return false; break; case ePODFileNodeUserData: if(!src.ReadAfterAlloc(s.pUserData, nLen)) return false; else { s.nUserDataSize = nLen; break; } // Parameters from the older pod format case ePODFileNodePos: if(!src.ReadArray32(&fPos[0], 3)) return false; bOldNodeFormat = true; break; case ePODFileNodeRot: if(!src.ReadArray32(&fQuat[0], 4)) return false; bOldNodeFormat = true; break; case ePODFileNodeScale: if(!src.ReadArray32(&fScale[0], 3)) return false; bOldNodeFormat = true; break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadTexture @Modified s The SPODTexture to read into @Input src CSource object to read data from. @Return true if successful @Description Read a texture block in from a pod file *****************************************************************************/ static bool ReadTexture( SPODTexture &s, CSource &src) { unsigned int nName, nLen; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileTexture | PVRTMODELPOD_TAG_END: return true; case ePODFileTexName: if(!src.ReadAfterAlloc(s.pszName, nLen)) return false; break; default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function ReadScene @Modified s The SPODScene to read into @Input src CSource object to read data from. @Return true if successful @Description Read a scene block in from a pod file *****************************************************************************/ static bool ReadScene( SPODScene &s, CSource &src) { unsigned int nName, nLen; unsigned int nCameras=0, nLights=0, nMaterials=0, nMeshes=0, nTextures=0, nNodes=0; s.nFPS = 30; // Set default for user data s.pUserData = 0; s.nUserDataSize = 0; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileScene | PVRTMODELPOD_TAG_END: if(nCameras != s.nNumCamera) return false; if(nLights != s.nNumLight) return false; if(nMaterials != s.nNumMaterial) return false; if(nMeshes != s.nNumMesh) return false; if(nTextures != s.nNumTexture) return false; if(nNodes != s.nNumNode) return false; return true; case ePODFileColourBackground: if(!src.ReadArray32(&s.pfColourBackground[0], sizeof(s.pfColourBackground) / sizeof(*s.pfColourBackground))) return false; break; case ePODFileColourAmbient: if(!src.ReadArray32(&s.pfColourAmbient[0], sizeof(s.pfColourAmbient) / sizeof(*s.pfColourAmbient))) return false; break; case ePODFileNumCamera: if(!src.Read32(s.nNumCamera)) return false; if(!SafeAlloc(s.pCamera, s.nNumCamera)) return false; break; case ePODFileNumLight: if(!src.Read32(s.nNumLight)) return false; if(!SafeAlloc(s.pLight, s.nNumLight)) return false; break; case ePODFileNumMesh: if(!src.Read32(s.nNumMesh)) return false; if(!SafeAlloc(s.pMesh, s.nNumMesh)) return false; break; case ePODFileNumNode: if(!src.Read32(s.nNumNode)) return false; if(!SafeAlloc(s.pNode, s.nNumNode)) return false; break; case ePODFileNumMeshNode: if(!src.Read32(s.nNumMeshNode)) return false; break; case ePODFileNumTexture: if(!src.Read32(s.nNumTexture)) return false; if(!SafeAlloc(s.pTexture, s.nNumTexture)) return false; break; case ePODFileNumMaterial: if(!src.Read32(s.nNumMaterial)) return false; if(!SafeAlloc(s.pMaterial, s.nNumMaterial)) return false; break; case ePODFileNumFrame: if(!src.Read32(s.nNumFrame)) return false; break; case ePODFileFPS: if(!src.Read32(s.nFPS)) return false; break; case ePODFileFlags: if(!src.Read32(s.nFlags)) return false; break; case ePODFileCamera: if(!ReadCamera(s.pCamera[nCameras++], src)) return false; break; case ePODFileLight: if(!ReadLight(s.pLight[nLights++], src)) return false; break; case ePODFileMaterial: if(!ReadMaterial(s.pMaterial[nMaterials++], src)) return false; break; case ePODFileMesh: if(!ReadMesh(s.pMesh[nMeshes++], src)) return false; break; case ePODFileNode: if(!ReadNode(s.pNode[nNodes++], src)) return false; break; case ePODFileTexture: if(!ReadTexture(s.pTexture[nTextures++], src)) return false; break; case ePODFileUserData: if(!src.ReadAfterAlloc(s.pUserData, nLen)) return false; else { s.nUserDataSize = nLen; break; } default: if(!src.Skip(nLen)) return false; } } return false; } /*!*************************************************************************** @Function Read @Output pS SPODScene data. May be NULL. @Input src CSource object to read data from. @Output pszExpOpt Export options. @Input count Data size. @Output pszHistory Export history. @Input historyCount History data size. @Description Loads the specified ".POD" file; returns the scene in pScene. This structure must later be destroyed with PVRTModelPODDestroy() to prevent memory leaks. ".POD" files are exported from 3D Studio MAX using a PowerVR plugin. pS may be NULL if only the export options are required. *****************************************************************************/ static bool Read( SPODScene * const pS, CSource &src, char * const pszExpOpt, const size_t count, char * const pszHistory, const size_t historyCount) { unsigned int nName, nLen; bool bVersionOK = false, bDone = false; bool bNeedOptions = pszExpOpt != 0; bool bNeedHistory = pszHistory != 0; bool bLoadingOptionsOrHistory = bNeedOptions || bNeedHistory; while(src.ReadMarker(nName, nLen)) { switch(nName) { case ePODFileVersion: { char *pszVersion = NULL; if(nLen != strlen(PVRTMODELPOD_VERSION)+1) return false; if(!SafeAlloc(pszVersion, nLen)) return false; if(!src.Read(pszVersion, nLen)) return false; if(strcmp(pszVersion, PVRTMODELPOD_VERSION) != 0) return false; bVersionOK = true; FREE(pszVersion); } continue; case ePODFileScene: if(pS) { if(!ReadScene(*pS, src)) return false; bDone = true; } continue; case ePODFileExpOpt: if(bNeedOptions) { if(!src.Read(pszExpOpt, PVRT_MIN(nLen, (unsigned int) count))) return false; bNeedOptions = false; if(count < nLen) nLen -= (unsigned int) count ; // Adjust nLen as the read has moved our position else nLen = 0; } break; case ePODFileHistory: if(bNeedHistory) { if(!src.Read(pszHistory, PVRT_MIN(nLen, (unsigned int) historyCount))) return false; bNeedHistory = false; if(count < nLen) nLen -= (unsigned int) historyCount; // Adjust nLen as the read has moved our position else nLen = 0; } break; case ePODFileScene | PVRTMODELPOD_TAG_END: return bVersionOK == true && bDone == true; case (unsigned int) ePODFileEndiannessMisMatch: PVRTErrorOutputDebug("Error: Endianness mismatch between the .pod file and the platform.\n"); return false; } if(bLoadingOptionsOrHistory && !bNeedOptions && !bNeedHistory) return true; // The options and/or history has been loaded // Unhandled data, skip it if(!src.Skip(nLen)) return false; } if(bLoadingOptionsOrHistory) return true; if(!pS) return false; /* Convert data to fixed or float point as this build desires */ #ifdef PVRT_FIXED_POINT_ENABLE if(!(pS->nFlags & PVRTMODELPODSF_FIXED)) { PVRTErrorOutputDebug("Error: The tools have been compiled with fixed point enabled but the POD file isn't in fixed point format.\n"); #else if(pS->nFlags & PVRTMODELPODSF_FIXED) { PVRTErrorOutputDebug("Error: The POD file is in fixed point format but the tools haven't been compiled with fixed point enabled.\n"); #endif return false; } return bVersionOK == true && bDone == true; } /*!*************************************************************************** @Function ReadFromSourceStream @Output pS CPVRTModelPOD data. May not be NULL. @Input src CSource object to read data from. @Output pszExpOpt Export options. @Input count Data size. @Output pszHistory Export history. @Input historyCount History data size. @Description Loads the ".POD" data from the source stream; returns the scene in pS. *****************************************************************************/ static EPVRTError ReadFromSourceStream( CPVRTModelPOD * const pS, CSourceStream &src, char * const pszExpOpt, const size_t count, char * const pszHistory, const size_t historyCount) { memset(pS, 0, sizeof(*pS)); if(!Read(pszExpOpt || pszHistory ? NULL : pS, src, pszExpOpt, count, pszHistory, historyCount)) return PVR_FAIL; if(pS->InitImpl() != PVR_SUCCESS) return PVR_FAIL; return PVR_SUCCESS; } /**************************************************************************** ** Class: CPVRTModelPOD ****************************************************************************/ /*!*************************************************************************** @Function ReadFromFile @Input pszFileName Filename to load @Output pszExpOpt String in which to place exporter options @Input count Maximum number of characters to store. @Output pszHistory String in which to place the pod file history @Input historyCount Maximum number of characters to store. @Return PVR_SUCCESS if successful, PVR_FAIL if not @Description Loads the specified ".POD" file; returns the scene in pScene. This structure must later be destroyed with PVRTModelPODDestroy() to prevent memory leaks. ".POD" files are exported using the PVRGeoPOD exporters. If pszExpOpt is NULL, the scene is loaded; otherwise the scene is not loaded and pszExpOpt is filled in. The same is true for pszHistory. *****************************************************************************/ EPVRTError CPVRTModelPOD::ReadFromFile( const char * const pszFileName, char * const pszExpOpt, const size_t count, char * const pszHistory, const size_t historyCount) { CSourceStream src; if(!src.Init(pszFileName)) return PVR_FAIL; return ReadFromSourceStream(this, src, pszExpOpt, count, pszHistory, historyCount); } /*!*************************************************************************** @Function ReadFromMemory @Input pData Data to load @Input i32Size Size of data @Output pszExpOpt String in which to place exporter options @Input count Maximum number of characters to store. @Output pszHistory String in which to place the pod file history @Input historyCount Maximum number of characters to store. @Return PVR_SUCCESS if successful, PVR_FAIL if not @Description Loads the supplied pod data. This data can be exported directly to a header using one of the pod exporters. If pszExpOpt is NULL, the scene is loaded; otherwise the scene is not loaded and pszExpOpt is filled in. The same is true for pszHistory. *****************************************************************************/ EPVRTError CPVRTModelPOD::ReadFromMemory( const char * pData, const size_t i32Size, char * const pszExpOpt, const size_t count, char * const pszHistory, const size_t historyCount) { CSourceStream src; if(!src.Init(pData, i32Size)) return PVR_FAIL; return ReadFromSourceStream(this, src, pszExpOpt, count, pszHistory, historyCount); } /*!*************************************************************************** @Function ReadFromMemory @Input scene Scene data from the header file @Return PVR_SUCCESS if successful, PVR_FAIL if not @Description Sets the scene data from the supplied data structure. Use when loading from .H files. *****************************************************************************/ EPVRTError CPVRTModelPOD::ReadFromMemory( const SPODScene &scene) { Destroy(); memset(this, 0, sizeof(*this)); *(SPODScene*)this = scene; if(InitImpl() != PVR_SUCCESS) return PVR_FAIL; m_pImpl->bFromMemory = true; return PVR_SUCCESS; } /*!*************************************************************************** @Function CopyFromMemory @Input scene Scene data @Return PVR_SUCCESS if successful, PVR_FAIL if not @Description Sets the scene data from the supplied data structure. *****************************************************************************/ EPVRTError CPVRTModelPOD::CopyFromMemory(const SPODScene &scene) { Destroy(); unsigned int i; // SPODScene nNumFrame = scene.nNumFrame; nFPS = scene.nFPS; nFlags = scene.nFlags; for(i = 0; i < 3; ++i) { pfColourBackground[i] = scene.pfColourBackground[i]; pfColourAmbient[i] = scene.pfColourAmbient[i]; } // Nodes if(scene.nNumNode && SafeAlloc(pNode, scene.nNumNode)) { nNumNode = scene.nNumNode; nNumMeshNode = scene.nNumMeshNode; for(i = 0; i < nNumNode; ++i) PVRTModelPODCopyNode(scene.pNode[i], pNode[i], scene.nNumFrame); } // Meshes if(scene.nNumMesh && SafeAlloc(pMesh, scene.nNumMesh)) { nNumMesh = scene.nNumMesh; for(i = 0; i < nNumMesh; ++i) PVRTModelPODCopyMesh(scene.pMesh[i], pMesh[i]); } // Cameras if(scene.nNumCamera && SafeAlloc(pCamera, scene.nNumCamera)) { nNumCamera = scene.nNumCamera; for(i = 0; i < nNumCamera; ++i) PVRTModelPODCopyCamera(scene.pCamera[i], pCamera[i], scene.nNumFrame); } // Lights if(scene.nNumLight && SafeAlloc(pLight, scene.nNumLight)) { nNumLight = scene.nNumLight; for(i = 0; i < nNumLight; ++i) PVRTModelPODCopyLight(scene.pLight[i], pLight[i]); } // Textures if(scene.nNumTexture && SafeAlloc(pTexture, scene.nNumTexture)) { nNumTexture = scene.nNumTexture; for(i = 0; i < nNumTexture; ++i) PVRTModelPODCopyTexture(scene.pTexture[i], pTexture[i]); } // Materials if(scene.nNumMaterial && SafeAlloc(pMaterial, scene.nNumMaterial)) { nNumMaterial = scene.nNumMaterial; for(i = 0; i < nNumMaterial; ++i) PVRTModelPODCopyMaterial(scene.pMaterial[i], pMaterial[i]); } if(scene.pUserData && SafeAlloc(pUserData, scene.nUserDataSize)) { memcpy(pUserData, scene.pUserData, nUserDataSize); nUserDataSize = scene.nUserDataSize; } if(InitImpl() != PVR_SUCCESS) return PVR_FAIL; return PVR_SUCCESS; } #if defined(_WIN32) /*!*************************************************************************** @Function ReadFromResource @Input pszName Name of the resource to load from @Return PVR_SUCCESS if successful, PVR_FAIL if not @Description Loads the specified ".POD" file; returns the scene in pScene. This structure must later be destroyed with PVRTModelPODDestroy() to prevent memory leaks. ".POD" files are exported from 3D Studio MAX using a PowerVR plugin. *****************************************************************************/ EPVRTError CPVRTModelPOD::ReadFromResource( const TCHAR * const pszName) { CSourceResource src; if(!src.Init(pszName)) return PVR_FAIL; memset(this, 0, sizeof(*this)); if(!Read(this, src, NULL, 0, NULL, 0)) return PVR_FAIL; if(InitImpl() != PVR_SUCCESS) return PVR_FAIL; return PVR_SUCCESS; } #endif /* WIN32 */ /*!*********************************************************************** @Function InitImpl @Description Used by the Read*() fns to initialise implementation details. Should also be called by applications which manually build data in the POD structures for rendering; in this case call it after the data has been created. Otherwise, do not call this function. *************************************************************************/ EPVRTError CPVRTModelPOD::InitImpl() { // Allocate space for implementation data delete m_pImpl; m_pImpl = new SPVRTPODImpl; if(!m_pImpl) return PVR_FAIL; // Zero implementation data memset(m_pImpl, 0, sizeof(*m_pImpl)); #ifdef _DEBUG m_pImpl->nWmTotal = 0; #endif // Allocate world-matrix cache m_pImpl->pfCache = new VERTTYPE[nNumNode]; m_pImpl->pWmCache = new PVRTMATRIX[nNumNode]; m_pImpl->pWmZeroCache = new PVRTMATRIX[nNumNode]; FlushCache(); return PVR_SUCCESS; } /*!*********************************************************************** @Function DestroyImpl @Description Used to free memory allocated by the implementation. *************************************************************************/ void CPVRTModelPOD::DestroyImpl() { if(m_pImpl) { if(m_pImpl->pfCache) delete [] m_pImpl->pfCache; if(m_pImpl->pWmCache) delete [] m_pImpl->pWmCache; if(m_pImpl->pWmZeroCache) delete [] m_pImpl->pWmZeroCache; delete m_pImpl; m_pImpl = 0; } } /*!*********************************************************************** @Function FlushCache @Description Clears the matrix cache; use this if necessary when you edit the position or animation of a node. *************************************************************************/ void CPVRTModelPOD::FlushCache() { // Pre-calc frame zero matrices SetFrame(0); for(unsigned int i = 0; i < nNumNode; ++i) GetWorldMatrixNoCache(m_pImpl->pWmZeroCache[i], pNode[i]); // Load cache with frame-zero data memcpy(m_pImpl->pWmCache, m_pImpl->pWmZeroCache, nNumNode * sizeof(*m_pImpl->pWmCache)); memset(m_pImpl->pfCache, 0, nNumNode * sizeof(*m_pImpl->pfCache)); } /*!*********************************************************************** @Function IsLoaded @Description Boolean to check whether a POD file has been loaded. *************************************************************************/ bool CPVRTModelPOD::IsLoaded() { return (m_pImpl!=NULL); } /*!*************************************************************************** @Function Constructor @Description Initializes the pointer to scene data to NULL *****************************************************************************/ CPVRTModelPOD::CPVRTModelPOD() : m_pImpl(NULL) {} /*!*************************************************************************** @Function Destructor @Description Frees the memory allocated to store the scene in pScene. *****************************************************************************/ CPVRTModelPOD::~CPVRTModelPOD() { Destroy(); } /*!*************************************************************************** @Function Destroy @Description Frees the memory allocated to store the scene in pScene. *****************************************************************************/ void CPVRTModelPOD::Destroy() { unsigned int i; if(m_pImpl != NULL) { /* Only attempt to free this memory if it was actually allocated at run-time, as opposed to compiled into the app. */ if(!m_pImpl->bFromMemory) { for(i = 0; i < nNumCamera; ++i) FREE(pCamera[i].pfAnimFOV); FREE(pCamera); FREE(pLight); for(i = 0; i < nNumMaterial; ++i) { FREE(pMaterial[i].pszName); FREE(pMaterial[i].pszEffectFile); FREE(pMaterial[i].pszEffectName); FREE(pMaterial[i].pUserData); } FREE(pMaterial); for(i = 0; i < nNumMesh; ++i) { FREE(pMesh[i].sFaces.pData); FREE(pMesh[i].pnStripLength); if(pMesh[i].pInterleaved) { FREE(pMesh[i].pInterleaved); } else { FREE(pMesh[i].sVertex.pData); FREE(pMesh[i].sNormals.pData); FREE(pMesh[i].sTangents.pData); FREE(pMesh[i].sBinormals.pData); for(unsigned int j = 0; j < pMesh[i].nNumUVW; ++j) FREE(pMesh[i].psUVW[j].pData); FREE(pMesh[i].sVtxColours.pData); FREE(pMesh[i].sBoneIdx.pData); FREE(pMesh[i].sBoneWeight.pData); } FREE(pMesh[i].psUVW); pMesh[i].sBoneBatches.Release(); } FREE(pMesh); for(i = 0; i < nNumNode; ++i) { FREE(pNode[i].pszName); FREE(pNode[i].pfAnimPosition); FREE(pNode[i].pnAnimPositionIdx); FREE(pNode[i].pfAnimRotation); FREE(pNode[i].pnAnimRotationIdx); FREE(pNode[i].pfAnimScale); FREE(pNode[i].pnAnimScaleIdx); FREE(pNode[i].pfAnimMatrix); FREE(pNode[i].pnAnimMatrixIdx); FREE(pNode[i].pUserData); pNode[i].nAnimFlags = 0; } FREE(pNode); for(i = 0; i < nNumTexture; ++i) FREE(pTexture[i].pszName); FREE(pTexture); FREE(pUserData); } // Free the working space used by the implementation DestroyImpl(); } memset(this, 0, sizeof(*this)); } /*!*************************************************************************** @Function SetFrame @Input fFrame Frame number @Description Set the animation frame for which subsequent Get*() calls should return data. *****************************************************************************/ void CPVRTModelPOD::SetFrame(const VERTTYPE fFrame) { if(nNumFrame) { /* Limit animation frames. Example: If there are 100 frames of animation, the highest frame number allowed is 98, since that will blend between frames 98 and 99. (99 being of course the 100th frame.) */ _ASSERT(fFrame <= f2vt((float)(nNumFrame-1))); m_pImpl->nFrame = (int)vt2f(fFrame); m_pImpl->fBlend = fFrame - f2vt(m_pImpl->nFrame); } else { m_pImpl->fBlend = 0; m_pImpl->nFrame = 0; } m_pImpl->fFrame = fFrame; } /*!*************************************************************************** @Function GetRotationMatrix @Output mOut Rotation matrix @Input node Node to get the rotation matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetRotationMatrix( PVRTMATRIX &mOut, const SPODNode &node) const { PVRTQUATERNION q; if(node.pfAnimRotation) { if(node.nAnimFlags & ePODHasRotationAni) { if(node.pnAnimRotationIdx) { PVRTMatrixQuaternionSlerp( q, (PVRTQUATERNION&)node.pfAnimRotation[node.pnAnimRotationIdx[m_pImpl->nFrame]], (PVRTQUATERNION&)node.pfAnimRotation[node.pnAnimRotationIdx[m_pImpl->nFrame+1]], m_pImpl->fBlend); } else { PVRTMatrixQuaternionSlerp( q, (PVRTQUATERNION&)node.pfAnimRotation[4*m_pImpl->nFrame], (PVRTQUATERNION&)node.pfAnimRotation[4*(m_pImpl->nFrame+1)], m_pImpl->fBlend); } PVRTMatrixRotationQuaternion(mOut, q); } else { PVRTMatrixRotationQuaternion(mOut, *(PVRTQUATERNION*)node.pfAnimRotation); } } else { PVRTMatrixIdentity(mOut); } } /*!*************************************************************************** @Function GetRotationMatrix @Input node Node to get the rotation matrix from @Returns Rotation matrix @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetRotationMatrix(const SPODNode &node) const { PVRTMat4 mOut; GetRotationMatrix(mOut,node); return mOut; } /*!*************************************************************************** @Function GetScalingMatrix @Output mOut Scaling matrix @Input node Node to get the rotation matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetScalingMatrix( PVRTMATRIX &mOut, const SPODNode &node) const { PVRTVECTOR3 v; if(node.pfAnimScale) { if(node.nAnimFlags & ePODHasScaleAni) { if(node.pnAnimScaleIdx) { PVRTMatrixVec3Lerp( v, (PVRTVECTOR3&)node.pfAnimScale[node.pnAnimScaleIdx[m_pImpl->nFrame+0]], (PVRTVECTOR3&)node.pfAnimScale[node.pnAnimScaleIdx[m_pImpl->nFrame+1]], m_pImpl->fBlend); } else { PVRTMatrixVec3Lerp( v, (PVRTVECTOR3&)node.pfAnimScale[7*(m_pImpl->nFrame+0)], (PVRTVECTOR3&)node.pfAnimScale[7*(m_pImpl->nFrame+1)], m_pImpl->fBlend); } PVRTMatrixScaling(mOut, v.x, v.y, v.z); } else { PVRTMatrixScaling(mOut, node.pfAnimScale[0], node.pfAnimScale[1], node.pfAnimScale[2]); } } else { PVRTMatrixIdentity(mOut); } } /*!*************************************************************************** @Function GetScalingMatrix @Input node Node to get the rotation matrix from @Returns Scaling matrix @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetScalingMatrix(const SPODNode &node) const { PVRTMat4 mOut; GetScalingMatrix(mOut, node); return mOut; } /*!*************************************************************************** @Function GetTranslation @Output V Translation vector @Input node Node to get the translation vector from @Description Generates the translation vector for the given Mesh Instance. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetTranslation( PVRTVECTOR3 &V, const SPODNode &node) const { if(node.pfAnimPosition) { if(node.nAnimFlags & ePODHasPositionAni) { if(node.pnAnimPositionIdx) { PVRTMatrixVec3Lerp(V, (PVRTVECTOR3&)node.pfAnimPosition[node.pnAnimPositionIdx[m_pImpl->nFrame+0]], (PVRTVECTOR3&)node.pfAnimPosition[node.pnAnimPositionIdx[m_pImpl->nFrame+1]], m_pImpl->fBlend); } else { PVRTMatrixVec3Lerp(V, (PVRTVECTOR3&)node.pfAnimPosition[3 * (m_pImpl->nFrame+0)], (PVRTVECTOR3&)node.pfAnimPosition[3 * (m_pImpl->nFrame+1)], m_pImpl->fBlend); } } else { V = *(PVRTVECTOR3*) node.pfAnimPosition; } } else { _ASSERT(false); } } /*!*************************************************************************** @Function GetTranslation @Input node Node to get the translation vector from @Returns Translation vector @Description Generates the translation vector for the given Mesh Instance. Uses animation data. *****************************************************************************/ PVRTVec3 CPVRTModelPOD::GetTranslation(const SPODNode &node) const { PVRTVec3 vOut; GetTranslation(vOut, node); return vOut; } /*!*************************************************************************** @Function GetTranslationMatrix @Output mOut Translation matrix @Input node Node to get the translation matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetTranslationMatrix( PVRTMATRIX &mOut, const SPODNode &node) const { PVRTVECTOR3 v; if(node.pfAnimPosition) { if(node.nAnimFlags & ePODHasPositionAni) { if(node.pnAnimPositionIdx) { PVRTMatrixVec3Lerp(v, (PVRTVECTOR3&)node.pfAnimPosition[node.pnAnimPositionIdx[m_pImpl->nFrame+0]], (PVRTVECTOR3&)node.pfAnimPosition[node.pnAnimPositionIdx[m_pImpl->nFrame+1]], m_pImpl->fBlend); } else { PVRTMatrixVec3Lerp(v, (PVRTVECTOR3&)node.pfAnimPosition[3*(m_pImpl->nFrame+0)], (PVRTVECTOR3&)node.pfAnimPosition[3*(m_pImpl->nFrame+1)], m_pImpl->fBlend); } PVRTMatrixTranslation(mOut, v.x, v.y, v.z); } else { PVRTMatrixTranslation(mOut, node.pfAnimPosition[0], node.pfAnimPosition[1], node.pfAnimPosition[2]); } } else { PVRTMatrixIdentity(mOut); } } /*!*************************************************************************** @Function GetTranslationMatrix @Input node Node to get the translation matrix from @Returns Translation matrix @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetTranslationMatrix(const SPODNode &node) const { PVRTMat4 mOut; GetTranslationMatrix(mOut, node); return mOut; } /*!*************************************************************************** @Function GetTransformationMatrix @Output mOut Transformation matrix @Input node Node to get the transformation matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetTransformationMatrix(PVRTMATRIX &mOut, const SPODNode &node) const { if(node.pfAnimMatrix) { if(node.nAnimFlags & ePODHasMatrixAni) { if(node.pnAnimMatrixIdx) mOut = *((PVRTMATRIX*) &node.pfAnimMatrix[node.pnAnimMatrixIdx[m_pImpl->nFrame]]); else mOut = *((PVRTMATRIX*) &node.pfAnimMatrix[16*m_pImpl->nFrame]); } else { mOut = *((PVRTMATRIX*) node.pfAnimMatrix); } } else { PVRTMatrixIdentity(mOut); } } /*!*************************************************************************** @Function GetWorldMatrixNoCache @Output mOut World matrix @Input node Node to get the world matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetWorldMatrixNoCache( PVRTMATRIX &mOut, const SPODNode &node) const { PVRTMATRIX mTmp; if(node.pfAnimMatrix) // The transformations are stored as matrices GetTransformationMatrix(mOut, node); else { // Scale GetScalingMatrix(mOut, node); // Rotation GetRotationMatrix(mTmp, node); PVRTMatrixMultiply(mOut, mOut, mTmp); // Translation GetTranslationMatrix(mTmp, node); PVRTMatrixMultiply(mOut, mOut, mTmp); } // Do we have to worry about a parent? if(node.nIdxParent < 0) return; // Apply parent's transform too. GetWorldMatrixNoCache(mTmp, pNode[node.nIdxParent]); PVRTMatrixMultiply(mOut, mOut, mTmp); } /*!*************************************************************************** @Function GetWorldMatrixNoCache @Input node Node to get the world matrix from @Returns World matrix @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetWorldMatrixNoCache(const SPODNode& node) const { PVRTMat4 mWorld; GetWorldMatrixNoCache(mWorld,node); return mWorld; } /*!*************************************************************************** @Function GetWorldMatrix @Output mOut World matrix @Input node Node to get the world matrix from @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetWorldMatrix( PVRTMATRIX &mOut, const SPODNode &node) const { unsigned int nIdx; #ifdef _DEBUG ++m_pImpl->nWmTotal; m_pImpl->fHitPerc = (float)m_pImpl->nWmCacheHit / (float)m_pImpl->nWmTotal; m_pImpl->fHitPercZero = (float)m_pImpl->nWmZeroCacheHit / (float)m_pImpl->nWmTotal; #endif // Calculate a node index nIdx = (unsigned int)(&node - pNode); // There is a dedicated cache for frame 0 data if(m_pImpl->fFrame == 0) { mOut = m_pImpl->pWmZeroCache[nIdx]; #ifdef _DEBUG ++m_pImpl->nWmZeroCacheHit; #endif return; } // Has this matrix been calculated & cached? if(m_pImpl->fFrame == m_pImpl->pfCache[nIdx]) { mOut = m_pImpl->pWmCache[nIdx]; #ifdef _DEBUG ++m_pImpl->nWmCacheHit; #endif return; } GetWorldMatrixNoCache(mOut, node); // Cache the matrix m_pImpl->pfCache[nIdx] = m_pImpl->fFrame; m_pImpl->pWmCache[nIdx] = mOut; } /*!*************************************************************************** @Function GetWorldMatrix @Input node Node to get the world matrix from @Returns World matrix @Description Generates the world matrix for the given Mesh Instance; applies the parent's transform too. Uses animation data. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetWorldMatrix(const SPODNode& node) const { PVRTMat4 mWorld; GetWorldMatrix(mWorld,node); return mWorld; } /*!*************************************************************************** @Function GetBoneWorldMatrix @Output mOut Bone world matrix @Input NodeMesh Mesh to take the bone matrix from @Input NodeBone Bone to take the matrix from @Description Generates the world matrix for the given bone. *****************************************************************************/ void CPVRTModelPOD::GetBoneWorldMatrix( PVRTMATRIX &mOut, const SPODNode &NodeMesh, const SPODNode &NodeBone) { PVRTMATRIX mTmp; VERTTYPE fFrame; fFrame = m_pImpl->fFrame; SetFrame(0); // Transform by object matrix GetWorldMatrix(mOut, NodeMesh); // Back transform bone from frame 0 position GetWorldMatrix(mTmp, NodeBone); PVRTMatrixInverse(mTmp, mTmp); PVRTMatrixMultiply(mOut, mOut, mTmp); // The bone origin should now be at the origin SetFrame(fFrame); // Transform bone into frame fFrame position GetWorldMatrix(mTmp, NodeBone); PVRTMatrixMultiply(mOut, mOut, mTmp); } /*!*************************************************************************** @Function GetBoneWorldMatrix @Input NodeMesh Mesh to take the bone matrix from @Input NodeBone Bone to take the matrix from @Returns Bone world matrix @Description Generates the world matrix for the given bone. *****************************************************************************/ PVRTMat4 CPVRTModelPOD::GetBoneWorldMatrix( const SPODNode &NodeMesh, const SPODNode &NodeBone) { PVRTMat4 mOut; GetBoneWorldMatrix(mOut,NodeMesh,NodeBone); return mOut; } /*!*************************************************************************** @Function GetCamera @Output vFrom Position of the camera @Output vTo Target of the camera @Output vUp Up direction of the camera @Input nIdx Camera number @Return Camera horizontal FOV @Description Calculate the From, To and Up vectors for the given camera. Uses animation data. Note that even if the camera has a target, *pvTo is not the position of that target. *pvTo is a position in the correct direction of the target, one unit away from the camera. *****************************************************************************/ VERTTYPE CPVRTModelPOD::GetCamera( PVRTVECTOR3 &vFrom, PVRTVECTOR3 &vTo, PVRTVECTOR3 &vUp, const unsigned int nIdx) const { PVRTMATRIX mTmp; VERTTYPE *pfData; SPODCamera *pCam; const SPODNode *pNd; _ASSERT(nIdx < nNumCamera); // Camera nodes are after the mesh and light nodes in the array pNd = &pNode[nNumMeshNode + nNumLight + nIdx]; pCam = &pCamera[pNd->nIdx]; GetWorldMatrix(mTmp, *pNd); // View position is 0,0,0,1 transformed by world matrix vFrom.x = mTmp.f[12]; vFrom.y = mTmp.f[13]; vFrom.z = mTmp.f[14]; // View direction is 0,-1,0,1 transformed by world matrix vTo.x = -mTmp.f[4] + mTmp.f[12]; vTo.y = -mTmp.f[5] + mTmp.f[13]; vTo.z = -mTmp.f[6] + mTmp.f[14]; #if defined(BUILD_DX9) || defined(BUILD_DX10) || defined(BUILD_DX11) /* When you rotate the camera from "straight forward" to "straight down", in D3D the UP vector will be [0, 0, 1] */ vUp.x = mTmp.f[ 8]; vUp.y = mTmp.f[ 9]; vUp.z = mTmp.f[10]; #endif #if defined(BUILD_OGL) || defined(BUILD_OGLES) || defined(BUILD_OGLES2) || defined(BUILD_OGLES3) /* When you rotate the camera from "straight forward" to "straight down", in OpenGL the UP vector will be [0, 0, -1] */ vUp.x = -mTmp.f[ 8]; vUp.y = -mTmp.f[ 9]; vUp.z = -mTmp.f[10]; #endif /* Find & calculate FOV value */ if(pCam->pfAnimFOV) { pfData = &pCam->pfAnimFOV[m_pImpl->nFrame]; return pfData[0] + m_pImpl->fBlend * (pfData[1] - pfData[0]); } else { return pCam->fFOV; } } /*!*************************************************************************** @Function GetCameraPos @Output vFrom Position of the camera @Output vTo Target of the camera @Input nIdx Camera number @Return Camera horizontal FOV @Description Calculate the position of the camera and its target. Uses animation data. If the queried camera does not have a target, *pvTo is not changed. *****************************************************************************/ VERTTYPE CPVRTModelPOD::GetCameraPos( PVRTVECTOR3 &vFrom, PVRTVECTOR3 &vTo, const unsigned int nIdx) const { PVRTMATRIX mTmp; VERTTYPE *pfData; SPODCamera *pCam; const SPODNode *pNd; _ASSERT(nIdx < nNumCamera); // Camera nodes are after the mesh and light nodes in the array pNd = &pNode[nNumMeshNode + nNumLight + nIdx]; // View position is 0,0,0,1 transformed by world matrix GetWorldMatrix(mTmp, *pNd); vFrom.x = mTmp.f[12]; vFrom.y = mTmp.f[13]; vFrom.z = mTmp.f[14]; pCam = &pCamera[pNd->nIdx]; if(pCam->nIdxTarget >= 0) { // View position is 0,0,0,1 transformed by world matrix GetWorldMatrix(mTmp, pNode[pCam->nIdxTarget]); vTo.x = mTmp.f[12]; vTo.y = mTmp.f[13]; vTo.z = mTmp.f[14]; } /* Find & calculate FOV value */ if(pCam->pfAnimFOV) { pfData = &pCam->pfAnimFOV[m_pImpl->nFrame]; return pfData[0] + m_pImpl->fBlend * (pfData[1] - pfData[0]); } else { return pCam->fFOV; } } /*!*************************************************************************** @Function GetLight @Output vPos Position of the light @Output vDir Direction of the light @Input nIdx Light number @Description Calculate the position and direction of the given Light. Uses animation data. *****************************************************************************/ void CPVRTModelPOD::GetLight( PVRTVECTOR3 &vPos, PVRTVECTOR3 &vDir, const unsigned int nIdx) const { PVRTMATRIX mTmp; const SPODNode *pNd; _ASSERT(nIdx < nNumLight); // Light nodes are after the mesh nodes in the array pNd = &pNode[nNumMeshNode + nIdx]; GetWorldMatrix(mTmp, *pNd); // View position is 0,0,0,1 transformed by world matrix vPos.x = mTmp.f[12]; vPos.y = mTmp.f[13]; vPos.z = mTmp.f[14]; // View direction is 0,-1,0,0 transformed by world matrix vDir.x = -mTmp.f[4]; vDir.y = -mTmp.f[5]; vDir.z = -mTmp.f[6]; } /*!*************************************************************************** @Function GetLightPositon @Input u32Idx Light number @Return PVRTVec4 position of light with w set correctly @Description Calculates the position of the given light. Uses animation data *****************************************************************************/ PVRTVec4 CPVRTModelPOD::GetLightPosition(const unsigned int u32Idx) const { // TODO: make this a real function instead of just wrapping GetLight() PVRTVec3 vPos, vDir; GetLight(vPos,vDir,u32Idx); _ASSERT(u32Idx < nNumLight); _ASSERT(pLight[u32Idx].eType!=ePODDirectional); return PVRTVec4(vPos,1); } /*!*************************************************************************** @Function GetLightDirection @Input u32Idx Light number @Return PVRTVec4 direction of light with w set correctly @Description Calculate the direction of the given Light. Uses animation data. *****************************************************************************/ PVRTVec4 CPVRTModelPOD::GetLightDirection(const unsigned int u32Idx) const { // TODO: make this a real function instead of just wrapping GetLight() PVRTVec3 vPos, vDir; GetLight(vPos,vDir,u32Idx); _ASSERT(u32Idx < nNumLight); _ASSERT(pLight[u32Idx].eType!=ePODPoint); return PVRTVec4(vDir,0); } /*!*************************************************************************** @Function CreateSkinIdxWeight @Output pIdx Four bytes containing matrix indices for vertex (0..255) (D3D: use UBYTE4) @Output pWeight Four bytes containing blend weights for vertex (0.0 .. 1.0) (D3D: use D3DCOLOR) @Input nVertexBones Number of bones this vertex uses @Input pnBoneIdx Pointer to 'nVertexBones' indices @Input pfBoneWeight Pointer to 'nVertexBones' blend weights @Description Creates the matrix indices and blend weights for a boned vertex. Call once per vertex of a boned mesh. *****************************************************************************/ EPVRTError CPVRTModelPOD::CreateSkinIdxWeight( char * const pIdx, // Four bytes containing matrix indices for vertex (0..255) (D3D: use UBYTE4) char * const pWeight, // Four bytes containing blend weights for vertex (0.0 .. 1.0) (D3D: use D3DCOLOR) const int nVertexBones, // Number of bones this vertex uses const int * const pnBoneIdx, // Pointer to 'nVertexBones' indices const VERTTYPE * const pfBoneWeight) // Pointer to 'nVertexBones' blend weights { int i, nSum; int nIdx[4]; int nWeight[4]; for(i = 0; i < nVertexBones; ++i) { nIdx[i] = pnBoneIdx[i]; nWeight[i] = (int)vt2f((VERTTYPEMUL(f2vt(255.0f), pfBoneWeight[i]))); if(nIdx[i] > 255) { PVRTErrorOutputDebug("Too many bones (highest index is 255).\n"); return PVR_FAIL; } nWeight[i] = PVRT_MAX(nWeight[i], 0); nWeight[i] = PVRT_MIN(nWeight[i], 255); } for(; i < 4; ++i) { nIdx[i] = 0; nWeight[i] = 0; } if(nVertexBones) { // It's important the weights sum to 1 nSum = 0; for(i = 0; i < 4; ++i) nSum += nWeight[i]; if(!nSum) return PVR_FAIL; _ASSERT(nSum <= 255); i = 0; while(nSum < 255) { if(nWeight[i]) { ++nWeight[i]; ++nSum; } if(++i > 3) i = 0; } _ASSERT(nSum == 255); } #if defined(BUILD_DX9) && defined(BUILD_DX10) && defined(BUILD_DX11) *(unsigned int*)pIdx = D3DCOLOR_ARGB(nIdx[3], nIdx[2], nIdx[1], nIdx[0]); // UBYTE4 is WZYX *(unsigned int*)pWeight = D3DCOLOR_RGBA(nWeight[0], nWeight[1], nWeight[2], nWeight[3]); // D3DCOLORs are WXYZ #endif #if defined(BUILD_OGL) || defined(BUILD_OGLES) || defined(BUILD_OGLES2) || defined(BUILD_OGLES3) // Return indices and weights as bytes for(i = 0; i < 4; ++i) { pIdx[i] = (char) nIdx[i]; pWeight[i] = (char) nWeight[i]; } #endif return PVR_SUCCESS; } /*!*************************************************************************** @Function SavePOD @Input pszFilename Filename to save to @Input pszExpOpt A string containing the options used by the exporter @Description Save a binary POD file (.POD). *****************************************************************************/ EPVRTError CPVRTModelPOD::SavePOD(const char * const pszFilename, const char * const pszExpOpt, const char * const pszHistory) { FILE *pFile; bool bRet; pFile = fopen(pszFilename, "wb+"); if(!pFile) return PVR_FAIL; bRet = WritePOD(pFile, pszExpOpt, pszHistory, *this); // Done fclose(pFile); return bRet ? PVR_SUCCESS : PVR_FAIL; } /*!*************************************************************************** @Function PVRTModelPODDataTypeSize @Input type Type to get the size of @Return Size of the data element @Description Returns the size of each data element. *****************************************************************************/ PVRTuint32 PVRTModelPODDataTypeSize(const EPVRTDataType type) { switch(type) { default: _ASSERT(false); return 0; case EPODDataFloat: return static_cast<PVRTuint32>(sizeof(float)); case EPODDataInt: case EPODDataUnsignedInt: return static_cast<PVRTuint32>(sizeof(int)); case EPODDataShort: case EPODDataShortNorm: case EPODDataUnsignedShort: case EPODDataUnsignedShortNorm: return static_cast<PVRTuint32>(sizeof(unsigned short)); case EPODDataRGBA: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataABGR: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataARGB: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataD3DCOLOR: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataUBYTE4: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataDEC3N: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataFixed16_16: return static_cast<PVRTuint32>(sizeof(unsigned int)); case EPODDataUnsignedByte: case EPODDataUnsignedByteNorm: case EPODDataByte: case EPODDataByteNorm: return static_cast<PVRTuint32>(sizeof(unsigned char)); } } /*!*************************************************************************** @Function PVRTModelPODDataTypeComponentCount @Input type Type to get the number of components from @Return number of components in the data element @Description Returns the number of components in a data element. *****************************************************************************/ PVRTuint32 PVRTModelPODDataTypeComponentCount(const EPVRTDataType type) { switch(type) { default: _ASSERT(false); return 0; case EPODDataFloat: case EPODDataInt: case EPODDataUnsignedInt: case EPODDataShort: case EPODDataShortNorm: case EPODDataUnsignedShort: case EPODDataUnsignedShortNorm: case EPODDataFixed16_16: case EPODDataByte: case EPODDataByteNorm: case EPODDataUnsignedByte: case EPODDataUnsignedByteNorm: return 1; case EPODDataDEC3N: return 3; case EPODDataRGBA: case EPODDataABGR: case EPODDataARGB: case EPODDataD3DCOLOR: case EPODDataUBYTE4: return 4; } } /*!*************************************************************************** @Function PVRTModelPODDataStride @Input data Data elements @Return Size of the vector elements @Description Returns the size of the vector of data elements. *****************************************************************************/ PVRTuint32 PVRTModelPODDataStride(const CPODData &data) { return PVRTModelPODDataTypeSize(data.eType) * data.n; } /*!*************************************************************************** @Function PVRTModelPODDataConvert @Modified data Data elements to convert @Input eNewType New type of elements @Input nCnt Number of elements @Description Convert the format of the array of vectors. *****************************************************************************/ void PVRTModelPODDataConvert(CPODData &data, const unsigned int nCnt, const EPVRTDataType eNewType) { PVRTVECTOR4f v; unsigned int i; CPODData old; if(!data.pData || data.eType == eNewType) return; old = data; switch(eNewType) { case EPODDataFloat: case EPODDataInt: case EPODDataUnsignedInt: case EPODDataUnsignedShort: case EPODDataUnsignedShortNorm: case EPODDataFixed16_16: case EPODDataUnsignedByte: case EPODDataUnsignedByteNorm: case EPODDataShort: case EPODDataShortNorm: case EPODDataByte: case EPODDataByteNorm: data.n = (PVRTuint32) (old.n * PVRTModelPODDataTypeComponentCount(old.eType)); break; case EPODDataRGBA: case EPODDataABGR: case EPODDataARGB: case EPODDataD3DCOLOR: case EPODDataUBYTE4: case EPODDataDEC3N: data.n = 1; break; default: _ASSERT(false); // unrecognised type break; } data.eType = eNewType; data.nStride = (unsigned int)PVRTModelPODDataStride(data); // If the old & new strides are identical, we can convert it in place if(old.nStride != data.nStride) { data.pData = (unsigned char*)malloc(data.nStride * nCnt); } for(i = 0; i < nCnt; ++i) { PVRTVertexRead(&v, old.pData + i * old.nStride, old.eType, old.n); PVRTVertexWrite(data.pData + i * data.nStride, eNewType, (int) (data.n * PVRTModelPODDataTypeComponentCount(data.eType)), &v); } if(old.nStride != data.nStride) { FREE(old.pData); } } /*!*************************************************************************** @Function PVRTModelPODScaleAndConvertVtxData @Modified mesh POD mesh to scale and convert the mesh data @Input eNewType The data type to scale and convert the vertex data to @Return PVR_SUCCESS on success and PVR_FAIL on failure. @Description Scales the vertex data to fit within the range of the requested data type and then converts the data to that type. This function isn't currently compiled in for fixed point builds of the tools. *****************************************************************************/ #if !defined(PVRT_FIXED_POINT_ENABLE) EPVRTError PVRTModelPODScaleAndConvertVtxData(SPODMesh &mesh, const EPVRTDataType eNewType) { // Initialise the matrix to identity PVRTMatrixIdentity(mesh.mUnpackMatrix); // No vertices to process if(!mesh.nNumVertex) return PVR_SUCCESS; // This function expects the data to be floats and not interleaved if(mesh.sVertex.eType != EPODDataFloat && mesh.pInterleaved != 0) return PVR_FAIL; if(eNewType == EPODDataFloat) // Nothing to do return PVR_FAIL; // A few variables float fLower = 0.0f, fUpper = 0.0f; PVRTBOUNDINGBOX BoundingBox; PVRTMATRIX mOffset, mScale; PVRTVECTOR4 v,o; // Set the w component of o as it is needed for later o.w = 1.0f; // Calc bounding box PVRTBoundingBoxComputeInterleaved(&BoundingBox, mesh.sVertex.pData, mesh.nNumVertex, 0, mesh.sVertex.nStride); // Get new type data range that we wish to scale the data to // Due to a hardware bug in early MBXs in some cases we clamp the data to the minimum possible value +1 switch(eNewType) { case EPODDataInt: fUpper = 1 << 30; fLower = -fUpper; break; case EPODDataUnsignedInt: fUpper = 1 << 30; break; case EPODDataShort: case EPODDataFixed16_16: fUpper = 32767.0f; fLower = -fUpper; break; case EPODDataUnsignedShort: fUpper = 0x0ffff; break; case EPODDataRGBA: case EPODDataABGR: case EPODDataARGB: case EPODDataD3DCOLOR: fUpper = 1.0f; break; case EPODDataUBYTE4: case EPODDataUnsignedByte: fUpper = 0x0ff; break; case EPODDataShortNorm: case EPODDataUnsignedShortNorm: case EPODDataByteNorm: case EPODDataUnsignedByteNorm: fUpper = 1.0f; fLower = -fUpper; break; case EPODDataDEC3N: fUpper = 511.0f; fLower = -fUpper; break; case EPODDataByte: fUpper = 127.0f; fLower = -fUpper; break; default: _ASSERT(false); return PVR_FAIL; // Unsupported format specified } PVRTVECTOR3f vScale, vOffset; float fRange = fUpper - fLower; vScale.x = fRange / (BoundingBox.Point[7].x - BoundingBox.Point[0].x); vScale.y = fRange / (BoundingBox.Point[7].y - BoundingBox.Point[0].y); vScale.z = fRange / (BoundingBox.Point[7].z - BoundingBox.Point[0].z); vOffset.x = -BoundingBox.Point[0].x; vOffset.y = -BoundingBox.Point[0].y; vOffset.z = -BoundingBox.Point[0].z; PVRTMatrixTranslation(mOffset, -fLower, -fLower, -fLower); PVRTMatrixScaling(mScale, 1.0f / vScale.x, 1.0f / vScale.y, 1.0f / vScale.z); PVRTMatrixMultiply(mesh.mUnpackMatrix, mOffset, mScale); PVRTMatrixTranslation(mOffset, -vOffset.x, -vOffset.y, -vOffset.z); PVRTMatrixMultiply(mesh.mUnpackMatrix, mesh.mUnpackMatrix, mOffset); // Transform vertex data for(unsigned int i = 0; i < mesh.nNumVertex; ++i) { PVRTVertexRead(&v, mesh.sVertex.pData + i * mesh.sVertex.nStride, mesh.sVertex.eType, mesh.sVertex.n); o.x = (v.x + vOffset.x) * vScale.x + fLower; o.y = (v.y + vOffset.y) * vScale.y + fLower; o.z = (v.z + vOffset.z) * vScale.z + fLower; _ASSERT((o.x >= fLower && o.x <= fUpper) || fabs(1.0f - o.x / fLower) < 0.01f || fabs(1.0f - o.x / fUpper) < 0.01f); _ASSERT((o.y >= fLower && o.y <= fUpper) || fabs(1.0f - o.y / fLower) < 0.01f || fabs(1.0f - o.y / fUpper) < 0.01f); _ASSERT((o.z >= fLower && o.z <= fUpper) || fabs(1.0f - o.z / fLower) < 0.01f || fabs(1.0f - o.z / fUpper) < 0.01f); #if defined(_DEBUG) PVRTVECTOR4 res; PVRTTransform(&res, &o, &mesh.mUnpackMatrix); _ASSERT(fabs(res.x - v.x) <= 0.02); _ASSERT(fabs(res.y - v.y) <= 0.02); _ASSERT(fabs(res.z - v.z) <= 0.02); _ASSERT(fabs(res.w - 1.0) <= 0.02); #endif PVRTVertexWrite(mesh.sVertex.pData + i * mesh.sVertex.nStride, mesh.sVertex.eType, (int) (mesh.sVertex.n * PVRTModelPODDataTypeComponentCount(mesh.sVertex.eType)), &o); } // Convert the data to the chosen format PVRTModelPODDataConvert(mesh.sVertex, mesh.nNumVertex, eNewType); return PVR_SUCCESS; } #endif /*!*************************************************************************** @Function PVRTModelPODDataShred @Modified data Data elements to modify @Input nCnt Number of elements @Input pChannels A list of the wanted channels, e.g. {'x', 'y', 0} @Description Reduce the number of dimensions in 'data' using the requested channel array. The array should have a maximum length of 4 or be null terminated if less channels are wanted. It is also possible to negate an element, e.g. {'x','y', -'z'}. *****************************************************************************/ void PVRTModelPODDataShred(CPODData &data, const unsigned int nCnt, const int * pChannels) { CPODData old; PVRTVECTOR4f v,o; float * const pv = &v.x; float * const po = &o.x; unsigned int i, nCh; int i32Map[4]; bool bNegate[4]; if(!data.pData || !pChannels) return; old = data; // Count the number of output channels while setting up cMap and bNegate for(data.n = 0; data.n < 4 && pChannels[data.n]; ++data.n) { i32Map[data.n] = abs(pChannels[data.n]) == 'w' ? 3 : abs(pChannels[data.n]) - 'x'; bNegate[data.n] = pChannels[data.n] < 0; } if(data.n > old.n) data.n = old.n; // Allocate output memory data.nStride = (unsigned int)PVRTModelPODDataStride(data); if(data.nStride == 0) { FREE(data.pData); return; } data.pData = (unsigned char*)malloc(data.nStride * nCnt); for(i = 0; i < nCnt; ++i) { // Read the vector PVRTVertexRead(&v, old.pData + i * old.nStride, old.eType, old.n); // Shred the vector for(nCh = 0; nCh < 4 && pChannels[nCh]; ++nCh) po[nCh] = bNegate[nCh] ? -pv[i32Map[nCh]] : pv[i32Map[nCh]]; for(; nCh < 4; ++nCh) po[nCh] = 0; // Write the vector PVRTVertexWrite((char*)data.pData + i * data.nStride, data.eType, (int) (data.n * PVRTModelPODDataTypeComponentCount(data.eType)), &o); } FREE(old.pData); } /*!*************************************************************************** @Function PVRTModelPODReorderFaces @Modified mesh The mesh to re-order the faces of @Input i32El1 The first index to be written out @Input i32El2 The second index to be written out @Input i32El3 The third index to be written out @Description Reorders the face indices of a mesh. *****************************************************************************/ void PVRTModelPODReorderFaces(SPODMesh &mesh, const int i32El1, const int i32El2, const int i32El3) { if(!mesh.sFaces.pData) return; unsigned int ui32V[3]; for(unsigned int i = 0; i < mesh.nNumFaces * 3; i += 3) { unsigned char *pData = mesh.sFaces.pData + i * mesh.sFaces.nStride; // Read PVRTVertexRead(&ui32V[0], pData, mesh.sFaces.eType); PVRTVertexRead(&ui32V[1], pData + mesh.sFaces.nStride, mesh.sFaces.eType); PVRTVertexRead(&ui32V[2], pData + 2 * mesh.sFaces.nStride, mesh.sFaces.eType); // Write in place the new order PVRTVertexWrite(pData, mesh.sFaces.eType, ui32V[i32El1]); PVRTVertexWrite(pData + mesh.sFaces.nStride, mesh.sFaces.eType, ui32V[i32El2]); PVRTVertexWrite(pData + 2 * mesh.sFaces.nStride, mesh.sFaces.eType, ui32V[i32El3]); } } /*!*************************************************************************** @Function InterleaveArray @Modified pInterleaved @Modified data @Input nNumVertex @Input nStride @Input nPadding @Input nOffset @Description Interleaves the pod data *****************************************************************************/ static void InterleaveArray( char * const pInterleaved, CPODData &data, const PVRTuint32 nNumVertex, const PVRTuint32 nStride, const PVRTuint32 nPadding, PVRTuint32 &nOffset) { if(!data.nStride) return; for(PVRTuint32 i = 0; i < nNumVertex; ++i) memcpy(pInterleaved + i * nStride + nOffset, (char*)data.pData + i * data.nStride, data.nStride); FREE(data.pData); data.pData = ((unsigned char*)0 + nOffset); // patched for cocos3d by Bill Hollings data.nStride = nStride; nOffset += PVRTModelPODDataStride(data) + nPadding; } /*!*************************************************************************** @Function DeinterleaveArray @Input data @Input pInter @Input nNumVertex @Description DeInterleaves the pod data *****************************************************************************/ static void DeinterleaveArray( CPODData &data, const void * const pInter, const PVRTuint32 nNumVertex, const PVRTuint32 nAlignToNBytes) { const PVRTuint32 nSrcStride = data.nStride; const PVRTuint32 nDestStride= PVRTModelPODDataStride(data); const PVRTuint32 nAlignedStride = nDestStride + ((nAlignToNBytes - nDestStride % nAlignToNBytes) % nAlignToNBytes); const char *pSrc = (char*)pInter + (size_t)data.pData; if(!nSrcStride) return; data.pData = 0; SafeAlloc(data.pData, nAlignedStride * nNumVertex); data.nStride = nAlignedStride; for(PVRTuint32 i = 0; i < nNumVertex; ++i) memcpy((char*)data.pData + i * nAlignedStride, pSrc + i * nSrcStride, nDestStride); } /*!*************************************************************************** @Function PVRTModelPODToggleInterleaved @Modified mesh Mesh to modify @Input ui32AlignToNBytes Align the interleaved data to this no. of bytes. @Description Switches the supplied mesh to or from interleaved data format. *****************************************************************************/ void PVRTModelPODToggleInterleaved(SPODMesh &mesh, const PVRTuint32 ui32AlignToNBytes) { unsigned int i; if(!mesh.nNumVertex) return; if(mesh.pInterleaved) { /* De-interleave */ DeinterleaveArray(mesh.sVertex, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sNormals, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sTangents, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sBinormals, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); for(i = 0; i < mesh.nNumUVW; ++i) DeinterleaveArray(mesh.psUVW[i], mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sVtxColours, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sBoneIdx, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); DeinterleaveArray(mesh.sBoneWeight, mesh.pInterleaved, mesh.nNumVertex, ui32AlignToNBytes); FREE(mesh.pInterleaved); } else { PVRTuint32 nStride, nOffset, nBytes; #define NEEDED_PADDING(x) ((x && ui32AlignToNBytes) ? (ui32AlignToNBytes - x % ui32AlignToNBytes) % ui32AlignToNBytes : 0) // Interleave PVRTuint32 nVertexStride, nNormalStride, nTangentStride, nBinormalStride, nVtxColourStride, nBoneIdxStride, nBoneWeightStride; PVRTuint32 nUVWStride[8]; PVRTuint32 nVertexPadding, nNormalPadding, nTangentPadding, nBinormalPadding, nVtxColourPadding, nBoneIdxPadding, nBoneWeightPadding; PVRTuint32 nUVWPadding[8]; _ASSERT(mesh.nNumUVW < 8); nStride = nVertexStride = PVRTModelPODDataStride(mesh.sVertex); nStride += nVertexPadding = NEEDED_PADDING(nVertexStride); nStride += nNormalStride = PVRTModelPODDataStride(mesh.sNormals); nStride += nNormalPadding = NEEDED_PADDING(nNormalStride); nStride += nTangentStride = PVRTModelPODDataStride(mesh.sTangents); nStride += nTangentPadding = NEEDED_PADDING(nTangentStride); nStride += nBinormalStride = PVRTModelPODDataStride(mesh.sBinormals); nStride += nBinormalPadding = NEEDED_PADDING(nBinormalStride); for(i = 0; i < mesh.nNumUVW; ++i) { nStride += nUVWStride[i] = PVRTModelPODDataStride(mesh.psUVW[i]); nStride += nUVWPadding[i] = NEEDED_PADDING(nUVWStride[i]); } nStride += nVtxColourStride = PVRTModelPODDataStride(mesh.sVtxColours); nStride += nVtxColourPadding = NEEDED_PADDING(nVtxColourStride); nStride += nBoneIdxStride = PVRTModelPODDataStride(mesh.sBoneIdx); nStride += nBoneIdxPadding = NEEDED_PADDING(nBoneIdxStride); nStride += nBoneWeightStride = PVRTModelPODDataStride(mesh.sBoneWeight); nStride += nBoneWeightPadding = NEEDED_PADDING(nBoneWeightStride); #undef NEEDED_PADDING // Allocate interleaved array SafeAlloc(mesh.pInterleaved, mesh.nNumVertex * nStride); // Interleave the data nOffset = 0; for(nBytes = 4; nBytes > 0; nBytes >>= 1) { if(PVRTModelPODDataTypeSize(mesh.sVertex.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sVertex, mesh.nNumVertex, nStride, nVertexPadding, nOffset); if(PVRTModelPODDataTypeSize(mesh.sNormals.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sNormals, mesh.nNumVertex, nStride, nNormalPadding, nOffset); if(PVRTModelPODDataTypeSize(mesh.sTangents.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sTangents, mesh.nNumVertex, nStride, nTangentPadding, nOffset); if(PVRTModelPODDataTypeSize(mesh.sBinormals.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sBinormals, mesh.nNumVertex, nStride, nBinormalPadding, nOffset); if(PVRTModelPODDataTypeSize(mesh.sVtxColours.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sVtxColours, mesh.nNumVertex, nStride, nVtxColourPadding, nOffset); for(i = 0; i < mesh.nNumUVW; ++i) { if(PVRTModelPODDataTypeSize(mesh.psUVW[i].eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.psUVW[i], mesh.nNumVertex, nStride, nUVWPadding[i], nOffset); } if(PVRTModelPODDataTypeSize(mesh.sBoneIdx.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sBoneIdx, mesh.nNumVertex, nStride, nBoneIdxPadding, nOffset); if(PVRTModelPODDataTypeSize(mesh.sBoneWeight.eType) == nBytes) InterleaveArray((char*)mesh.pInterleaved, mesh.sBoneWeight, mesh.nNumVertex, nStride, nBoneWeightPadding, nOffset); } } } /*!*************************************************************************** @Function PVRTModelPODDeIndex @Modified mesh Mesh to modify @Description De-indexes the supplied mesh. The mesh must be Interleaved before calling this function. *****************************************************************************/ void PVRTModelPODDeIndex(SPODMesh &mesh) { unsigned char *pNew = 0; if(!mesh.pInterleaved || !mesh.nNumVertex) return; _ASSERT(mesh.nNumVertex && mesh.nNumFaces); // Create a new vertex list mesh.nNumVertex = PVRTModelPODCountIndices(mesh); SafeAlloc(pNew, mesh.sVertex.nStride * mesh.nNumVertex); // Deindex the vertices if(mesh.sFaces.eType == EPODDataUnsignedShort) { for(unsigned int i = 0; i < mesh.nNumVertex; ++i) memcpy(pNew + i * mesh.sVertex.nStride, (char*)mesh.pInterleaved + ((unsigned short*)mesh.sFaces.pData)[i] * mesh.sVertex.nStride, mesh.sVertex.nStride); } else { _ASSERT(mesh.sFaces.eType == EPODDataUnsignedInt); for(unsigned int i = 0; i < mesh.nNumVertex; ++i) memcpy(pNew + i * mesh.sVertex.nStride, (char*)mesh.pInterleaved + ((unsigned int*)mesh.sFaces.pData)[i] * mesh.sVertex.nStride, mesh.sVertex.nStride); } // Replace the old vertex list FREE(mesh.pInterleaved); mesh.pInterleaved = pNew; // Get rid of the index list FREE(mesh.sFaces.pData); mesh.sFaces.n = 0; mesh.sFaces.nStride = 0; } /*!*************************************************************************** @Function PVRTModelPODToggleStrips @Modified mesh Mesh to modify @Description Converts the supplied mesh to or from strips. *****************************************************************************/ void PVRTModelPODToggleStrips(SPODMesh &mesh) { CPODData old; size_t nIdxSize, nTriStride; if(!mesh.nNumFaces) return; _ASSERT(mesh.sFaces.n == 1); nIdxSize = PVRTModelPODDataTypeSize(mesh.sFaces.eType); nTriStride = PVRTModelPODDataStride(mesh.sFaces) * 3; old = mesh.sFaces; mesh.sFaces.pData = 0; SafeAlloc(mesh.sFaces.pData, nTriStride * mesh.nNumFaces); if(mesh.nNumStrips) { unsigned int nListIdxCnt, nStripIdxCnt; // Convert to list nListIdxCnt = 0; nStripIdxCnt = 0; for(unsigned int i = 0; i < mesh.nNumStrips; ++i) { for(unsigned int j = 0; j < mesh.pnStripLength[i]; ++j) { if(j) { _ASSERT(j == 1); // Because this will surely break with any other number memcpy( (char*)mesh.sFaces.pData + nIdxSize * nListIdxCnt, (char*)old.pData + nIdxSize * (nStripIdxCnt - 1), nIdxSize); nListIdxCnt += 1; memcpy( (char*)mesh.sFaces.pData + nIdxSize * nListIdxCnt, (char*)old.pData + nIdxSize * (nStripIdxCnt - 2), nIdxSize); nListIdxCnt += 1; memcpy( (char*)mesh.sFaces.pData + nIdxSize * nListIdxCnt, (char*)old.pData + nIdxSize * nStripIdxCnt, nIdxSize); nListIdxCnt += 1; nStripIdxCnt += 1; } else { memcpy( (char*)mesh.sFaces.pData + nIdxSize * nListIdxCnt, (char*)old.pData + nIdxSize * nStripIdxCnt, nTriStride); nStripIdxCnt += 3; nListIdxCnt += 3; } } } _ASSERT(nListIdxCnt == mesh.nNumFaces*3); FREE(mesh.pnStripLength); mesh.nNumStrips = 0; } else { int nIdxCnt; int nBatchCnt; unsigned int n0, n1, n2; unsigned int p0, p1, p2, nFaces; unsigned char* pFaces; // Convert to strips mesh.pnStripLength = (unsigned int*)calloc(mesh.nNumFaces, sizeof(*mesh.pnStripLength)); mesh.nNumStrips = 0; nIdxCnt = 0; nBatchCnt = mesh.sBoneBatches.nBatchCnt ? mesh.sBoneBatches.nBatchCnt : 1; for(int h = 0; h < nBatchCnt; ++h) { n0 = 0; n1 = 0; n2 = 0; if(!mesh.sBoneBatches.nBatchCnt) { nFaces = mesh.nNumFaces; pFaces = old.pData; } else { if(h + 1 < mesh.sBoneBatches.nBatchCnt) nFaces = mesh.sBoneBatches.pnBatchOffset[h+1] - mesh.sBoneBatches.pnBatchOffset[h]; else nFaces = mesh.nNumFaces - mesh.sBoneBatches.pnBatchOffset[h]; pFaces = &old.pData[3 * mesh.sBoneBatches.pnBatchOffset[h] * old.nStride]; } for(unsigned int i = 0; i < nFaces; ++i) { p0 = n0; p1 = n1; p2 = n2; PVRTVertexRead(&n0, (char*)pFaces + (3 * i + 0) * old.nStride, old.eType); PVRTVertexRead(&n1, (char*)pFaces + (3 * i + 1) * old.nStride, old.eType); PVRTVertexRead(&n2, (char*)pFaces + (3 * i + 2) * old.nStride, old.eType); if(mesh.pnStripLength[mesh.nNumStrips]) { if(mesh.pnStripLength[mesh.nNumStrips] & 0x01) { if(p1 == n1 && p2 == n0) { PVRTVertexWrite((char*)mesh.sFaces.pData + nIdxCnt * mesh.sFaces.nStride, mesh.sFaces.eType, n2); ++nIdxCnt; mesh.pnStripLength[mesh.nNumStrips] += 1; continue; } } else { if(p2 == n1 && p0 == n0) { PVRTVertexWrite((char*)mesh.sFaces.pData + nIdxCnt * mesh.sFaces.nStride, mesh.sFaces.eType, n2); ++nIdxCnt; mesh.pnStripLength[mesh.nNumStrips] += 1; continue; } } ++mesh.nNumStrips; } // Start of strip, copy entire triangle PVRTVertexWrite((char*)mesh.sFaces.pData + nIdxCnt * mesh.sFaces.nStride, mesh.sFaces.eType, n0); ++nIdxCnt; PVRTVertexWrite((char*)mesh.sFaces.pData + nIdxCnt * mesh.sFaces.nStride, mesh.sFaces.eType, n1); ++nIdxCnt; PVRTVertexWrite((char*)mesh.sFaces.pData + nIdxCnt * mesh.sFaces.nStride, mesh.sFaces.eType, n2); ++nIdxCnt; mesh.pnStripLength[mesh.nNumStrips] += 1; } } if(mesh.pnStripLength[mesh.nNumStrips]) ++mesh.nNumStrips; SafeRealloc(mesh.sFaces.pData, nIdxCnt * nIdxSize); mesh.pnStripLength = (unsigned int*)realloc(mesh.pnStripLength, sizeof(*mesh.pnStripLength) * mesh.nNumStrips); } FREE(old.pData); } /*!*************************************************************************** @Function PVRTModelPODCountIndices @Input mesh Mesh @Return Number of indices used by mesh @Description Counts the number of indices of a mesh *****************************************************************************/ unsigned int PVRTModelPODCountIndices(const SPODMesh &mesh) { return mesh.nNumStrips ? mesh.nNumFaces + (mesh.nNumStrips * 2) : mesh.nNumFaces * 3; } /*!*************************************************************************** @Function PVRTModelPODCopyCPODData @Input in @Output out @Input ui32No @Input bInterleaved @Description Used to copy a CPODData of a mesh *****************************************************************************/ void PVRTModelPODCopyCPODData(const CPODData &in, CPODData &out, unsigned int ui32No, bool bInterleaved) { FREE(out.pData); out.eType = in.eType; out.n = in.n; out.nStride = in.nStride; if(bInterleaved) { out.pData = in.pData; } else if(in.pData) { size_t ui32Size = PVRTModelPODDataStride(out) * ui32No; if(SafeAlloc(out.pData, ui32Size)) memcpy(out.pData, in.pData, ui32Size); } } /*!*************************************************************************** @Function PVRTModelPODCopyNode @Input in @Output out @Input nNumFrames @Description Used to copy a pod node *****************************************************************************/ void PVRTModelPODCopyNode(const SPODNode &in, SPODNode &out, int nNumFrames) { out.nIdx = in.nIdx; out.nIdxMaterial = in.nIdxMaterial; out.nIdxParent = in.nIdxParent; out.nAnimFlags = in.nAnimFlags; out.pUserData = 0; out.nUserDataSize = 0; if(in.pszName && SafeAlloc(out.pszName, strlen(in.pszName) + 1)) memcpy(out.pszName, in.pszName, strlen(in.pszName) + 1); int i32Size; // Position i32Size = in.nAnimFlags & ePODHasPositionAni ? PVRTModelPODGetAnimArraySize(in.pnAnimPositionIdx, nNumFrames, 3) : 3; if(in.pnAnimPositionIdx && SafeAlloc(out.pnAnimPositionIdx, nNumFrames)) memcpy(out.pnAnimPositionIdx, in.pnAnimPositionIdx, sizeof(*out.pnAnimPositionIdx) * nNumFrames); if(in.pfAnimPosition && SafeAlloc(out.pfAnimPosition, i32Size)) memcpy(out.pfAnimPosition, in.pfAnimPosition, sizeof(*out.pfAnimPosition) * i32Size); // Rotation i32Size = in.nAnimFlags & ePODHasRotationAni ? PVRTModelPODGetAnimArraySize(in.pnAnimRotationIdx, nNumFrames, 4) : 4; if(in.pnAnimRotationIdx && SafeAlloc(out.pnAnimRotationIdx, nNumFrames)) memcpy(out.pnAnimRotationIdx, in.pnAnimRotationIdx, sizeof(*out.pnAnimRotationIdx) * nNumFrames); if(in.pfAnimRotation && SafeAlloc(out.pfAnimRotation, i32Size)) memcpy(out.pfAnimRotation, in.pfAnimRotation, sizeof(*out.pfAnimRotation) * i32Size); // Scale i32Size = in.nAnimFlags & ePODHasScaleAni ? PVRTModelPODGetAnimArraySize(in.pnAnimScaleIdx, nNumFrames, 7) : 7; if(in.pnAnimScaleIdx && SafeAlloc(out.pnAnimScaleIdx, nNumFrames)) memcpy(out.pnAnimScaleIdx, in.pnAnimScaleIdx, sizeof(*out.pnAnimScaleIdx) * nNumFrames); if(in.pfAnimScale && SafeAlloc(out.pfAnimScale, i32Size)) memcpy(out.pfAnimScale, in.pfAnimScale, sizeof(*out.pfAnimScale) * i32Size); // Matrix i32Size = in.nAnimFlags & ePODHasMatrixAni ? PVRTModelPODGetAnimArraySize(in.pnAnimMatrixIdx, nNumFrames, 16) : 16; if(in.pnAnimMatrixIdx && SafeAlloc(out.pnAnimMatrixIdx, nNumFrames)) memcpy(out.pnAnimMatrixIdx, in.pnAnimMatrixIdx, sizeof(*out.pnAnimMatrixIdx) * nNumFrames); if(in.pfAnimMatrix && SafeAlloc(out.pfAnimMatrix, i32Size)) memcpy(out.pfAnimMatrix, in.pfAnimMatrix, sizeof(*out.pfAnimMatrix) * i32Size); if(in.pUserData && SafeAlloc(out.pUserData, in.nUserDataSize)) { memcpy(out.pUserData, in.pUserData, in.nUserDataSize); out.nUserDataSize = in.nUserDataSize; } } /*!*************************************************************************** @Function PVRTModelPODCopyMesh @Input in @Output out @Description Used to copy a pod mesh *****************************************************************************/ void PVRTModelPODCopyMesh(const SPODMesh &in, SPODMesh &out) { unsigned int i; bool bInterleaved = in.pInterleaved != 0; out.nNumVertex = in.nNumVertex; out.nNumFaces = in.nNumFaces; // Face data PVRTModelPODCopyCPODData(in.sFaces , out.sFaces , out.nNumFaces * 3, false); // Vertex data PVRTModelPODCopyCPODData(in.sVertex , out.sVertex , out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sNormals , out.sNormals , out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sTangents , out.sTangents , out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sBinormals , out.sBinormals , out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sVtxColours, out.sVtxColours, out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sBoneIdx , out.sBoneIdx , out.nNumVertex, bInterleaved); PVRTModelPODCopyCPODData(in.sBoneWeight, out.sBoneWeight, out.nNumVertex, bInterleaved); if(in.nNumUVW && SafeAlloc(out.psUVW, in.nNumUVW)) { out.nNumUVW = in.nNumUVW; for(i = 0; i < out.nNumUVW; ++i) { PVRTModelPODCopyCPODData(in.psUVW[i], out.psUVW[i], out.nNumVertex, bInterleaved); } } // Allocate and copy interleaved array if(bInterleaved && SafeAlloc(out.pInterleaved, out.nNumVertex * in.sVertex.nStride)) memcpy(out.pInterleaved, in.pInterleaved, out.nNumVertex * in.sVertex.nStride); if(in.pnStripLength && SafeAlloc(out.pnStripLength, out.nNumFaces)) { memcpy(out.pnStripLength, in.pnStripLength, sizeof(*out.pnStripLength) * out.nNumFaces); out.nNumStrips = in.nNumStrips; } if(in.sBoneBatches.nBatchCnt) { out.sBoneBatches.Release(); out.sBoneBatches.nBatchBoneMax = in.sBoneBatches.nBatchBoneMax; out.sBoneBatches.nBatchCnt = in.sBoneBatches.nBatchCnt; if(in.sBoneBatches.pnBatches) { out.sBoneBatches.pnBatches = (int*) malloc(out.sBoneBatches.nBatchCnt * out.sBoneBatches.nBatchBoneMax * sizeof(*out.sBoneBatches.pnBatches)); if(out.sBoneBatches.pnBatches) memcpy(out.sBoneBatches.pnBatches, in.sBoneBatches.pnBatches, out.sBoneBatches.nBatchCnt * out.sBoneBatches.nBatchBoneMax * sizeof(*out.sBoneBatches.pnBatches)); } if(in.sBoneBatches.pnBatchBoneCnt) { out.sBoneBatches.pnBatchBoneCnt = (int*) malloc(out.sBoneBatches.nBatchCnt * sizeof(*out.sBoneBatches.pnBatchBoneCnt)); if(out.sBoneBatches.pnBatchBoneCnt) memcpy(out.sBoneBatches.pnBatchBoneCnt, in.sBoneBatches.pnBatchBoneCnt, out.sBoneBatches.nBatchCnt * sizeof(*out.sBoneBatches.pnBatchBoneCnt)); } if(in.sBoneBatches.pnBatchOffset) { out.sBoneBatches.pnBatchOffset = (int*) malloc(out.sBoneBatches.nBatchCnt * sizeof(out.sBoneBatches.pnBatchOffset)); if(out.sBoneBatches.pnBatchOffset) memcpy(out.sBoneBatches.pnBatchOffset, in.sBoneBatches.pnBatchOffset, out.sBoneBatches.nBatchCnt * sizeof(*out.sBoneBatches.pnBatchOffset)); } } memcpy(out.mUnpackMatrix.f, in.mUnpackMatrix.f, sizeof(in.mUnpackMatrix.f[0]) * 16); out.ePrimitiveType = in.ePrimitiveType; } /*!*************************************************************************** @Function PVRTModelPODCopyTexture @Input in @Output out @Description Used to copy a pod texture *****************************************************************************/ void PVRTModelPODCopyTexture(const SPODTexture &in, SPODTexture &out) { if(in.pszName && SafeAlloc(out.pszName, strlen(in.pszName) + 1)) memcpy(out.pszName, in.pszName, strlen(in.pszName) + 1); } /*!*************************************************************************** @Function PVRTModelPODCopyMaterial @Input in @Output out @Description Used to copy a pod material *****************************************************************************/ void PVRTModelPODCopyMaterial(const SPODMaterial &in, SPODMaterial &out) { memcpy(&out, &in, sizeof(SPODMaterial)); out.pszName = 0; out.pszEffectFile = 0; out.pszEffectName = 0; out.pUserData = 0; out.nUserDataSize = 0; if(in.pszName && SafeAlloc(out.pszName, strlen(in.pszName) + 1)) memcpy(out.pszName, in.pszName, strlen(in.pszName) + 1); if(in.pszEffectFile && SafeAlloc(out.pszEffectFile, strlen(in.pszEffectFile) + 1)) memcpy(out.pszEffectFile, in.pszEffectFile, strlen(in.pszEffectFile) + 1); if(in.pszEffectName && SafeAlloc(out.pszEffectName, strlen(in.pszEffectName) + 1)) memcpy(out.pszEffectName, in.pszEffectName, strlen(in.pszEffectName) + 1); if(in.pUserData && SafeAlloc(out.pUserData, in.nUserDataSize)) { memcpy(out.pUserData, in.pUserData, in.nUserDataSize); out.nUserDataSize = in.nUserDataSize; } } /*!*************************************************************************** @Function PVRTModelPODCopyCamera @Input in @Output out @Input nNumFrames The number of animation frames @Description Used to copy a pod camera *****************************************************************************/ void PVRTModelPODCopyCamera(const SPODCamera &in, SPODCamera &out, int nNumFrames) { memcpy(&out, &in, sizeof(SPODCamera)); out.pfAnimFOV = 0; if(in.pfAnimFOV && SafeAlloc(out.pfAnimFOV, nNumFrames)) memcpy(out.pfAnimFOV, in.pfAnimFOV, sizeof(*out.pfAnimFOV) * nNumFrames); } /*!*************************************************************************** @Function PVRTModelPODCopyLight @Input in @Output out @Description Used to copy a pod light *****************************************************************************/ void PVRTModelPODCopyLight(const SPODLight &in, SPODLight &out) { memcpy(&out, &in, sizeof(SPODLight)); } /*!*************************************************************************** @Function TransformCPODData @Input in @Output out @Input idx Value to transform @Input pPalette Palette of matrices to transform with @Input pBoneIdx Array of indices into pPalette @Input pBoneWeight Array of weights to weight the influence of the matrices of pPalette with @Input i32BoneCnt Size of pBoneIdx and pBoneWeight @Description Used to transform a particular value in a CPODData *****************************************************************************/ inline void TransformCPODData(CPODData &in, CPODData &out, int idx, PVRTMATRIX *pPalette, float *pBoneIdx, float *pBoneW, int i32BoneCnt, bool bNormalise) { PVRTVECTOR4f fResult, fOrig, fTmp; if(in.n) { PVRTVertexRead(&fOrig, in.pData + (idx * in.nStride), in.eType, in.n); memset(&fResult.x, 0, sizeof(fResult)); if(i32BoneCnt) { for(int i = 0; i < i32BoneCnt; ++i) { int i32BoneIdx = (int) pBoneIdx[i]; fTmp.x = vt2f(pPalette[i32BoneIdx].f[0]) * fOrig.x + vt2f(pPalette[i32BoneIdx].f[4]) * fOrig.y + vt2f(pPalette[i32BoneIdx].f[8]) * fOrig.z + vt2f(pPalette[i32BoneIdx].f[12]) * fOrig.w; fTmp.y = vt2f(pPalette[i32BoneIdx].f[1]) * fOrig.x + vt2f(pPalette[i32BoneIdx].f[5]) * fOrig.y + vt2f(pPalette[i32BoneIdx].f[9]) * fOrig.z + vt2f(pPalette[i32BoneIdx].f[13]) * fOrig.w; fTmp.z = vt2f(pPalette[i32BoneIdx].f[2]) * fOrig.x + vt2f(pPalette[i32BoneIdx].f[6]) * fOrig.y + vt2f(pPalette[i32BoneIdx].f[10])* fOrig.z + vt2f(pPalette[i32BoneIdx].f[14]) * fOrig.w; fTmp.w = vt2f(pPalette[i32BoneIdx].f[3]) * fOrig.x + vt2f(pPalette[i32BoneIdx].f[7]) * fOrig.y + vt2f(pPalette[i32BoneIdx].f[11])* fOrig.z + vt2f(pPalette[i32BoneIdx].f[15]) * fOrig.w; fResult.x += fTmp.x * pBoneW[i]; fResult.y += fTmp.y * pBoneW[i]; fResult.z += fTmp.z * pBoneW[i]; fResult.w += fTmp.w * pBoneW[i]; } } else { fResult.x = vt2f(pPalette[0].f[0]) * fOrig.x + vt2f(pPalette[0].f[4]) * fOrig.y + vt2f(pPalette[0].f[8]) * fOrig.z + vt2f(pPalette[0].f[12]) * fOrig.w; fResult.y = vt2f(pPalette[0].f[1]) * fOrig.x + vt2f(pPalette[0].f[5]) * fOrig.y + vt2f(pPalette[0].f[9]) * fOrig.z + vt2f(pPalette[0].f[13]) * fOrig.w; fResult.z = vt2f(pPalette[0].f[2]) * fOrig.x + vt2f(pPalette[0].f[6]) * fOrig.y + vt2f(pPalette[0].f[10])* fOrig.z + vt2f(pPalette[0].f[14]) * fOrig.w; fResult.w = vt2f(pPalette[0].f[3]) * fOrig.x + vt2f(pPalette[0].f[7]) * fOrig.y + vt2f(pPalette[0].f[11])* fOrig.z + vt2f(pPalette[0].f[15]) * fOrig.w; } if(bNormalise) { double temp = (double)(fResult.x * fResult.x + fResult.y * fResult.y + fResult.z * fResult.z); temp = 1.0 / sqrt(temp); float f = (float)temp; fResult.x = fResult.x * f; fResult.y = fResult.y * f; fResult.z = fResult.z * f; } PVRTVertexWrite(out.pData + (idx * out.nStride), out.eType, in.n, &fResult); } } /*!*************************************************************************** @Function PVRTModelPODFlattenToWorldSpace @Input in - Source scene. All meshes must not be interleaved. @Output out @Description Used to flatten a pod scene to world space. All animation and skinning information will be removed. The returned position, normal, binormals and tangent data if present will be returned as floats regardless of the input data type. *****************************************************************************/ EPVRTError PVRTModelPODFlattenToWorldSpace(CPVRTModelPOD &in, CPVRTModelPOD &out) { unsigned int i, j, k, l; PVRTMATRIX mWorld; // Destroy the out pod scene to make sure it is clean out.Destroy(); // Init mesh and node arrays SafeAlloc(out.pNode, in.nNumNode); SafeAlloc(out.pMesh, in.nNumMeshNode); out.nNumNode = in.nNumNode; out.nNumMesh = out.nNumMeshNode = in.nNumMeshNode; // Init scene values out.nNumFrame = 0; out.nFlags = in.nFlags; for(i = 0; i < 3; ++i) { out.pfColourBackground[i] = in.pfColourBackground[i]; out.pfColourAmbient[i] = in.pfColourAmbient[i]; } // flatten meshes to world space for(i = 0; i < in.nNumMeshNode; ++i) { SPODNode& inNode = in.pNode[i]; SPODNode& outNode = out.pNode[i]; // Get the meshes SPODMesh& inMesh = in.pMesh[inNode.nIdx]; SPODMesh& outMesh = out.pMesh[i]; if(inMesh.pInterleaved != 0) // This function requires all the meshes to be de-interleaved { _ASSERT(inMesh.pInterleaved == 0); out.Destroy(); // Destroy the out pod scene return PVR_FAIL; } // Copy the node PVRTModelPODCopyNode(inNode, outNode, in.nNumFrame); // Strip out animation and parenting outNode.nIdxParent = -1; outNode.nAnimFlags = 0; FREE(outNode.pfAnimMatrix); FREE(outNode.pfAnimPosition); FREE(outNode.pfAnimRotation); FREE(outNode.pfAnimScale); // Update the mesh ID. The rest of the IDs should remain correct outNode.nIdx = i; // Copy the mesh PVRTModelPODCopyMesh(inMesh, outMesh); // Strip out skinning information as that is no longer needed outMesh.sBoneBatches.Release(); outMesh.sBoneIdx.Reset(); outMesh.sBoneWeight.Reset(); // Set the data type to float and resize the arrays as this function outputs transformed data as float only if(inMesh.sVertex.n) { outMesh.sVertex.eType = EPODDataFloat; outMesh.sVertex.pData = (unsigned char*) realloc(outMesh.sVertex.pData, PVRTModelPODDataStride(outMesh.sVertex) * inMesh.nNumVertex); } if(inMesh.sNormals.n) { outMesh.sNormals.eType = EPODDataFloat; outMesh.sNormals.pData = (unsigned char*) realloc(outMesh.sNormals.pData, PVRTModelPODDataStride(outMesh.sNormals) * inMesh.nNumVertex); } if(inMesh.sTangents.n) { outMesh.sTangents.eType = EPODDataFloat; outMesh.sTangents.pData = (unsigned char*) realloc(outMesh.sTangents.pData, PVRTModelPODDataStride(outMesh.sTangents) * inMesh.nNumVertex); } if(inMesh.sBinormals.n) { outMesh.sBinormals.eType = EPODDataFloat; outMesh.sBinormals.pData = (unsigned char*) realloc(outMesh.sBinormals.pData, PVRTModelPODDataStride(outMesh.sBinormals) * inMesh.nNumVertex); } if(inMesh.sBoneBatches.nBatchCnt) { unsigned int ui32BatchPaletteSize = 0; PVRTMATRIX *pPalette = 0; PVRTMATRIX *pPaletteInvTrans = 0; unsigned int ui32Offset = 0, ui32Strip = 0; bool *pbTransformed = 0; SafeAlloc(pPalette, inMesh.sBoneBatches.nBatchBoneMax); SafeAlloc(pPaletteInvTrans, inMesh.sBoneBatches.nBatchBoneMax); SafeAlloc(pbTransformed, inMesh.nNumVertex); for(j = 0; j < (unsigned int) inMesh.sBoneBatches.nBatchCnt; ++j) { ui32BatchPaletteSize = (unsigned int) inMesh.sBoneBatches.pnBatchBoneCnt[j]; for(k = 0; k < ui32BatchPaletteSize; ++k) { // Get the Node of the bone int i32NodeID = inMesh.sBoneBatches.pnBatches[j * inMesh.sBoneBatches.nBatchBoneMax + k]; // Get the World transformation matrix for this bone in.GetBoneWorldMatrix(pPalette[k], inNode, in.pNode[i32NodeID]); // Get the inverse transpose of the 3x3 if(inMesh.sNormals.n || inMesh.sTangents.n || inMesh.sBinormals.n) { pPaletteInvTrans[k] = pPalette[k]; pPaletteInvTrans[k].f[3] = pPaletteInvTrans[k].f[7] = pPaletteInvTrans[k].f[11] = 0; pPaletteInvTrans[k].f[12] = pPaletteInvTrans[k].f[13] = pPaletteInvTrans[k].f[14] = 0; PVRTMatrixInverse(pPaletteInvTrans[k], pPaletteInvTrans[k]); PVRTMatrixTranspose(pPaletteInvTrans[k], pPaletteInvTrans[k]); } } // Calculate the number of triangles in the current batch unsigned int ui32Tris; if(j + 1 < (unsigned int) inMesh.sBoneBatches.nBatchCnt) ui32Tris = inMesh.sBoneBatches.pnBatchOffset[j + 1] - inMesh.sBoneBatches.pnBatchOffset[j]; else ui32Tris = inMesh.nNumFaces - inMesh.sBoneBatches.pnBatchOffset[j]; unsigned int idx; float fBoneIdx[4], fBoneWeights[4]; if(inMesh.nNumStrips == 0) { ui32Offset = 3 * inMesh.sBoneBatches.pnBatchOffset[j]; for(l = ui32Offset; l < ui32Offset + (ui32Tris * 3); ++l) { if(inMesh.sFaces.pData) // Indexed Triangle Lists PVRTVertexRead(&idx, inMesh.sFaces.pData + (l * inMesh.sFaces.nStride), inMesh.sFaces.eType); else // Indexed Triangle Lists idx = l; if(!pbTransformed[idx]) { PVRTVertexRead((PVRTVECTOR4f*) &fBoneIdx[0], inMesh.sBoneIdx.pData + (idx * inMesh.sBoneIdx.nStride), inMesh.sBoneIdx.eType, inMesh.sBoneIdx.n); PVRTVertexRead((PVRTVECTOR4f*) &fBoneWeights[0], inMesh.sBoneWeight.pData + (idx * inMesh.sBoneWeight.nStride), inMesh.sBoneWeight.eType, inMesh.sBoneWeight.n); TransformCPODData(inMesh.sVertex, outMesh.sVertex, idx, pPalette, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, false); TransformCPODData(inMesh.sNormals, outMesh.sNormals, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); TransformCPODData(inMesh.sTangents, outMesh.sTangents, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); TransformCPODData(inMesh.sBinormals, outMesh.sBinormals, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); pbTransformed[idx] = true; } } } else { unsigned int ui32TrisDrawn = 0; while(ui32TrisDrawn < ui32Tris) { for(l = ui32Offset; l < ui32Offset + (inMesh.pnStripLength[ui32Strip]+2); ++l) { if(inMesh.sFaces.pData) // Indexed Triangle Strips PVRTVertexRead(&idx, inMesh.sFaces.pData + (l * inMesh.sFaces.nStride), inMesh.sFaces.eType); else // Triangle Strips idx = l; if(!pbTransformed[idx]) { PVRTVertexRead((PVRTVECTOR4f*) &fBoneIdx[0], inMesh.sBoneIdx.pData + (idx * inMesh.sBoneIdx.nStride), inMesh.sBoneIdx.eType, inMesh.sBoneIdx.n); PVRTVertexRead((PVRTVECTOR4f*) &fBoneWeights[0], inMesh.sBoneWeight.pData + (idx * inMesh.sBoneWeight.nStride), inMesh.sBoneWeight.eType, inMesh.sBoneWeight.n); TransformCPODData(inMesh.sVertex, outMesh.sVertex, idx, pPalette, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, false); TransformCPODData(inMesh.sNormals, outMesh.sNormals, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); TransformCPODData(inMesh.sTangents, outMesh.sTangents, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); TransformCPODData(inMesh.sBinormals, outMesh.sBinormals, idx, pPaletteInvTrans, &fBoneIdx[0], &fBoneWeights[0], inMesh.sBoneIdx.n, true); pbTransformed[idx] = true; } } ui32Offset += inMesh.pnStripLength[ui32Strip] + 2; ui32TrisDrawn += inMesh.pnStripLength[ui32Strip]; ++ui32Strip; } } } FREE(pPalette); FREE(pPaletteInvTrans); FREE(pbTransformed); } else { // Get transformation matrix in.GetWorldMatrix(mWorld, inNode); PVRTMATRIX mWorldInvTrans; // Get the inverse transpose of the 3x3 if(inMesh.sNormals.n || inMesh.sTangents.n || inMesh.sBinormals.n) { mWorldInvTrans = mWorld; mWorldInvTrans.f[3] = mWorldInvTrans.f[7] = mWorldInvTrans.f[11] = 0; mWorldInvTrans.f[12] = mWorldInvTrans.f[13] = mWorldInvTrans.f[14] = 0; PVRTMatrixInverse(mWorldInvTrans, mWorldInvTrans); PVRTMatrixTranspose(mWorldInvTrans, mWorldInvTrans); } // Transform the vertices for(j = 0; j < inMesh.nNumVertex; ++j) { TransformCPODData(inMesh.sVertex, outMesh.sVertex, j, &mWorld, 0, 0, 0, false); TransformCPODData(inMesh.sNormals, outMesh.sNormals, j, &mWorldInvTrans, 0, 0, 0, true); TransformCPODData(inMesh.sTangents, outMesh.sTangents, j, &mWorldInvTrans, 0, 0, 0, true); TransformCPODData(inMesh.sBinormals, outMesh.sBinormals, j, &mWorldInvTrans, 0, 0, 0, true); } } } // Copy the rest of the nodes for(i = in.nNumMeshNode; i < in.nNumNode; ++i) { PVRTModelPODCopyNode(in.pNode[i], out.pNode[i], in.nNumFrame); // Strip out animation and parenting out.pNode[i].nIdxParent = -1; out.pNode[i].nAnimFlags = 0; FREE(out.pNode[i].pfAnimMatrix); FREE(out.pNode[i].pnAnimMatrixIdx); FREE(out.pNode[i].pfAnimPosition); FREE(out.pNode[i].pnAnimPositionIdx); FREE(out.pNode[i].pfAnimRotation); FREE(out.pNode[i].pnAnimRotationIdx); FREE(out.pNode[i].pfAnimScale); FREE(out.pNode[i].pnAnimScaleIdx); // Get world transformation matrix.... in.GetWorldMatrix(mWorld, in.pNode[i]); // ...set the out node transformation matrix if(SafeAlloc(out.pNode[i].pfAnimMatrix, 16)) memcpy(out.pNode[i].pfAnimMatrix, mWorld.f, sizeof(PVRTMATRIX)); } // Copy camera, lights if(in.nNumCamera && SafeAlloc(out.pCamera, in.nNumCamera)) { out.nNumCamera = in.nNumCamera; for(i = 0; i < in.nNumCamera; ++i) PVRTModelPODCopyCamera(in.pCamera[i], out.pCamera[i], in.nNumFrame); } if(in.nNumLight && SafeAlloc(out.pLight, in.nNumLight)) { out.nNumLight = in.nNumLight; for(i = 0; i < out.nNumLight; ++i) PVRTModelPODCopyLight(in.pLight[i], out.pLight[i]); } // Copy textures if(in.nNumTexture && SafeAlloc(out.pTexture, in.nNumTexture)) { out.nNumTexture = in.nNumTexture; for(i = 0; i < out.nNumTexture; ++i) PVRTModelPODCopyTexture(in.pTexture[i], out.pTexture[i]); } // Copy materials if(in.nNumMaterial && SafeAlloc(out.pMaterial, in.nNumMaterial)) { out.nNumMaterial = in.nNumMaterial; for(i = 0; i < in.nNumMaterial; ++i) PVRTModelPODCopyMaterial(in.pMaterial[i], out.pMaterial[i]); } out.InitImpl(); return PVR_SUCCESS; } static bool MergeTexture(const CPVRTModelPOD &src, CPVRTModelPOD &dst, const int &srcTexID, int &dstTexID) { if(srcTexID != -1 && srcTexID < (int) src.nNumTexture) { if(dstTexID == -1) { // Resize our texture array to add our texture dst.pTexture = (SPODTexture*) realloc(dst.pTexture, (dst.nNumTexture + 1) * sizeof(SPODTexture)); if(!dst.pTexture) return false; dstTexID = dst.nNumTexture; ++dst.nNumTexture; dst.pTexture[dstTexID].pszName = (char*) malloc(strlen(src.pTexture[srcTexID].pszName) + 1); strcpy(dst.pTexture[dstTexID].pszName, src.pTexture[srcTexID].pszName); return true; } // See if our texture names match if(strcmp(src.pTexture[srcTexID].pszName, dst.pTexture[dstTexID].pszName) == 0) return true; // Nothing to do // See if our texture filenames match char * srcName = src.pTexture[srcTexID].pszName; char * dstName = dst.pTexture[dstTexID].pszName; bool bFoundPossibleEndOfFilename = false; bool bStrMatch = true, bFilenameMatch = true; while(*srcName != '\0' && *dstName != '\0') { if(*srcName != *dstName) { if(!bFoundPossibleEndOfFilename) return true; // They don't match bStrMatch = false; } if(*srcName == '.') { if(!bStrMatch) return true; // They don't match bFoundPossibleEndOfFilename = true; bFilenameMatch = bStrMatch; } ++srcName; ++dstName; } if(bFilenameMatch) { // Our filenames match but our extensions don't so merge our textures FREE(dst.pTexture[dstTexID].pszName); dst.pTexture[dstTexID].pszName = (char*) malloc(strlen(src.pTexture[srcTexID].pszName) + 1); strcpy(dst.pTexture[dstTexID].pszName, src.pTexture[srcTexID].pszName); return true; } // Our texture names aren't the same so don't try and merge } return true; } /*!*************************************************************************** @Function PVRTModelPODMergeMaterials @Input src - Source scene @Output dst - Destination scene @Description This function takes two scenes and merges the textures, PFX effects and blending parameters from the src materials into the dst materials if they have the same material name. *****************************************************************************/ EPVRTError PVRTModelPODMergeMaterials(const CPVRTModelPOD &src, CPVRTModelPOD &dst) { if(!src.nNumMaterial || !dst.nNumMaterial) return PVR_SUCCESS; bool *bMatched = (bool*) calloc(dst.nNumMaterial, sizeof(bool)); if(!bMatched) return PVR_FAIL; for(unsigned int i = 0; i < src.nNumMaterial; ++i) { const SPODMaterial &srcMaterial = src.pMaterial[i]; // Match our current material with one in the dst for(unsigned int j = 0; j < dst.nNumMaterial; ++j) { if(bMatched[j]) continue; // We have already matched this material with another SPODMaterial &dstMaterial = dst.pMaterial[j]; // We've found a material with the same name if(strcmp(srcMaterial.pszName, dstMaterial.pszName) == 0) { bMatched[j] = true; // Merge the textures if(!MergeTexture(src, dst, srcMaterial.nIdxTexDiffuse, dstMaterial.nIdxTexDiffuse)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexAmbient, dstMaterial.nIdxTexAmbient)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexSpecularColour, dstMaterial.nIdxTexSpecularColour)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexSpecularLevel, dstMaterial.nIdxTexSpecularLevel)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexBump, dstMaterial.nIdxTexBump)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexEmissive, dstMaterial.nIdxTexEmissive)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexGlossiness, dstMaterial.nIdxTexGlossiness)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexOpacity, dstMaterial.nIdxTexOpacity)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexReflection, dstMaterial.nIdxTexReflection)) { FREE(bMatched); return PVR_FAIL; } if(!MergeTexture(src, dst, srcMaterial.nIdxTexRefraction, dstMaterial.nIdxTexRefraction)) { FREE(bMatched); return PVR_FAIL; } dstMaterial.eBlendSrcRGB = srcMaterial.eBlendSrcRGB; dstMaterial.eBlendSrcA = srcMaterial.eBlendSrcA; dstMaterial.eBlendDstRGB = srcMaterial.eBlendDstRGB; dstMaterial.eBlendDstA = srcMaterial.eBlendDstA; dstMaterial.eBlendOpRGB = srcMaterial.eBlendOpRGB; dstMaterial.eBlendOpA = srcMaterial.eBlendOpA; memcpy(dstMaterial.pfBlendColour, srcMaterial.pfBlendColour, 4 * sizeof(VERTTYPE)); memcpy(dstMaterial.pfBlendFactor, srcMaterial.pfBlendFactor, 4 * sizeof(VERTTYPE)); dstMaterial.nFlags = srcMaterial.nFlags; // Merge effect names if(srcMaterial.pszEffectFile) { FREE(dstMaterial.pszEffectFile); dstMaterial.pszEffectFile = (char*) malloc(strlen(srcMaterial.pszEffectFile) + 1); strcpy(dstMaterial.pszEffectFile, srcMaterial.pszEffectFile); } if(srcMaterial.pszEffectName) { FREE(dstMaterial.pszEffectName); dstMaterial.pszEffectName = (char*) malloc(strlen(srcMaterial.pszEffectName) + 1); strcpy(dstMaterial.pszEffectName, srcMaterial.pszEffectName); } break; } } } FREE(bMatched); return PVR_SUCCESS; } /***************************************************************************** End of file (PVRTModelPOD.cpp) *****************************************************************************/
// Copyright (c) YugaByte, Inc. // Portions Copyright (c) 2021 Futurewei Cloud // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "entities/entity_ids.h" #include <boost/uuid/nil_generator.hpp> #include <fmt/format.h> namespace k2pg { namespace sql { using boost::uuids::uuid; using k2pg::Status; static constexpr int kUuidVersion = 3; // Repurpose old name-based UUID v3 to embed Postgres oids. const uint32_t kTemplate1Oid = 1; // Hardcoded for template1. (in initdb.c) const uint32_t kPgProcTableOid = 1255; // Hardcoded for pg_proc. (in pg_proc.h) // Static initialization is OK because this won't be used in another static initialization. const TableId kPgProcTableId = PgObjectId::GetTableUuid(kTemplate1Oid, kPgProcTableOid); //------------------------------------------------------------------------------------------------- namespace { // TODO: get rid of the 16 byid UUID, and use PG dboid and tabld oid directly. // Layout of Postgres database and table 4-byte oids in a the 16-byte table UUID: // // +-----------------------------------------------------------------------------------------------+ // | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | // +-----------------------------------------------------------------------------------------------+ // | database | | vsn | | var | | | table | // | oid | | | | | | | oid | // +-----------------------------------------------------------------------------------------------+ static char hex_chars[] = "0123456789abcdef"; void UuidSetDatabaseId(const uint32_t database_oid, uuid* id) { id->data[0] = database_oid >> 24 & 0xFF; id->data[1] = database_oid >> 16 & 0xFF; id->data[2] = database_oid >> 8 & 0xFF; id->data[3] = database_oid & 0xFF; } void UuidSetTableIds(const uint32_t table_oid, uuid* id) { id->data[12] = table_oid >> 24 & 0xFF; id->data[13] = table_oid >> 16 & 0xFF; id->data[14] = table_oid >> 8 & 0xFF; id->data[15] = table_oid & 0xFF; } std::string b2a_hex(const char* input, int len) { std::string result; result.resize(len << 1); const unsigned char* b = reinterpret_cast<const unsigned char*>(input); for (int i = 0; i < len; i++) { result[i * 2 + 0] = hex_chars[b[i] >> 4]; result[i * 2 + 1] = hex_chars[b[i] & 0xf]; } return result; } std::string UuidToString(uuid* id) { // Set variant that is stored in octet 7, which is index 8, since indexes count backwards. // Variant must be 0b10xxxxxx for RFC 4122 UUID variant 1. id->data[8] &= 0xBF; id->data[8] |= 0x80; // Set version that is stored in octet 9 which is index 6, since indexes count backwards. id->data[6] &= 0x0F; id->data[6] |= (kUuidVersion << 4); return b2a_hex(reinterpret_cast<const char *>(id->data), sizeof(id->data)); } } // namespace std::string ObjectIdGenerator::Next(const bool binary_id) { boost::uuids::uuid oid = oid_generator_(); return binary_id ? std::string(reinterpret_cast<const char *>(oid.data), sizeof(oid.data)) : b2a_hex(reinterpret_cast<const char *>(oid.data), sizeof(oid.data)); } std::string PgObjectId::ToString() const { return fmt::format("({}, {})", database_oid_, object_oid_); } std::string PgObjectId::GetDatabaseUuid() const { return GetDatabaseUuid(database_oid_); } std::string PgObjectId::GetDatabaseUuid(const PgOid& database_oid) { uuid id = boost::uuids::nil_uuid(); UuidSetDatabaseId(database_oid, &id); return UuidToString(&id); } std::string PgObjectId::GetTableUuid(const PgOid& database_oid, const PgOid& table_oid) { uuid id = boost::uuids::nil_uuid(); UuidSetDatabaseId(database_oid, &id); UuidSetTableIds(table_oid, &id); return UuidToString(&id); } std::string PgObjectId::GetTableUuid() const { return GetTableUuid(database_oid_, object_oid_); } std::string PgObjectId::GetTableId() const { return GetTableId(object_oid_); } std::string PgObjectId::GetTableId(const PgOid& table_oid) { // table id is a uuid without database oid information return GetTableUuid(kPgInvalidOid, table_oid); } bool PgObjectId::IsPgsqlId(const std::string& uuid) { if (uuid.size() != 32) return false; // Ignore non-UUID string like "sys.catalog.uuid" try { size_t pos = 0; #ifndef NDEBUG const int variant = std::stoi(uuid.substr(8 * 2, 2), &pos, 16); DCHECK((pos == 2) && (variant & 0xC0) == 0x80) << "Invalid Postgres uuid " << uuid; #endif const int version = std::stoi(uuid.substr(6 * 2, 2), &pos, 16); if ((pos == 2) && (version & 0xF0) >> 4 == kUuidVersion) return true; } catch(const std::invalid_argument&) { } catch(const std::out_of_range&) { // TODO: log the actual exceptions } return false; } Result<uint32_t> PgObjectId::GetDatabaseOidByUuid(const std::string& database_uuid) { DCHECK(IsPgsqlId(database_uuid)); try { size_t pos = 0; const uint32_t oid = stoul(database_uuid.substr(0, sizeof(uint32_t) * 2), &pos, 16); if (pos == sizeof(uint32_t) * 2) { return oid; } } catch(const std::invalid_argument&) { } catch(const std::out_of_range&) { // TODO: log the actual exceptions } return kPgInvalidOid; return STATUS(InvalidArgument, "Invalid PostgreSQL database uuid", database_uuid); } uint32_t PgObjectId::GetTableOidByTableUuid(const std::string& table_uuid) { DCHECK(IsPgsqlId(table_uuid)); try { size_t pos = 0; const uint32_t oid = stoul(table_uuid.substr(12 * 2, sizeof(uint32_t) * 2), &pos, 16); if (pos == sizeof(uint32_t) * 2) { return oid; } } catch(const std::invalid_argument&) { } catch(const std::out_of_range&) { // TODO: log the actual exceptions } return kPgInvalidOid; } Result<uint32_t> PgObjectId::GetDatabaseOidByTableUuid(const std::string& table_uuid) { DCHECK(IsPgsqlId(table_uuid)); try { size_t pos = 0; const uint32_t oid = stoul(table_uuid.substr(0, sizeof(uint32_t) * 2), &pos, 16); if (pos == sizeof(uint32_t) * 2) { return oid; } } catch(const std::invalid_argument&) { } catch(const std::out_of_range&) { // TODO: log the actual exceptions } return STATUS(InvalidArgument, "Invalid PostgreSQL table uuid", table_uuid); } bool IsValidRowMarkType(RowMarkType row_mark_type) { switch (row_mark_type) { case RowMarkType::ROW_MARK_EXCLUSIVE: [[fallthrough]]; case RowMarkType::ROW_MARK_NOKEYEXCLUSIVE: [[fallthrough]]; case RowMarkType::ROW_MARK_SHARE: [[fallthrough]]; case RowMarkType::ROW_MARK_KEYSHARE: return true; break; default: return false; break; } } bool RowMarkNeedsPessimisticLock(RowMarkType row_mark_type) { /* * Currently, using pessimistic locking for all supported row marks except the key share lock. * This is because key share locks are used for foreign keys and we don't want pessimistic * locking there. */ return IsValidRowMarkType(row_mark_type) && row_mark_type != RowMarkType::ROW_MARK_KEYSHARE; } } // namespace sql } // namespace k2pg
// RUN: clang-cc -emit-llvm -o - %s extern "C" int printf(...); struct F { F() : iF(1), fF(2.0) {} int iF; float fF; }; struct V { double d; int iV; }; struct B : virtual V{ double d; int iB; }; struct B1 : virtual V{ double d; int iB1; }; class A : public B, public B1 { public: A() : f(1.0), d(2.0), Ai(3) {} float f; double d; int Ai; F Af; }; template <typename T> struct TT { int T::t::*pti; }; struct I { typedef I t; int x; }; void pr(const F& b) { printf(" %d %f\n", b.iF, b.fF); } void test_aggr_pdata(A& a1) { F A::* af = &A::Af; pr(a1.*af); (a1.*af).iF = 100; (a1.*af).fF = 200.00; printf(" %d %f\n", (a1.*af).iF, (a1.*af).fF); pr(a1.*af); (a1.*af).iF++; (a1.*af).fF--; --(a1.*af).fF; pr(a1.*af); } void test_aggr_pdata_1(A* pa) { F A::* af = &A::Af; pr(pa->*af); (pa->*af).iF = 100; (pa->*af).fF = 200.00; printf(" %d %f\n", (pa->*af).iF, (pa->*af).fF); pr(pa->*af); (pa->*af).iF++; (pa->*af).fF--; --(pa->*af).fF; pr(pa->*af); } int main() { A a1; TT<I> tt; I i; int A::* pa = &A::Ai; float A::* pf = &A::f; double A::* pd = &A::d; tt.pti = &I::x; printf("%d %d %d\n", &A::Ai, &A::f, &A::d); printf("%d\n", &A::B::iB); printf("%d\n", &A::B1::iB1); printf("%d\n", &A::f); printf("%d\n", &A::B::iV); printf("%d\n", &A::B1::iV); printf("%d\n", &A::B::V::iV); printf("%d\n", &A::B1::V::iV); printf("%d, %f, %f \n", a1.*pa, a1.*pf, a1.*pd); printf("%d\n", i.*tt.pti); test_aggr_pdata(a1); test_aggr_pdata_1(&a1); }
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR THE BIFROST* ENGINE - RELEASE 1.2/L ; ; See "bifrost_l.h" for further details ; ---------------------------------------------------------------- ; void BIFROSTL_setTile(unsigned int px, unsigned int py, unsigned int tile) ; callee SECTION code_clib SECTION code_bifrost_l PUBLIC BIFROSTL_setTile_callee BIFROSTL_setTile_callee: pop hl ; RET address pop de ; E=tile pop bc ; C=py ex (sp),hl ; L=px INCLUDE "arch/zx/bifrost_l/z80/asm_BIFROSTL_setTile.asm"
// --------------------------------------------------------------------------- // // @file TwMgr.cpp // @author Philippe Decaudin // @license This file is part of the AntTweakBar library. // For conditions of distribution and use, see License.txt // // --------------------------------------------------------------------------- #include "TwPrecomp.h" #include <AntTweakBar.h> #include "TwMgr.h" #include "TwBar.h" #include "TwFonts.h" #include "TwOpenGL.h" #include "TwOpenGLCore.h" #ifdef ANT_WINDOWS #ifndef TW_NO_DIRECT3D # include "TwDirect3D9.h" # include "TwDirect3D10.h" # include "TwDirect3D11.h" #endif # include "resource.h" # ifdef _DEBUG # include <crtdbg.h> # endif // _DEBUG #endif // ANT_WINDOWS #if !defined(ANT_WINDOWS) # define _snprintf snprintf #endif // defined(ANT_WINDOWS) using namespace std; CTwMgr *g_TwMgr = NULL; // current TwMgr bool g_BreakOnError = false; TwErrorHandler g_ErrorHandler = NULL; int g_TabLength = 4; CTwBar * const TW_GLOBAL_BAR = (CTwBar *)(-1); int g_InitWndWidth = -1; int g_InitWndHeight = -1; TwCopyCDStringToClient g_InitCopyCDStringToClient = NULL; TwCopyStdStringToClient g_InitCopyStdStringToClient = NULL; float g_FontScaling = 1.0f; // multi-windows const int TW_MASTER_WINDOW_ID = 0; typedef map<int, CTwMgr *> CTwWndMap; CTwWndMap g_Wnds; CTwMgr *g_TwMasterMgr = NULL; // error messages extern const char *g_ErrUnknownAttrib; extern const char *g_ErrNoValue; extern const char *g_ErrBadValue; const char *g_ErrInit = "Already initialized"; const char *g_ErrShut = "Already shutdown"; const char *g_ErrNotInit = "Not initialized"; const char *g_ErrUnknownAPI = "Unsupported graph API"; const char *g_ErrBadDevice = "Invalid graph device"; const char *g_ErrBadParam = "Invalid parameter"; const char *g_ErrExist = "Exists already"; const char *g_ErrNotFound = "Not found"; const char *g_ErrNthToDo = "Nothing to do"; const char *g_ErrBadSize = "Bad size"; const char *g_ErrIsDrawing = "Asynchronous drawing detected"; const char *g_ErrIsProcessing="Asynchronous processing detected"; const char *g_ErrOffset = "Offset larger than StructSize"; const char *g_ErrDelStruct = "Cannot delete a struct member"; const char *g_ErrNoBackQuote= "Name cannot include back-quote"; const char *g_ErrStdString = "Debug/Release std::string mismatch"; const char *g_ErrCStrParam = "Value count for TW_PARAM_CSTRING must be 1"; const char *g_ErrOutOfRange = "Index out of range"; const char *g_ErrHasNoValue = "Has no value"; const char *g_ErrBadType = "Incompatible type"; const char *g_ErrDelHelp = "Cannot delete help bar"; char g_ErrParse[512]; void ANT_CALL TwGlobalError(const char *_ErrorMessage); #if defined(ANT_UNIX) || defined(ANT_OSX) #define _stricmp strcasecmp #define _strdup strdup #endif #ifdef ANT_WINDOWS bool g_UseCurRsc = true; // use dll resources for rotoslider cursors #endif // --------------------------------------------------------------------------- const float FLOAT_EPS = 1.0e-7f; const float FLOAT_EPS_SQ = 1.0e-14f; const float FLOAT_PI = 3.14159265358979323846f; const double DOUBLE_EPS = 1.0e-14; const double DOUBLE_EPS_SQ = 1.0e-28; const double DOUBLE_PI = 3.14159265358979323846; inline double DegToRad(double degree) { return degree * (DOUBLE_PI/180.0); } inline double RadToDeg(double radian) { return radian * (180.0/DOUBLE_PI); } // --------------------------------------------------------------------------- // a static global object to verify that Tweakbar module has been properly terminated (in debug mode only) #ifdef _DEBUG static struct CTwVerif { ~CTwVerif() { if( g_TwMgr!=NULL ) g_TwMgr->SetLastError("Tweak bar module has not been terminated properly: call TwTerminate()\n"); } } s_Verif; #endif // _DEBUG // --------------------------------------------------------------------------- // Color ext type // --------------------------------------------------------------------------- void CColorExt::RGB2HLS() { float fH = 0, fL = 0, fS = 0; ColorRGBToHLSf((float)R/255.0f, (float)G/255.0f, (float)B/255.0f, &fH, &fL, &fS); H = (int)fH; if( H>=360 ) H -= 360; else if( H<0 ) H += 360; L = (int)(255.0f*fL + 0.5f); if( L<0 ) L = 0; else if( L>255 ) L = 255; S = (int)(255.0f*fS + 0.5f); if( S<0 ) S = 0; else if( S>255 ) S = 255; } void CColorExt::HLS2RGB() { float fR = 0, fG = 0, fB = 0; ColorHLSToRGBf((float)H, (float)L/255.0f, (float)S/255.0f, &fR, &fG, &fB); R = (int)(255.0f*fR + 0.5f); if( R<0 ) R = 0; else if( R>255 ) R = 255; G = (int)(255.0f*fG + 0.5f); if( G<0 ) G = 0; else if( G>255 ) G = 255; B = (int)(255.0f*fB + 0.5f); if( B<0 ) B = 0; else if( B>255 ) B = 255; } void ANT_CALL CColorExt::InitColor32CB(void *_ExtValue, void *_ClientData) { CColorExt *ext = static_cast<CColorExt *>(_ExtValue); if( ext ) { ext->m_IsColorF = false; ext->R = 0; ext->G = 0; ext->B = 0; ext->H = 0; ext->L = 0; ext->S = 0; ext->A = 255; ext->m_HLS = false; ext->m_HasAlpha = false; ext->m_CanHaveAlpha = true; if( g_TwMgr && g_TwMgr->m_GraphAPI==TW_DIRECT3D9 ) // D3D10 now use OGL rgba order! ext->m_OGL = false; else ext->m_OGL = true; ext->m_PrevConvertedColor = Color32FromARGBi(ext->A, ext->R, ext->G, ext->B); ext->m_StructProxy = (CTwMgr::CStructProxy *)_ClientData; } } void ANT_CALL CColorExt::InitColor3FCB(void *_ExtValue, void *_ClientData) { InitColor32CB(_ExtValue, _ClientData); CColorExt *ext = static_cast<CColorExt *>(_ExtValue); if( ext ) { ext->m_IsColorF = true; ext->m_HasAlpha = false; ext->m_CanHaveAlpha = false; } } void ANT_CALL CColorExt::InitColor4FCB(void *_ExtValue, void *_ClientData) { InitColor32CB(_ExtValue, _ClientData); CColorExt *ext = static_cast<CColorExt *>(_ExtValue); if( ext ) { ext->m_IsColorF = true; ext->m_HasAlpha = true; ext->m_CanHaveAlpha = true; } } void ANT_CALL CColorExt::CopyVarFromExtCB(void *_VarValue, const void *_ExtValue, unsigned int _ExtMemberIndex, void *_ClientData) { unsigned int *var32 = static_cast<unsigned int *>(_VarValue); float *varF = static_cast<float *>(_VarValue); CColorExt *ext = (CColorExt *)(_ExtValue); CTwMgr::CMemberProxy *mProxy = static_cast<CTwMgr::CMemberProxy *>(_ClientData); if( _VarValue && ext ) { if( ext->m_HasAlpha && mProxy && mProxy->m_StructProxy && mProxy->m_StructProxy->m_Type==g_TwMgr->m_TypeColor3F ) ext->m_HasAlpha = false; // Synchronize HLS and RGB if( _ExtMemberIndex>=0 && _ExtMemberIndex<=2 ) ext->RGB2HLS(); else if( _ExtMemberIndex>=3 && _ExtMemberIndex<=5 ) ext->HLS2RGB(); else if( mProxy && _ExtMemberIndex==7 && mProxy->m_VarParent ) { assert( mProxy->m_VarParent->m_Vars.size()==8 ); if( mProxy->m_VarParent->m_Vars[0]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[1]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[2]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[3]->m_Visible != ext->m_HLS || mProxy->m_VarParent->m_Vars[4]->m_Visible != ext->m_HLS || mProxy->m_VarParent->m_Vars[5]->m_Visible != ext->m_HLS ) { mProxy->m_VarParent->m_Vars[0]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[1]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[2]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[3]->m_Visible = ext->m_HLS; mProxy->m_VarParent->m_Vars[4]->m_Visible = ext->m_HLS; mProxy->m_VarParent->m_Vars[5]->m_Visible = ext->m_HLS; mProxy->m_Bar->NotUpToDate(); } if( mProxy->m_VarParent->m_Vars[6]->m_Visible != ext->m_HasAlpha ) { mProxy->m_VarParent->m_Vars[6]->m_Visible = ext->m_HasAlpha; mProxy->m_Bar->NotUpToDate(); } if( static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[7])->m_ReadOnly ) { static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[7])->m_ReadOnly = false; mProxy->m_Bar->NotUpToDate(); } } // Convert to color32 color32 col = Color32FromARGBi((ext->m_HasAlpha ? ext->A : 255), ext->R, ext->G, ext->B); if( ext->m_OGL && !ext->m_IsColorF ) col = (col&0xff00ff00) | (unsigned char)(col>>16) | (((unsigned char)(col))<<16); if( ext->m_IsColorF ) Color32ToARGBf(col, (ext->m_HasAlpha ? varF+3 : NULL), varF+0, varF+1, varF+2); else { if( ext->m_HasAlpha ) *var32 = col; else *var32 = ((*var32)&0xff000000) | (col&0x00ffffff); } ext->m_PrevConvertedColor = col; } } void ANT_CALL CColorExt::CopyVarToExtCB(const void *_VarValue, void *_ExtValue, unsigned int _ExtMemberIndex, void *_ClientData) { const unsigned int *var32 = static_cast<const unsigned int *>(_VarValue); const float *varF = static_cast<const float *>(_VarValue); CColorExt *ext = static_cast<CColorExt *>(_ExtValue); CTwMgr::CMemberProxy *mProxy = static_cast<CTwMgr::CMemberProxy *>(_ClientData); if( _VarValue && ext ) { if( ext->m_HasAlpha && mProxy && mProxy->m_StructProxy && mProxy->m_StructProxy->m_Type==g_TwMgr->m_TypeColor3F ) ext->m_HasAlpha = false; if( mProxy && _ExtMemberIndex==7 && mProxy->m_VarParent ) { assert( mProxy->m_VarParent->m_Vars.size()==8 ); if( mProxy->m_VarParent->m_Vars[0]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[1]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[2]->m_Visible != !ext->m_HLS || mProxy->m_VarParent->m_Vars[3]->m_Visible != ext->m_HLS || mProxy->m_VarParent->m_Vars[4]->m_Visible != ext->m_HLS || mProxy->m_VarParent->m_Vars[5]->m_Visible != ext->m_HLS ) { mProxy->m_VarParent->m_Vars[0]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[1]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[2]->m_Visible = !ext->m_HLS; mProxy->m_VarParent->m_Vars[3]->m_Visible = ext->m_HLS; mProxy->m_VarParent->m_Vars[4]->m_Visible = ext->m_HLS; mProxy->m_VarParent->m_Vars[5]->m_Visible = ext->m_HLS; mProxy->m_Bar->NotUpToDate(); } if( mProxy->m_VarParent->m_Vars[6]->m_Visible != ext->m_HasAlpha ) { mProxy->m_VarParent->m_Vars[6]->m_Visible = ext->m_HasAlpha; mProxy->m_Bar->NotUpToDate(); } if( static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[7])->m_ReadOnly ) { static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[7])->m_ReadOnly = false; mProxy->m_Bar->NotUpToDate(); } } color32 col; if( ext->m_IsColorF ) col = Color32FromARGBf((ext->m_HasAlpha ? varF[3] : 1), varF[0], varF[1], varF[2]); else col = *var32; if( ext->m_OGL && !ext->m_IsColorF ) col = (col&0xff00ff00) | (unsigned char)(col>>16) | (((unsigned char)(col))<<16); Color32ToARGBi(col, (ext->m_HasAlpha ? &ext->A : NULL), &ext->R, &ext->G, &ext->B); if( (col & 0x00ffffff)!=(ext->m_PrevConvertedColor & 0x00ffffff) ) ext->RGB2HLS(); ext->m_PrevConvertedColor = col; } } void ANT_CALL CColorExt::SummaryCB(char *_SummaryString, size_t /*_SummaryMaxLength*/, const void *_ExtValue, void * /*_ClientData*/) { // copy var CColorExt *ext = (CColorExt *)(_ExtValue); if( ext && ext->m_StructProxy && ext->m_StructProxy->m_StructData ) { if( ext->m_StructProxy->m_StructGetCallback ) ext->m_StructProxy->m_StructGetCallback(ext->m_StructProxy->m_StructData, ext->m_StructProxy->m_StructClientData); //if( *(unsigned int *)(ext->m_StructProxy->m_StructData)!=ext->m_PrevConvertedColor ) CopyVarToExtCB(ext->m_StructProxy->m_StructData, ext, 99, NULL); } //unsigned int col = 0; //CopyVar32FromExtCB(&col, _ExtValue, 99, _ClientData); //_snprintf(_SummaryString, _SummaryMaxLength, "0x%.8X", col); //(void) _SummaryMaxLength, _ExtValue, _ClientData; _SummaryString[0] = ' '; // required to force background color for this value _SummaryString[1] = '\0'; } void CColorExt::CreateTypes() { if( g_TwMgr==NULL ) return; TwStructMember ColorExtMembers[] = { { "Red", TW_TYPE_INT32, offsetof(CColorExt, R), "min=0 max=255" }, { "Green", TW_TYPE_INT32, offsetof(CColorExt, G), "min=0 max=255" }, { "Blue", TW_TYPE_INT32, offsetof(CColorExt, B), "min=0 max=255" }, { "Hue", TW_TYPE_INT32, offsetof(CColorExt, H), "hide min=0 max=359" }, { "Lightness", TW_TYPE_INT32, offsetof(CColorExt, L), "hide min=0 max=255" }, { "Saturation", TW_TYPE_INT32, offsetof(CColorExt, S), "hide min=0 max=255" }, { "Alpha", TW_TYPE_INT32, offsetof(CColorExt, A), "hide min=0 max=255" }, { "Mode", TW_TYPE_BOOLCPP, offsetof(CColorExt, m_HLS), "true='HLS' false='RGB' readwrite" } }; g_TwMgr->m_TypeColor32 = TwDefineStructExt("COLOR32", ColorExtMembers, 8, sizeof(unsigned int), sizeof(CColorExt), CColorExt::InitColor32CB, CColorExt::CopyVarFromExtCB, CColorExt::CopyVarToExtCB, CColorExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 32-bit-encoded color."); g_TwMgr->m_TypeColor3F = TwDefineStructExt("COLOR3F", ColorExtMembers, 8, 3*sizeof(float), sizeof(CColorExt), CColorExt::InitColor3FCB, CColorExt::CopyVarFromExtCB, CColorExt::CopyVarToExtCB, CColorExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 3-floats-encoded RGB color."); g_TwMgr->m_TypeColor4F = TwDefineStructExt("COLOR4F", ColorExtMembers, 8, 4*sizeof(float), sizeof(CColorExt), CColorExt::InitColor4FCB, CColorExt::CopyVarFromExtCB, CColorExt::CopyVarToExtCB, CColorExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 4-floats-encoded RGBA color."); // Do not name them "TW_COLOR*" because the name is displayed in the help bar. } // --------------------------------------------------------------------------- // Quaternion ext type // --------------------------------------------------------------------------- void ANT_CALL CQuaternionExt::InitQuat4FCB(void *_ExtValue, void *_ClientData) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); if( ext ) { ext->Qx = ext->Qy = ext->Qz = 0; ext->Qs = 1; ext->Vx = 1; ext->Vy = ext->Vz = 0; ext->Angle = 0; ext->Dx = ext->Dy = ext->Dz = 0; ext->m_AAMode = false; // Axis & angle mode hidden ext->m_ShowVal = false; ext->m_IsFloat = true; ext->m_IsDir = false; ext->m_Dir[0] = ext->m_Dir[1] = ext->m_Dir[2] = 0; ext->m_DirColor = 0xffffff00; int i, j; for(i=0; i<3; ++i) for(j=0; j<3; ++j) ext->m_Permute[i][j] = (i==j) ? 1.0f : 0.0f; ext->m_StructProxy = (CTwMgr::CStructProxy *)_ClientData; ext->ConvertToAxisAngle(); ext->m_Highlighted = false; ext->m_Rotating = false; if( ext->m_StructProxy!=NULL ) { ext->m_StructProxy->m_CustomDrawCallback = CQuaternionExt::DrawCB; ext->m_StructProxy->m_CustomMouseButtonCallback = CQuaternionExt::MouseButtonCB; ext->m_StructProxy->m_CustomMouseMotionCallback = CQuaternionExt::MouseMotionCB; ext->m_StructProxy->m_CustomMouseLeaveCallback = CQuaternionExt::MouseLeaveCB; } } } void ANT_CALL CQuaternionExt::InitQuat4DCB(void *_ExtValue, void *_ClientData) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); if( ext ) { ext->Qx = ext->Qy = ext->Qz = 0; ext->Qs = 1; ext->Vx = 1; ext->Vy = ext->Vz = 0; ext->Angle = 0; ext->Dx = ext->Dy = ext->Dz = 0; ext->m_AAMode = false; // Axis & angle mode hidden ext->m_ShowVal = false; ext->m_IsFloat = false; ext->m_IsDir = false; ext->m_Dir[0] = ext->m_Dir[1] = ext->m_Dir[2] = 0; ext->m_DirColor = 0xffffff00; int i, j; for(i=0; i<3; ++i) for(j=0; j<3; ++j) ext->m_Permute[i][j] = (i==j) ? 1.0f : 0.0f; ext->m_StructProxy = (CTwMgr::CStructProxy *)_ClientData; ext->ConvertToAxisAngle(); ext->m_Highlighted = false; ext->m_Rotating = false; if( ext->m_StructProxy!=NULL ) { ext->m_StructProxy->m_CustomDrawCallback = CQuaternionExt::DrawCB; ext->m_StructProxy->m_CustomMouseButtonCallback = CQuaternionExt::MouseButtonCB; ext->m_StructProxy->m_CustomMouseMotionCallback = CQuaternionExt::MouseMotionCB; ext->m_StructProxy->m_CustomMouseLeaveCallback = CQuaternionExt::MouseLeaveCB; } } } void ANT_CALL CQuaternionExt::InitDir3FCB(void *_ExtValue, void *_ClientData) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); if( ext ) { ext->Qx = ext->Qy = ext->Qz = 0; ext->Qs = 1; ext->Vx = 1; ext->Vy = ext->Vz = 0; ext->Angle = 0; ext->Dx = 1; ext->Dy = ext->Dz = 0; ext->m_AAMode = false; // Axis & angle mode hidden ext->m_ShowVal = true; ext->m_IsFloat = true; ext->m_IsDir = true; ext->m_Dir[0] = ext->m_Dir[1] = ext->m_Dir[2] = 0; ext->m_DirColor = 0xffffff00; int i, j; for(i=0; i<3; ++i) for(j=0; j<3; ++j) ext->m_Permute[i][j] = (i==j) ? 1.0f : 0.0f; ext->m_StructProxy = (CTwMgr::CStructProxy *)_ClientData; ext->ConvertToAxisAngle(); ext->m_Highlighted = false; ext->m_Rotating = false; if( ext->m_StructProxy!=NULL ) { ext->m_StructProxy->m_CustomDrawCallback = CQuaternionExt::DrawCB; ext->m_StructProxy->m_CustomMouseButtonCallback = CQuaternionExt::MouseButtonCB; ext->m_StructProxy->m_CustomMouseMotionCallback = CQuaternionExt::MouseMotionCB; ext->m_StructProxy->m_CustomMouseLeaveCallback = CQuaternionExt::MouseLeaveCB; } } } void ANT_CALL CQuaternionExt::InitDir3DCB(void *_ExtValue, void *_ClientData) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); if( ext ) { ext->Qx = ext->Qy = ext->Qz = 0; ext->Qs = 1; ext->Vx = 1; ext->Vy = ext->Vz = 0; ext->Angle = 0; ext->Dx = 1; ext->Dy = ext->Dz = 0; ext->m_AAMode = false; // Axis & angle mode hidden ext->m_ShowVal = true; ext->m_IsFloat = false; ext->m_IsDir = true; ext->m_Dir[0] = ext->m_Dir[1] = ext->m_Dir[2] = 0; ext->m_DirColor = 0xffffff00; int i, j; for(i=0; i<3; ++i) for(j=0; j<3; ++j) ext->m_Permute[i][j] = (i==j) ? 1.0f : 0.0f; ext->m_StructProxy = (CTwMgr::CStructProxy *)_ClientData; ext->ConvertToAxisAngle(); ext->m_Highlighted = false; ext->m_Rotating = false; if( ext->m_StructProxy!=NULL ) { ext->m_StructProxy->m_CustomDrawCallback = CQuaternionExt::DrawCB; ext->m_StructProxy->m_CustomMouseButtonCallback = CQuaternionExt::MouseButtonCB; ext->m_StructProxy->m_CustomMouseMotionCallback = CQuaternionExt::MouseMotionCB; ext->m_StructProxy->m_CustomMouseLeaveCallback = CQuaternionExt::MouseLeaveCB; } } } void ANT_CALL CQuaternionExt::CopyVarFromExtCB(void *_VarValue, const void *_ExtValue, unsigned int _ExtMemberIndex, void *_ClientData) { CQuaternionExt *ext = (CQuaternionExt *)(_ExtValue); CTwMgr::CMemberProxy *mProxy = static_cast<CTwMgr::CMemberProxy *>(_ClientData); if( _VarValue && ext ) { // Synchronize Quat and AxisAngle if( _ExtMemberIndex>=4 && _ExtMemberIndex<=7 ) { ext->ConvertToAxisAngle(); // show/hide quat values if( _ExtMemberIndex==4 && mProxy && mProxy->m_VarParent ) { assert( mProxy->m_VarParent->m_Vars.size()==16 ); bool visible = ext->m_ShowVal; if( ext->m_IsDir ) { if( mProxy->m_VarParent->m_Vars[13]->m_Visible != visible || mProxy->m_VarParent->m_Vars[14]->m_Visible != visible || mProxy->m_VarParent->m_Vars[15]->m_Visible != visible ) { mProxy->m_VarParent->m_Vars[13]->m_Visible = visible; mProxy->m_VarParent->m_Vars[14]->m_Visible = visible; mProxy->m_VarParent->m_Vars[15]->m_Visible = visible; mProxy->m_Bar->NotUpToDate(); } } else { if( mProxy->m_VarParent->m_Vars[4]->m_Visible != visible || mProxy->m_VarParent->m_Vars[5]->m_Visible != visible || mProxy->m_VarParent->m_Vars[6]->m_Visible != visible || mProxy->m_VarParent->m_Vars[7]->m_Visible != visible ) { mProxy->m_VarParent->m_Vars[4]->m_Visible = visible; mProxy->m_VarParent->m_Vars[5]->m_Visible = visible; mProxy->m_VarParent->m_Vars[6]->m_Visible = visible; mProxy->m_VarParent->m_Vars[7]->m_Visible = visible; mProxy->m_Bar->NotUpToDate(); } } } } else if( _ExtMemberIndex>=8 && _ExtMemberIndex<=11 ) ext->ConvertFromAxisAngle(); else if( mProxy && _ExtMemberIndex==12 && mProxy->m_VarParent && !ext->m_IsDir ) { assert( mProxy->m_VarParent->m_Vars.size()==16 ); bool aa = ext->m_AAMode; if( mProxy->m_VarParent->m_Vars[4]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[5]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[6]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[7]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[8 ]->m_Visible != aa || mProxy->m_VarParent->m_Vars[9 ]->m_Visible != aa || mProxy->m_VarParent->m_Vars[10]->m_Visible != aa || mProxy->m_VarParent->m_Vars[11]->m_Visible != aa ) { mProxy->m_VarParent->m_Vars[4]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[5]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[6]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[7]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[8 ]->m_Visible = aa; mProxy->m_VarParent->m_Vars[9 ]->m_Visible = aa; mProxy->m_VarParent->m_Vars[10]->m_Visible = aa; mProxy->m_VarParent->m_Vars[11]->m_Visible = aa; mProxy->m_Bar->NotUpToDate(); } if( static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[12])->m_ReadOnly ) { static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[12])->m_ReadOnly = false; mProxy->m_Bar->NotUpToDate(); } } if( ext->m_IsFloat ) { float *var = static_cast<float *>(_VarValue); if( ext->m_IsDir ) { var[0] = (float)ext->Dx; var[1] = (float)ext->Dy; var[2] = (float)ext->Dz; } else // quat { var[0] = (float)ext->Qx; var[1] = (float)ext->Qy; var[2] = (float)ext->Qz; var[3] = (float)ext->Qs; } } else { double *var = static_cast<double *>(_VarValue); if( ext->m_IsDir ) { var[0] = ext->Dx; var[1] = ext->Dy; var[2] = ext->Dz; } else // quat { var[0] = ext->Qx; var[1] = ext->Qy; var[2] = ext->Qz; var[3] = ext->Qs; } } } } void ANT_CALL CQuaternionExt::CopyVarToExtCB(const void *_VarValue, void *_ExtValue, unsigned int _ExtMemberIndex, void *_ClientData) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); CTwMgr::CMemberProxy *mProxy = static_cast<CTwMgr::CMemberProxy *>(_ClientData); (void)mProxy; if( _VarValue && ext ) { if( mProxy && _ExtMemberIndex==12 && mProxy->m_VarParent && !ext->m_IsDir ) { assert( mProxy->m_VarParent->m_Vars.size()==16 ); bool aa = ext->m_AAMode; if( mProxy->m_VarParent->m_Vars[4]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[5]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[6]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[7]->m_Visible != !aa || mProxy->m_VarParent->m_Vars[8 ]->m_Visible != aa || mProxy->m_VarParent->m_Vars[9 ]->m_Visible != aa || mProxy->m_VarParent->m_Vars[10]->m_Visible != aa || mProxy->m_VarParent->m_Vars[11]->m_Visible != aa ) { mProxy->m_VarParent->m_Vars[4]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[5]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[6]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[7]->m_Visible = !aa; mProxy->m_VarParent->m_Vars[8 ]->m_Visible = aa; mProxy->m_VarParent->m_Vars[9 ]->m_Visible = aa; mProxy->m_VarParent->m_Vars[10]->m_Visible = aa; mProxy->m_VarParent->m_Vars[11]->m_Visible = aa; mProxy->m_Bar->NotUpToDate(); } if( static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[12])->m_ReadOnly ) { static_cast<CTwVarAtom *>(mProxy->m_VarParent->m_Vars[12])->m_ReadOnly = false; mProxy->m_Bar->NotUpToDate(); } } else if( mProxy && _ExtMemberIndex==4 && mProxy->m_VarParent ) { assert( mProxy->m_VarParent->m_Vars.size()==16 ); bool visible = ext->m_ShowVal; if( ext->m_IsDir ) { if( mProxy->m_VarParent->m_Vars[13]->m_Visible != visible || mProxy->m_VarParent->m_Vars[14]->m_Visible != visible || mProxy->m_VarParent->m_Vars[15]->m_Visible != visible ) { mProxy->m_VarParent->m_Vars[13]->m_Visible = visible; mProxy->m_VarParent->m_Vars[14]->m_Visible = visible; mProxy->m_VarParent->m_Vars[15]->m_Visible = visible; mProxy->m_Bar->NotUpToDate(); } } else { if( mProxy->m_VarParent->m_Vars[4]->m_Visible != visible || mProxy->m_VarParent->m_Vars[5]->m_Visible != visible || mProxy->m_VarParent->m_Vars[6]->m_Visible != visible || mProxy->m_VarParent->m_Vars[7]->m_Visible != visible ) { mProxy->m_VarParent->m_Vars[4]->m_Visible = visible; mProxy->m_VarParent->m_Vars[5]->m_Visible = visible; mProxy->m_VarParent->m_Vars[6]->m_Visible = visible; mProxy->m_VarParent->m_Vars[7]->m_Visible = visible; mProxy->m_Bar->NotUpToDate(); } } } if( ext->m_IsFloat ) { const float *var = static_cast<const float *>(_VarValue); if( ext->m_IsDir ) { ext->Dx = var[0]; ext->Dy = var[1]; ext->Dz = var[2]; QuatFromDir(&ext->Qx, &ext->Qy, &ext->Qz, &ext->Qs, var[0], var[1], var[2]); } else { ext->Qx = var[0]; ext->Qy = var[1]; ext->Qz = var[2]; ext->Qs = var[3]; } } else { const double *var = static_cast<const double *>(_VarValue); if( ext->m_IsDir ) { ext->Dx = var[0]; ext->Dy = var[1]; ext->Dz = var[2]; QuatFromDir(&ext->Qx, &ext->Qy, &ext->Qz, &ext->Qs, var[0], var[1], var[2]); } else { ext->Qx = var[0]; ext->Qy = var[1]; ext->Qz = var[2]; ext->Qs = var[3]; } } ext->ConvertToAxisAngle(); } } void ANT_CALL CQuaternionExt::SummaryCB(char *_SummaryString, size_t _SummaryMaxLength, const void *_ExtValue, void * /*_ClientData*/) { const CQuaternionExt *ext = static_cast<const CQuaternionExt *>(_ExtValue); if( ext ) { if( ext->m_AAMode ) _snprintf(_SummaryString, _SummaryMaxLength, "V={%.2f,%.2f,%.2f} A=%.0f%c", ext->Vx, ext->Vy, ext->Vz, ext->Angle, 176); else if( ext->m_IsDir ) { //float d[] = {1, 0, 0}; //ApplyQuat(d+0, d+1, d+2, 1, 0, 0, (float)ext->Qx, (float)ext->Qy, (float)ext->Qz, (float)ext->Qs); _snprintf(_SummaryString, _SummaryMaxLength, "V={%.2f,%.2f,%.2f}", ext->Dx, ext->Dy, ext->Dz); } else _snprintf(_SummaryString, _SummaryMaxLength, "Q={x:%.2f,y:%.2f,z:%.2f,s:%.2f}", ext->Qx, ext->Qy, ext->Qz, ext->Qs); } else { _SummaryString[0] = ' '; // required to force background color for this value _SummaryString[1] = '\0'; } } TwType CQuaternionExt::s_CustomType = TW_TYPE_UNDEF; vector<float> CQuaternionExt::s_SphTri; vector<color32> CQuaternionExt::s_SphCol; vector<int> CQuaternionExt::s_SphTriProj; vector<color32> CQuaternionExt::s_SphColLight; vector<float> CQuaternionExt::s_ArrowTri[4]; vector<float> CQuaternionExt::s_ArrowNorm[4]; vector<int> CQuaternionExt::s_ArrowTriProj[4]; vector<color32> CQuaternionExt::s_ArrowColLight[4]; void CQuaternionExt::CreateTypes() { if( g_TwMgr==NULL ) return; s_CustomType = (TwType)(TW_TYPE_CUSTOM_BASE + (int)g_TwMgr->m_Customs.size()); g_TwMgr->m_Customs.push_back(NULL); // increment custom type number for(int pass=0; pass<2; pass++) // pass 0: create quat types; pass 1: create dir types { const char *quatDefPass0 = "step=0.01 hide"; const char *quatDefPass1 = "step=0.01 hide"; const char *quatSDefPass0 = "step=0.01 min=-1 max=1 hide"; const char *quatSDefPass1 = "step=0.01 min=-1 max=1 hide"; const char *dirDefPass0 = "step=0.01 hide"; const char *dirDefPass1 = "step=0.01"; const char *quatDef = (pass==0) ? quatDefPass0 : quatDefPass1; const char *quatSDef = (pass==0) ? quatSDefPass0 : quatSDefPass1; const char *dirDef = (pass==0) ? dirDefPass0 : dirDefPass1; TwStructMember QuatExtMembers[] = { { "0", s_CustomType, 0, "" }, { "1", s_CustomType, 0, "" }, { "2", s_CustomType, 0, "" }, { "3", s_CustomType, 0, "" }, { "Quat X", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Qx), quatDef }, // copy of the source quaternion { "Quat Y", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Qy), quatDef }, { "Quat Z", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Qz), quatDef }, { "Quat S", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Qs), quatSDef }, { "Axis X", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Vx), "step=0.01 hide" }, // axis and angle conversion -> Mode hidden because it is not equivalent to a quat (would have required vector renormalization) { "Axis Y", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Vy), "step=0.01 hide" }, { "Axis Z", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Vz), "step=0.01 hide" }, { "Angle (degree)", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Angle), "step=1 min=-360 max=360 hide" }, { "Mode", TW_TYPE_BOOLCPP, offsetof(CQuaternionExt, m_AAMode), "true='Axis Angle' false='Quaternion' readwrite hide" }, { "Dir X", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Dx), dirDef }, // copy of the source direction { "Dir Y", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Dy), dirDef }, { "Dir Z", TW_TYPE_DOUBLE, offsetof(CQuaternionExt, Dz), dirDef } }; if( pass==0 ) { g_TwMgr->m_TypeQuat4F = TwDefineStructExt("QUAT4F", QuatExtMembers, sizeof(QuatExtMembers)/sizeof(QuatExtMembers[0]), 4*sizeof(float), sizeof(CQuaternionExt), CQuaternionExt::InitQuat4FCB, CQuaternionExt::CopyVarFromExtCB, CQuaternionExt::CopyVarToExtCB, CQuaternionExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 4-floats-encoded quaternion"); g_TwMgr->m_TypeQuat4D = TwDefineStructExt("QUAT4D", QuatExtMembers, sizeof(QuatExtMembers)/sizeof(QuatExtMembers[0]), 4*sizeof(double), sizeof(CQuaternionExt), CQuaternionExt::InitQuat4DCB, CQuaternionExt::CopyVarFromExtCB, CQuaternionExt::CopyVarToExtCB, CQuaternionExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 4-doubles-encoded quaternion"); } else if( pass==1 ) { g_TwMgr->m_TypeDir3F = TwDefineStructExt("DIR4F", QuatExtMembers, sizeof(QuatExtMembers)/sizeof(QuatExtMembers[0]), 3*sizeof(float), sizeof(CQuaternionExt), CQuaternionExt::InitDir3FCB, CQuaternionExt::CopyVarFromExtCB, CQuaternionExt::CopyVarToExtCB, CQuaternionExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 3-floats-encoded direction"); g_TwMgr->m_TypeDir3D = TwDefineStructExt("DIR4D", QuatExtMembers, sizeof(QuatExtMembers)/sizeof(QuatExtMembers[0]), 3*sizeof(double), sizeof(CQuaternionExt), CQuaternionExt::InitDir3DCB, CQuaternionExt::CopyVarFromExtCB, CQuaternionExt::CopyVarToExtCB, CQuaternionExt::SummaryCB, CTwMgr::CStruct::s_PassProxyAsClientData, "A 3-doubles-encoded direction"); } } CreateSphere(); CreateArrow(); } void CQuaternionExt::ConvertToAxisAngle() { if( fabs(Qs)>(1.0 + FLOAT_EPS) ) { //Vx = Vy = Vz = 0; // no, keep the previous value Angle = 0; } else { double a; if( Qs>=1.0f ) a = 0; // and keep V else if( Qs<=-1.0f ) a = DOUBLE_PI; // and keep V else if( fabs(Qx*Qx+Qy*Qy+Qz*Qz+Qs*Qs)<FLOAT_EPS_SQ ) a = 0; else { a = acos(Qs); if( a*Angle<0 ) // Preserve the sign of Angle a = -a; double f = 1.0f / sin(a); Vx = Qx * f; Vy = Qy * f; Vz = Qz * f; } Angle = 2.0*a; } // if( Angle>FLOAT_PI ) // Angle -= 2.0f*FLOAT_PI; // else if( Angle<-FLOAT_PI ) // Angle += 2.0f*FLOAT_PI; Angle = RadToDeg(Angle); if( fabs(Angle)<FLOAT_EPS && fabs(Vx*Vx+Vy*Vy+Vz*Vz)<FLOAT_EPS_SQ ) Vx = 1.0e-7; // all components cannot be null } void CQuaternionExt::ConvertFromAxisAngle() { double n = Vx*Vx + Vy*Vy + Vz*Vz; if( fabs(n)>FLOAT_EPS_SQ ) { double f = 0.5*DegToRad(Angle); Qs = cos(f); //do not normalize //if( fabs(n - 1.0)>FLOAT_EPS_SQ ) // f = sin(f) * (1.0/sqrt(n)) ; //else // f = sin(f); f = sin(f); Qx = Vx * f; Qy = Vy * f; Qz = Vz * f; } else { Qs = 1.0; Qx = Qy = Qz = 0.0; } } void CQuaternionExt::CopyToVar() { if( m_StructProxy!=NULL ) { if( m_StructProxy->m_StructSetCallback!=NULL ) { if( m_IsFloat ) { if( m_IsDir ) { float d[] = {1, 0, 0}; ApplyQuat(d+0, d+1, d+2, 1, 0, 0, (float)Qx, (float)Qy, (float)Qz, (float)Qs); float l = (float)sqrt(Dx*Dx + Dy*Dy + Dz*Dz); d[0] *= l; d[1] *= l; d[2] *= l; Dx = d[0]; Dy = d[1]; Dz = d[2]; // update also Dx,Dy,Dz m_StructProxy->m_StructSetCallback(d, m_StructProxy->m_StructClientData); } else { float q[] = { (float)Qx, (float)Qy, (float)Qz, (float)Qs }; m_StructProxy->m_StructSetCallback(q, m_StructProxy->m_StructClientData); } } else { if( m_IsDir ) { float d[] = {1, 0, 0}; ApplyQuat(d+0, d+1, d+2, 1, 0, 0, (float)Qx, (float)Qy, (float)Qz, (float)Qs); double l = sqrt(Dx*Dx + Dy*Dy + Dz*Dz); double dd[] = {l*d[0], l*d[1], l*d[2]}; Dx = dd[0]; Dy = dd[1]; Dz = dd[2]; // update also Dx,Dy,Dz m_StructProxy->m_StructSetCallback(dd, m_StructProxy->m_StructClientData); } else { double q[] = { Qx, Qy, Qz, Qs }; m_StructProxy->m_StructSetCallback(q, m_StructProxy->m_StructClientData); } } } else if( m_StructProxy->m_StructData!=NULL ) { if( m_IsFloat ) { if( m_IsDir ) { float *d = static_cast<float *>(m_StructProxy->m_StructData); ApplyQuat(d+0, d+1, d+2, 1, 0, 0, (float)Qx, (float)Qy, (float)Qz, (float)Qs); float l = (float)sqrt(Dx*Dx + Dy*Dy + Dz*Dz); d[0] *= l; d[1] *= l; d[2] *= l; Dx = d[0]; Dy = d[1]; Dz = d[2]; // update also Dx,Dy,Dz } else { float *q = static_cast<float *>(m_StructProxy->m_StructData); q[0] = (float)Qx; q[1] = (float)Qy; q[2] = (float)Qz; q[3] = (float)Qs; } } else { if( m_IsDir ) { double *dd = static_cast<double *>(m_StructProxy->m_StructData); float d[] = {1, 0, 0}; ApplyQuat(d+0, d+1, d+2, 1, 0, 0, (float)Qx, (float)Qy, (float)Qz, (float)Qs); double l = sqrt(Dx*Dx + Dy*Dy + Dz*Dz); dd[0] = l*d[0]; dd[1] = l*d[1]; dd[2] = l*d[2]; Dx = dd[0]; Dy = dd[1]; Dz = dd[2]; // update also Dx,Dy,Dz } else { double *q = static_cast<double *>(m_StructProxy->m_StructData); q[0] = Qx; q[1] = Qy; q[2] = Qz; q[3] = Qs; } } } } } void CQuaternionExt::CreateSphere() { const int SUBDIV = 7; s_SphTri.clear(); s_SphCol.clear(); const float A[8*3] = { 1,0,0, 0,0,-1, -1,0,0, 0,0,1, 0,0,1, 1,0,0, 0,0,-1, -1,0,0 }; const float B[8*3] = { 0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,-1,0, 0,-1,0, 0,-1,0, 0,-1,0 }; const float C[8*3] = { 0,0,1, 1,0,0, 0,0,-1, -1,0,0, 1,0,0, 0,0,-1, -1,0,0, 0,0,1 }; //const color32 COL_A[8] = { 0xffff8080, 0xff000080, 0xff800000, 0xff8080ff, 0xff8080ff, 0xffff8080, 0xff000080, 0xff800000 }; //const color32 COL_B[8] = { 0xff80ff80, 0xff80ff80, 0xff80ff80, 0xff80ff80, 0xff008000, 0xff008000, 0xff008000, 0xff008000 }; //const color32 COL_C[8] = { 0xff8080ff, 0xffff8080, 0xff000080, 0xff800000, 0xffff8080, 0xff000080, 0xff800000, 0xff8080ff }; const color32 COL_A[8] = { 0xffffffff, 0xffffff40, 0xff40ff40, 0xff40ffff, 0xffff40ff, 0xffff4040, 0xff404040, 0xff4040ff }; const color32 COL_B[8] = { 0xffffffff, 0xffffff40, 0xff40ff40, 0xff40ffff, 0xffff40ff, 0xffff4040, 0xff404040, 0xff4040ff }; const color32 COL_C[8] = { 0xffffffff, 0xffffff40, 0xff40ff40, 0xff40ffff, 0xffff40ff, 0xffff4040, 0xff404040, 0xff4040ff }; int i, j, k, l; float xa, ya, za, xb, yb, zb, xc, yc, zc, x, y, z, norm, u[3], v[3]; color32 col; for( i=0; i<8; ++i ) { xa = A[3*i+0]; ya = A[3*i+1]; za = A[3*i+2]; xb = B[3*i+0]; yb = B[3*i+1]; zb = B[3*i+2]; xc = C[3*i+0]; yc = C[3*i+1]; zc = C[3*i+2]; for( j=0; j<=SUBDIV; ++j ) for( k=0; k<=2*(SUBDIV-j); ++k ) { if( k%2==0 ) { u[0] = ((float)j)/(SUBDIV+1); v[0] = ((float)(k/2))/(SUBDIV+1); u[1] = ((float)(j+1))/(SUBDIV+1); v[1] = ((float)(k/2))/(SUBDIV+1); u[2] = ((float)j)/(SUBDIV+1); v[2] = ((float)(k/2+1))/(SUBDIV+1); } else { u[0] = ((float)j)/(SUBDIV+1); v[0] = ((float)(k/2+1))/(SUBDIV+1); u[1] = ((float)(j+1))/(SUBDIV+1); v[1] = ((float)(k/2))/(SUBDIV+1); u[2] = ((float)(j+1))/(SUBDIV+1); v[2] = ((float)(k/2+1))/(SUBDIV+1); } for( l=0; l<3; ++l ) { x = (1.0f-u[l]-v[l])*xa + u[l]*xb + v[l]*xc; y = (1.0f-u[l]-v[l])*ya + u[l]*yb + v[l]*yc; z = (1.0f-u[l]-v[l])*za + u[l]*zb + v[l]*zc; norm = sqrtf(x*x+y*y+z*z); x /= norm; y /= norm; z /= norm; s_SphTri.push_back(x); s_SphTri.push_back(y); s_SphTri.push_back(z); if( u[l]+v[l]>FLOAT_EPS ) col = ColorBlend(COL_A[i], ColorBlend(COL_B[i], COL_C[i], v[l]/(u[l]+v[l])), u[l]+v[l]); else col = COL_A[i]; //if( (j==0 && k==0) || (j==0 && k==2*SUBDIV) || (j==SUBDIV && k==0) ) // col = 0xffff0000; s_SphCol.push_back(col); } } } s_SphTriProj.clear(); s_SphTriProj.resize(2*s_SphCol.size(), 0); s_SphColLight.clear(); s_SphColLight.resize(s_SphCol.size(), 0); } void CQuaternionExt::CreateArrow() { const int SUBDIV = 15; const float CYL_RADIUS = 0.08f; const float CONE_RADIUS = 0.16f; const float CONE_LENGTH = 0.25f; const float ARROW_BGN = -1.1f; const float ARROW_END = 1.15f; int i; for(i=0; i<4; ++i) { s_ArrowTri[i].clear(); s_ArrowNorm[i].clear(); } float x0, x1, y0, y1, z0, z1, a0, a1, nx, nn; for(i=0; i<SUBDIV; ++i) { a0 = 2.0f*FLOAT_PI*(float(i))/SUBDIV; a1 = 2.0f*FLOAT_PI*(float(i+1))/SUBDIV; x0 = ARROW_BGN; x1 = ARROW_END-CONE_LENGTH; y0 = cosf(a0); z0 = sinf(a0); y1 = cosf(a1); z1 = sinf(a1); s_ArrowTri[ARROW_CYL].push_back(x1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z0); s_ArrowTri[ARROW_CYL].push_back(x0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z0); s_ArrowTri[ARROW_CYL].push_back(x0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z1); s_ArrowTri[ARROW_CYL].push_back(x1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z0); s_ArrowTri[ARROW_CYL].push_back(x0); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z1); s_ArrowTri[ARROW_CYL].push_back(x1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*y1); s_ArrowTri[ARROW_CYL].push_back(CYL_RADIUS*z1); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y0); s_ArrowNorm[ARROW_CYL].push_back(z0); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y0); s_ArrowNorm[ARROW_CYL].push_back(z0); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y1); s_ArrowNorm[ARROW_CYL].push_back(z1); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y0); s_ArrowNorm[ARROW_CYL].push_back(z0); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y1); s_ArrowNorm[ARROW_CYL].push_back(z1); s_ArrowNorm[ARROW_CYL].push_back(0); s_ArrowNorm[ARROW_CYL].push_back(y1); s_ArrowNorm[ARROW_CYL].push_back(z1); s_ArrowTri[ARROW_CYL_CAP].push_back(x0); s_ArrowTri[ARROW_CYL_CAP].push_back(0); s_ArrowTri[ARROW_CYL_CAP].push_back(0); s_ArrowTri[ARROW_CYL_CAP].push_back(x0); s_ArrowTri[ARROW_CYL_CAP].push_back(CYL_RADIUS*y1); s_ArrowTri[ARROW_CYL_CAP].push_back(CYL_RADIUS*z1); s_ArrowTri[ARROW_CYL_CAP].push_back(x0); s_ArrowTri[ARROW_CYL_CAP].push_back(CYL_RADIUS*y0); s_ArrowTri[ARROW_CYL_CAP].push_back(CYL_RADIUS*z0); s_ArrowNorm[ARROW_CYL_CAP].push_back(-1); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); s_ArrowNorm[ARROW_CYL_CAP].push_back(-1); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); s_ArrowNorm[ARROW_CYL_CAP].push_back(-1); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); s_ArrowNorm[ARROW_CYL_CAP].push_back(0); x0 = ARROW_END-CONE_LENGTH; x1 = ARROW_END; nx = CONE_RADIUS/(x1-x0); nn = 1.0f/sqrtf(nx*nx+1); s_ArrowTri[ARROW_CONE].push_back(x1); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowTri[ARROW_CONE].push_back(x0); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*y0); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*z0); s_ArrowTri[ARROW_CONE].push_back(x0); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*y1); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*z1); s_ArrowTri[ARROW_CONE].push_back(x1); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowTri[ARROW_CONE].push_back(x0); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*y1); s_ArrowTri[ARROW_CONE].push_back(CONE_RADIUS*z1); s_ArrowTri[ARROW_CONE].push_back(x1); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowTri[ARROW_CONE].push_back(0); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y0); s_ArrowNorm[ARROW_CONE].push_back(nn*z0); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y0); s_ArrowNorm[ARROW_CONE].push_back(nn*z0); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y1); s_ArrowNorm[ARROW_CONE].push_back(nn*z1); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y0); s_ArrowNorm[ARROW_CONE].push_back(nn*z0); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y1); s_ArrowNorm[ARROW_CONE].push_back(nn*z1); s_ArrowNorm[ARROW_CONE].push_back(nn*nx); s_ArrowNorm[ARROW_CONE].push_back(nn*y1); s_ArrowNorm[ARROW_CONE].push_back(nn*z1); s_ArrowTri[ARROW_CONE_CAP].push_back(x0); s_ArrowTri[ARROW_CONE_CAP].push_back(0); s_ArrowTri[ARROW_CONE_CAP].push_back(0); s_ArrowTri[ARROW_CONE_CAP].push_back(x0); s_ArrowTri[ARROW_CONE_CAP].push_back(CONE_RADIUS*y1); s_ArrowTri[ARROW_CONE_CAP].push_back(CONE_RADIUS*z1); s_ArrowTri[ARROW_CONE_CAP].push_back(x0); s_ArrowTri[ARROW_CONE_CAP].push_back(CONE_RADIUS*y0); s_ArrowTri[ARROW_CONE_CAP].push_back(CONE_RADIUS*z0); s_ArrowNorm[ARROW_CONE_CAP].push_back(-1); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); s_ArrowNorm[ARROW_CONE_CAP].push_back(-1); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); s_ArrowNorm[ARROW_CONE_CAP].push_back(-1); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); s_ArrowNorm[ARROW_CONE_CAP].push_back(0); } for(i=0; i<4; ++i) { s_ArrowTriProj[i].clear(); s_ArrowTriProj[i].resize(2*(s_ArrowTri[i].size()/3), 0); s_ArrowColLight[i].clear(); s_ArrowColLight[i].resize(s_ArrowTri[i].size()/3, 0); } } static inline void QuatMult(double *out, const double *q1, const double *q2) { out[0] = q1[3]*q2[0] + q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1]; out[1] = q1[3]*q2[1] + q1[1]*q2[3] + q1[2]*q2[0] - q1[0]*q2[2]; out[2] = q1[3]*q2[2] + q1[2]*q2[3] + q1[0]*q2[1] - q1[1]*q2[0]; out[3] = q1[3]*q2[3] - (q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2]); } static inline void QuatFromAxisAngle(double *out, const double *axis, double angle) { double n = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2]; if( fabs(n)>DOUBLE_EPS ) { double f = 0.5*angle; out[3] = cos(f); f = sin(f)/sqrt(n); out[0] = axis[0]*f; out[1] = axis[1]*f; out[2] = axis[2]*f; } else { out[3] = 1.0; out[0] = out[1] = out[2] = 0.0; } } static inline void Vec3Cross(double *out, const double *a, const double *b) { out[0] = a[1]*b[2]-a[2]*b[1]; out[1] = a[2]*b[0]-a[0]*b[2]; out[2] = a[0]*b[1]-a[1]*b[0]; } static inline double Vec3Dot(const double *a, const double *b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; } static inline void Vec3RotY(float *x, float *y, float *z) { (void)y; float tmp = *x; *x = - *z; *z = tmp; } static inline void Vec3RotZ(float *x, float *y, float *z) { (void)z; float tmp = *x; *x = - *y; *y = tmp; } void CQuaternionExt::ApplyQuat(float *outX, float *outY, float *outZ, float x, float y, float z, float qx, float qy, float qz, float qs) { float ps = - qx * x - qy * y - qz * z; float px = qs * x + qy * z - qz * y; float py = qs * y + qz * x - qx * z; float pz = qs * z + qx * y - qy * x; *outX = - ps * qx + px * qs - py * qz + pz * qy; *outY = - ps * qy + py * qs - pz * qx + px * qz; *outZ = - ps * qz + pz * qs - px * qy + py * qx; } void CQuaternionExt::QuatFromDir(double *outQx, double *outQy, double *outQz, double *outQs, double dx, double dy, double dz) { // compute a quaternion that rotates (1,0,0) to (dx,dy,dz) double dn = sqrt(dx*dx + dy*dy + dz*dz); if( dn<DOUBLE_EPS_SQ ) { *outQx = *outQy = *outQz = 0; *outQs = 1; } else { double rotAxis[3] = { 0, -dz, dy }; if( rotAxis[0]*rotAxis[0] + rotAxis[1]*rotAxis[1] + rotAxis[2]*rotAxis[2]<DOUBLE_EPS_SQ ) { rotAxis[0] = rotAxis[1] = 0; rotAxis[2] = 1; } double rotAngle = acos(dx/dn); double rotQuat[4]; QuatFromAxisAngle(rotQuat, rotAxis, rotAngle); *outQx = rotQuat[0]; *outQy = rotQuat[1]; *outQz = rotQuat[2]; *outQs = rotQuat[3]; } } void CQuaternionExt::Permute(float *outX, float *outY, float *outZ, float x, float y, float z) { float px = x, py = y, pz = z; *outX = m_Permute[0][0]*px + m_Permute[1][0]*py + m_Permute[2][0]*pz; *outY = m_Permute[0][1]*px + m_Permute[1][1]*py + m_Permute[2][1]*pz; *outZ = m_Permute[0][2]*px + m_Permute[1][2]*py + m_Permute[2][2]*pz; } void CQuaternionExt::PermuteInv(float *outX, float *outY, float *outZ, float x, float y, float z) { float px = x, py = y, pz = z; *outX = m_Permute[0][0]*px + m_Permute[0][1]*py + m_Permute[0][2]*pz; *outY = m_Permute[1][0]*px + m_Permute[1][1]*py + m_Permute[1][2]*pz; *outZ = m_Permute[2][0]*px + m_Permute[2][1]*py + m_Permute[2][2]*pz; } void CQuaternionExt::Permute(double *outX, double *outY, double *outZ, double x, double y, double z) { double px = x, py = y, pz = z; *outX = m_Permute[0][0]*px + m_Permute[1][0]*py + m_Permute[2][0]*pz; *outY = m_Permute[0][1]*px + m_Permute[1][1]*py + m_Permute[2][1]*pz; *outZ = m_Permute[0][2]*px + m_Permute[1][2]*py + m_Permute[2][2]*pz; } void CQuaternionExt::PermuteInv(double *outX, double *outY, double *outZ, double x, double y, double z) { double px = x, py = y, pz = z; *outX = m_Permute[0][0]*px + m_Permute[0][1]*py + m_Permute[0][2]*pz; *outY = m_Permute[1][0]*px + m_Permute[1][1]*py + m_Permute[1][2]*pz; *outZ = m_Permute[2][0]*px + m_Permute[2][1]*py + m_Permute[2][2]*pz; } static inline float QuatD(int w, int h) { return (float)min(abs(w), abs(h)) - 4; } static inline int QuatPX(float x, int w, int h) { return (int)(x*0.5f*QuatD(w, h) + (float)w*0.5f + 0.5f); } static inline int QuatPY(float y, int w, int h) { return (int)(-y*0.5f*QuatD(w, h) + (float)h*0.5f - 0.5f); } static inline float QuatIX(int x, int w, int h) { return (2.0f*(float)x - (float)w - 1.0f)/QuatD(w, h); } static inline float QuatIY(int y, int w, int h) { return (-2.0f*(float)y + (float)h - 1.0f)/QuatD(w, h); } void CQuaternionExt::DrawCB(int w, int h, void *_ExtValue, void *_ClientData, TwBar *_Bar, CTwVarGroup *varGrp) { if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) return; assert( g_TwMgr->m_Graph->IsDrawing() ); CQuaternionExt *ext = static_cast<CQuaternionExt *>(_ExtValue); assert( ext!=NULL ); (void)_ClientData; (void)_Bar; // show/hide quat values assert( varGrp->m_Vars.size()==16 ); bool visible = ext->m_ShowVal; if( ext->m_IsDir ) { if( varGrp->m_Vars[13]->m_Visible != visible || varGrp->m_Vars[14]->m_Visible != visible || varGrp->m_Vars[15]->m_Visible != visible ) { varGrp->m_Vars[13]->m_Visible = visible; varGrp->m_Vars[14]->m_Visible = visible; varGrp->m_Vars[15]->m_Visible = visible; _Bar->NotUpToDate(); } } else { if( varGrp->m_Vars[4]->m_Visible != visible || varGrp->m_Vars[5]->m_Visible != visible || varGrp->m_Vars[6]->m_Visible != visible || varGrp->m_Vars[7]->m_Visible != visible ) { varGrp->m_Vars[4]->m_Visible = visible; varGrp->m_Vars[5]->m_Visible = visible; varGrp->m_Vars[6]->m_Visible = visible; varGrp->m_Vars[7]->m_Visible = visible; _Bar->NotUpToDate(); } } // force ext update static_cast<CTwVarAtom *>(varGrp->m_Vars[4])->ValueToDouble(); assert( s_SphTri.size()>0 ); assert( s_SphTri.size()==3*s_SphCol.size() ); assert( s_SphTriProj.size()==2*s_SphCol.size() ); assert( s_SphColLight.size()==s_SphCol.size() ); if( QuatD(w, h)<=2 ) return; float x, y, z, nx, ny, nz, kx, ky, kz, qx, qy, qz, qs; int i, j, k, l, m; // normalize quaternion float qn = (float)sqrt(ext->Qs*ext->Qs+ext->Qx*ext->Qx+ext->Qy*ext->Qy+ext->Qz*ext->Qz); if( qn>FLOAT_EPS ) { qx = (float)ext->Qx/qn; qy = (float)ext->Qy/qn; qz = (float)ext->Qz/qn; qs = (float)ext->Qs/qn; } else { qx = qy = qz = 0; qs = 1; } double normDir = sqrt(ext->m_Dir[0]*ext->m_Dir[0] + ext->m_Dir[1]*ext->m_Dir[1] + ext->m_Dir[2]*ext->m_Dir[2]); bool drawDir = ext->m_IsDir || (normDir>DOUBLE_EPS); color32 alpha = ext->m_Highlighted ? 0xffffffff : 0xb0ffffff; // check if frame is right-handed ext->Permute(&kx, &ky, &kz, 1, 0, 0); double px[3] = { (double)kx, (double)ky, (double)kz }; ext->Permute(&kx, &ky, &kz, 0, 1, 0); double py[3] = { (double)kx, (double)ky, (double)kz }; ext->Permute(&kx, &ky, &kz, 0, 0, 1); double pz[3] = { (double)kx, (double)ky, (double)kz }; double ez[3]; Vec3Cross(ez, px, py); bool frameRightHanded = (ez[0]*pz[0]+ez[1]*pz[1]+ez[2]*pz[2] >= 0); ITwGraph::Cull cull = frameRightHanded ? ITwGraph::CULL_CW : ITwGraph::CULL_CCW; if( drawDir ) { float dir[] = {(float)ext->m_Dir[0], (float)ext->m_Dir[1], (float)ext->m_Dir[2]}; if( normDir<DOUBLE_EPS ) { normDir = 1; dir[0] = 1; } kx = dir[0]; ky = dir[1]; kz = dir[2]; double rotDirAxis[3] = { 0, -kz, ky }; if( rotDirAxis[0]*rotDirAxis[0] + rotDirAxis[1]*rotDirAxis[1] + rotDirAxis[2]*rotDirAxis[2]<DOUBLE_EPS_SQ ) { rotDirAxis[0] = rotDirAxis[1] = 0; rotDirAxis[2] = 1; } double rotDirAngle = acos(kx/normDir); double rotDirQuat[4]; QuatFromAxisAngle(rotDirQuat, rotDirAxis, rotDirAngle); kx = 1; ky = 0; kz = 0; ApplyQuat(&kx, &ky, &kz, kx, ky, kz, (float)rotDirQuat[0], (float)rotDirQuat[1], (float)rotDirQuat[2], (float)rotDirQuat[3]); ApplyQuat(&kx, &ky, &kz, kx, ky, kz, qx, qy, qz, qs); for(k=0; k<4; ++k) // 4 parts of the arrow { // draw order ext->Permute(&x, &y, &z, kx, ky, kz); j = (z>0) ? 3-k : k; assert( s_ArrowTriProj[j].size()==2*(s_ArrowTri[j].size()/3) && s_ArrowColLight[j].size()==s_ArrowTri[j].size()/3 && s_ArrowNorm[j].size()==s_ArrowTri[j].size() ); const int ntri = (int)s_ArrowTri[j].size()/3; const float *tri = &(s_ArrowTri[j][0]); const float *norm = &(s_ArrowNorm[j][0]); int *triProj = &(s_ArrowTriProj[j][0]); color32 *colLight = &(s_ArrowColLight[j][0]); for(i=0; i<ntri; ++i) { x = tri[3*i+0]; y = tri[3*i+1]; z = tri[3*i+2]; nx = norm[3*i+0]; ny = norm[3*i+1]; nz = norm[3*i+2]; if( x>0 ) x = 2.5f*x - 2.0f; else x += 0.2f; y *= 1.5f; z *= 1.5f; ApplyQuat(&x, &y, &z, x, y, z, (float)rotDirQuat[0], (float)rotDirQuat[1], (float)rotDirQuat[2], (float)rotDirQuat[3]); ApplyQuat(&x, &y, &z, x, y, z, qx, qy, qz, qs); ext->Permute(&x, &y, &z, x, y, z); ApplyQuat(&nx, &ny, &nz, nx, ny, nz, (float)rotDirQuat[0], (float)rotDirQuat[1], (float)rotDirQuat[2], (float)rotDirQuat[3]); ApplyQuat(&nx, &ny, &nz, nx, ny, nz, qx, qy, qz, qs); ext->Permute(&nx, &ny, &nz, nx, ny, nz); triProj[2*i+0] = QuatPX(x, w, h); triProj[2*i+1] = QuatPY(y, w, h); color32 col = (ext->m_DirColor|0xff000000) & alpha; colLight[i] = ColorBlend(0xff000000, col, fabsf(TClamp(nz, -1.0f, 1.0f))); } if( s_ArrowTri[j].size()>=9 ) // 1 tri = 9 floats g_TwMgr->m_Graph->DrawTriangles((int)s_ArrowTri[j].size()/9, triProj, colLight, cull); } } else { /* int px0 = QuatPX(0, w, h)-1, py0 = QuatPY(0, w, h), r0 = (int)(0.5f*QuatD(w, h)-0.5f); color32 col0 = 0x80000000; DrawArc(px0-1, py0, r0, 0, 360, col0); DrawArc(px0+1, py0, r0, 0, 360, col0); DrawArc(px0, py0-1, r0, 0, 360, col0); DrawArc(px0, py0+1, r0, 0, 360, col0); */ // draw arrows & sphere const float SPH_RADIUS = 0.75f; for(m=0; m<2; ++m) // m=0: back, m=1: front { for(l=0; l<3; ++l) // draw 3 arrows { kx = 1; ky = 0; kz = 0; if( l==1 ) Vec3RotZ(&kx, &ky, &kz); else if( l==2 ) Vec3RotY(&kx, &ky, &kz); ApplyQuat(&kx, &ky, &kz, kx, ky, kz, qx, qy, qz, qs); for(k=0; k<4; ++k) // 4 parts of the arrow { // draw order ext->Permute(&x, &y, &z, kx, ky, kz); j = (z>0) ? 3-k : k; bool cone = true; if( (m==0 && z>0) || (m==1 && z<=0) ) { if( j==ARROW_CONE || j==ARROW_CONE_CAP ) // do not draw cone continue; else cone = false; } assert( s_ArrowTriProj[j].size()==2*(s_ArrowTri[j].size()/3) && s_ArrowColLight[j].size()==s_ArrowTri[j].size()/3 && s_ArrowNorm[j].size()==s_ArrowTri[j].size() ); const int ntri = (int)s_ArrowTri[j].size()/3; const float *tri = &(s_ArrowTri[j][0]); const float *norm = &(s_ArrowNorm[j][0]); int *triProj = &(s_ArrowTriProj[j][0]); color32 *colLight = &(s_ArrowColLight[j][0]); for(i=0; i<ntri; ++i) { x = tri[3*i+0]; y = tri[3*i+1]; z = tri[3*i+2]; if( cone && x<=0 ) x = SPH_RADIUS; else if( !cone && x>0 ) x = -SPH_RADIUS; nx = norm[3*i+0]; ny = norm[3*i+1]; nz = norm[3*i+2]; if( l==1 ) { Vec3RotZ(&x, &y, &z); Vec3RotZ(&nx, &ny, &nz); } else if( l==2 ) { Vec3RotY(&x, &y, &z); Vec3RotY(&nx, &ny, &nz); } ApplyQuat(&x, &y, &z, x, y, z, qx, qy, qz, qs); ext->Permute(&x, &y, &z, x, y, z); ApplyQuat(&nx, &ny, &nz, nx, ny, nz, qx, qy, qz, qs); ext->Permute(&nx, &ny, &nz, nx, ny, nz); triProj[2*i+0] = QuatPX(x, w, h); triProj[2*i+1] = QuatPY(y, w, h); float fade = ( m==0 && z<0 ) ? TClamp(2.0f*z*z, 0.0f, 1.0f) : 0; float alphaFade = 1.0f; Color32ToARGBf(alpha, &alphaFade, NULL, NULL, NULL); alphaFade *= (1.0f-fade); color32 alphaFadeCol = Color32FromARGBf(alphaFade, 1, 1, 1); color32 col = (l==0) ? 0xffff0000 : ( (l==1) ? 0xff00ff00 : 0xff0000ff ); colLight[i] = ColorBlend(0xff000000, col, fabsf(TClamp(nz, -1.0f, 1.0f))) & alphaFadeCol; } if( s_ArrowTri[j].size()>=9 ) // 1 tri = 9 floats g_TwMgr->m_Graph->DrawTriangles((int)s_ArrowTri[j].size()/9, triProj, colLight, cull); } } if( m==0 ) { const float *tri = &(s_SphTri[0]); int *triProj = &(s_SphTriProj[0]); const color32 *col = &(s_SphCol[0]); color32 *colLight = &(s_SphColLight[0]); const int ntri = (int)s_SphTri.size()/3; for(i=0; i<ntri; ++i) // draw sphere { x = SPH_RADIUS*tri[3*i+0]; y = SPH_RADIUS*tri[3*i+1]; z = SPH_RADIUS*tri[3*i+2]; ApplyQuat(&x, &y, &z, x, y, z, qx, qy, qz, qs); ext->Permute(&x, &y, &z, x, y, z); triProj[2*i+0] = QuatPX(x, w, h); triProj[2*i+1] = QuatPY(y, w, h); colLight[i] = ColorBlend(0xff000000, col[i], fabsf(TClamp(z/SPH_RADIUS, -1.0f, 1.0f))) & alpha; } g_TwMgr->m_Graph->DrawTriangles((int)s_SphTri.size()/9, triProj, colLight, cull); } } // draw x g_TwMgr->m_Graph->DrawLine(w-12, h-36, w-12+5, h-36+5, 0xffc00000, true); g_TwMgr->m_Graph->DrawLine(w-12+5, h-36, w-12, h-36+5, 0xffc00000, true); // draw y g_TwMgr->m_Graph->DrawLine(w-12, h-25, w-12+3, h-25+4, 0xff00c000, true); g_TwMgr->m_Graph->DrawLine(w-12+5, h-25, w-12, h-25+7, 0xff00c000, true); // draw z g_TwMgr->m_Graph->DrawLine(w-12, h-12, w-12+5, h-12, 0xff0000c0, true); g_TwMgr->m_Graph->DrawLine(w-12, h-12+5, w-12+5, h-12+5, 0xff0000c0, true); g_TwMgr->m_Graph->DrawLine(w-12, h-12+5, w-12+5, h-12, 0xff0000c0, true); } // draw borders g_TwMgr->m_Graph->DrawLine(1, 0, w-1, 0, 0x40000000); g_TwMgr->m_Graph->DrawLine(w-1, 0, w-1, h-1, 0x40000000); g_TwMgr->m_Graph->DrawLine(w-1, h-1, 1, h-1, 0x40000000); g_TwMgr->m_Graph->DrawLine(1, h-1, 1, 0, 0x40000000); } bool CQuaternionExt::MouseMotionCB(int mouseX, int mouseY, int w, int h, void *structExtValue, void *clientData, TwBar *bar, CTwVarGroup *varGrp) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(structExtValue); if( ext==NULL ) return false; (void)clientData, (void)varGrp; if( mouseX>0 && mouseX<w && mouseY>0 && mouseY<h ) ext->m_Highlighted = true; if( ext->m_Rotating ) { double x = QuatIX(mouseX, w, h); double y = QuatIY(mouseY, w, h); double z = 1; double px, py, pz, ox, oy, oz; ext->PermuteInv(&px, &py, &pz, x, y, z); ext->PermuteInv(&ox, &oy, &oz, ext->m_OrigX, ext->m_OrigY, 1); double n0 = sqrt(ox*ox + oy*oy + oz*oz); double n1 = sqrt(px*px + py*py + pz*pz); if( n0>DOUBLE_EPS && n1>DOUBLE_EPS ) { double v0[] = { ox/n0, oy/n0, oz/n0 }; double v1[] = { px/n1, py/n1, pz/n1 }; double axis[3]; Vec3Cross(axis, v0, v1); double sa = sqrt(Vec3Dot(axis, axis)); double ca = Vec3Dot(v0, v1); double angle = atan2(sa, ca); if( x*x+y*y>1.0 ) angle *= 1.0 + 0.2f*(sqrt(x*x+y*y)-1.0); double qrot[4], qres[4], qorig[4]; QuatFromAxisAngle(qrot, axis, angle); double nqorig = sqrt(ext->m_OrigQuat[0]*ext->m_OrigQuat[0]+ext->m_OrigQuat[1]*ext->m_OrigQuat[1]+ext->m_OrigQuat[2]*ext->m_OrigQuat[2]+ext->m_OrigQuat[3]*ext->m_OrigQuat[3]); if( fabs(nqorig)>DOUBLE_EPS_SQ ) { qorig[0] = ext->m_OrigQuat[0]/nqorig; qorig[1] = ext->m_OrigQuat[1]/nqorig; qorig[2] = ext->m_OrigQuat[2]/nqorig; qorig[3] = ext->m_OrigQuat[3]/nqorig; QuatMult(qres, qrot, qorig); ext->Qx = qres[0]; ext->Qy = qres[1]; ext->Qz = qres[2]; ext->Qs = qres[3]; } else { ext->Qx = qrot[0]; ext->Qy = qrot[1]; ext->Qz = qrot[2]; ext->Qs = qrot[3]; } ext->CopyToVar(); if( bar!=NULL ) bar->NotUpToDate(); ext->m_PrevX = x; ext->m_PrevY = y; } } return true; } bool CQuaternionExt::MouseButtonCB(TwMouseButtonID button, bool pressed, int mouseX, int mouseY, int w, int h, void *structExtValue, void *clientData, TwBar *bar, CTwVarGroup *varGrp) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(structExtValue); if( ext==NULL ) return false; (void)clientData; (void)bar, (void)varGrp; if( button==TW_MOUSE_LEFT ) { if( pressed ) { ext->m_OrigQuat[0] = ext->Qx; ext->m_OrigQuat[1] = ext->Qy; ext->m_OrigQuat[2] = ext->Qz; ext->m_OrigQuat[3] = ext->Qs; ext->m_OrigX = QuatIX(mouseX, w, h); ext->m_OrigY = QuatIY(mouseY, w, h); ext->m_PrevX = ext->m_OrigX; ext->m_PrevY = ext->m_OrigY; ext->m_Rotating = true; } else ext->m_Rotating = false; } //printf("Click %x\n", structExtValue); return true; } void CQuaternionExt::MouseLeaveCB(void *structExtValue, void *clientData, TwBar *bar) { CQuaternionExt *ext = static_cast<CQuaternionExt *>(structExtValue); if( ext==NULL ) return; (void)clientData; (void)bar; //printf("Leave %x\n", structExtValue); ext->m_Highlighted = false; ext->m_Rotating = false; } // --------------------------------------------------------------------------- // Convertion between VC++ Debug/Release std::string // (Needed because VC++ adds some extra info to std::string in Debug mode!) // And resolve binary std::string incompatibility between VS2010 and other VS versions // --------------------------------------------------------------------------- #ifdef _MSC_VER // VS2010 store the string allocator pointer at the end // VS2008 VS2012 and others store the string allocator pointer at the beginning static void FixVS2010StdStringLibToClient(void *strPtr) { char *ptr = (char *)strPtr; const size_t SizeOfUndecoratedString = 16 + 2*sizeof(size_t) + sizeof(void *); // size of a VS std::string without extra debug iterator and info. assert(SizeOfUndecoratedString <= sizeof(std::string)); TwType LibStdStringBaseType = (TwType)(TW_TYPE_STDSTRING&0xffff0000); void **allocAddress2008 = (void **)(ptr + sizeof(std::string) - SizeOfUndecoratedString); void **allocAddress2010 = (void **)(ptr + sizeof(std::string) - sizeof(void *)); if (LibStdStringBaseType == TW_TYPE_STDSTRING_VS2008 && g_TwMgr->m_ClientStdStringBaseType == TW_TYPE_STDSTRING_VS2010) { void *allocator = *allocAddress2008; memmove(allocAddress2008, allocAddress2008 + 1, SizeOfUndecoratedString - sizeof(void *)); *allocAddress2010 = allocator; } else if (LibStdStringBaseType == TW_TYPE_STDSTRING_VS2010 && g_TwMgr->m_ClientStdStringBaseType == TW_TYPE_STDSTRING_VS2008) { void *allocator = *allocAddress2010; memmove(allocAddress2008 + 1, allocAddress2008, SizeOfUndecoratedString - sizeof(void *)); *allocAddress2008 = allocator; } } static void FixVS2010StdStringClientToLib(void *strPtr) { char *ptr = (char *)strPtr; const size_t SizeOfUndecoratedString = 16 + 2*sizeof(size_t) + sizeof(void *); // size of a VS std::string without extra debug iterator and info. assert(SizeOfUndecoratedString <= sizeof(std::string)); TwType LibStdStringBaseType = (TwType)(TW_TYPE_STDSTRING&0xffff0000); void **allocAddress2008 = (void **)(ptr + sizeof(std::string) - SizeOfUndecoratedString); void **allocAddress2010 = (void **)(ptr + sizeof(std::string) - sizeof(void *)); if (LibStdStringBaseType == TW_TYPE_STDSTRING_VS2008 && g_TwMgr->m_ClientStdStringBaseType == TW_TYPE_STDSTRING_VS2010) { void *allocator = *allocAddress2010; memmove(allocAddress2008 + 1, allocAddress2008, SizeOfUndecoratedString - sizeof(void *)); *allocAddress2008 = allocator; } else if (LibStdStringBaseType == TW_TYPE_STDSTRING_VS2010 && g_TwMgr->m_ClientStdStringBaseType == TW_TYPE_STDSTRING_VS2008) { void *allocator = *allocAddress2008; memmove(allocAddress2008, allocAddress2008 + 1, SizeOfUndecoratedString - sizeof(void *)); *allocAddress2010 = allocator; } } #endif // _MSC_VER CTwMgr::CClientStdString::CClientStdString() { memset(m_Data, 0, sizeof(m_Data)); } void CTwMgr::CClientStdString::FromLib(const char *libStr) { m_LibStr = libStr; // it is ok to have a local copy here memcpy(m_Data + sizeof(void *), &m_LibStr, sizeof(std::string)); #ifdef _MSC_VER FixVS2010StdStringLibToClient(m_Data + sizeof(void *)); #endif } std::string& CTwMgr::CClientStdString::ToClient() { assert( g_TwMgr!=NULL ); if( g_TwMgr->m_ClientStdStringStructSize==sizeof(std::string)+sizeof(void *) ) return *(std::string *)(m_Data); else if( g_TwMgr->m_ClientStdStringStructSize+sizeof(void *)==sizeof(std::string) ) return *(std::string *)(m_Data + 2*sizeof(void *)); else { assert( g_TwMgr->m_ClientStdStringStructSize==sizeof(std::string) ); return *(std::string *)(m_Data + sizeof(void *)); } } CTwMgr::CLibStdString::CLibStdString() { memset(m_Data, 0, sizeof(m_Data)); } void CTwMgr::CLibStdString::FromClient(const std::string& clientStr) { assert( g_TwMgr!=NULL ); memcpy(m_Data + sizeof(void *), &clientStr, g_TwMgr->m_ClientStdStringStructSize); #ifdef _MSC_VER FixVS2010StdStringClientToLib(m_Data + sizeof(void *)); #endif } std::string& CTwMgr::CLibStdString::ToLib() { assert( g_TwMgr!=NULL ); if( g_TwMgr->m_ClientStdStringStructSize==sizeof(std::string)+sizeof(void *) ) return *(std::string *)(m_Data + 2*sizeof(void *)); else if( g_TwMgr->m_ClientStdStringStructSize+sizeof(void *)==sizeof(std::string) ) return *(std::string *)(m_Data); else { assert( g_TwMgr->m_ClientStdStringStructSize==sizeof(std::string) ); return *(std::string *)(m_Data + sizeof(void *)); } } // --------------------------------------------------------------------------- // Management functions // --------------------------------------------------------------------------- static int TwCreateGraph(ETwGraphAPI _GraphAPI) { assert( g_TwMgr!=NULL && g_TwMgr->m_Graph==NULL ); switch( _GraphAPI ) { case TW_OPENGL: g_TwMgr->m_Graph = new CTwGraphOpenGL; break; case TW_OPENGL_CORE: g_TwMgr->m_Graph = new CTwGraphOpenGLCore; break; case TW_DIRECT3D9: #if defined(ANT_WINDOWS) && !defined(TW_NO_DIRECT3D) if( g_TwMgr->m_Device!=NULL ) g_TwMgr->m_Graph = new CTwGraphDirect3D9; else { g_TwMgr->SetLastError(g_ErrBadDevice); return 0; } #endif // ANT_WINDOWS break; case TW_DIRECT3D10: #if defined(ANT_WINDOWS) && !defined(TW_NO_DIRECT3D) if( g_TwMgr->m_Device!=NULL ) g_TwMgr->m_Graph = new CTwGraphDirect3D10; else { g_TwMgr->SetLastError(g_ErrBadDevice); return 0; } #endif // ANT_WINDOWS break; case TW_DIRECT3D11: #if defined(ANT_WINDOWS) && !defined(TW_NO_DIRECT3D) if( g_TwMgr->m_Device!=NULL ) g_TwMgr->m_Graph = new CTwGraphDirect3D11; else { g_TwMgr->SetLastError(g_ErrBadDevice); return 0; } #endif // ANT_WINDOWS break; } if( g_TwMgr->m_Graph==NULL ) { g_TwMgr->SetLastError(g_ErrUnknownAPI); return 0; } else return g_TwMgr->m_Graph->Init(); } // --------------------------------------------------------------------------- static inline int TwFreeAsyncDrawing() { if( g_TwMgr && g_TwMgr->m_Graph && g_TwMgr->m_Graph->IsDrawing() ) { const double SLEEP_MAX = 0.25; // wait at most 1/4 second PerfTimer timer; while( g_TwMgr->m_Graph->IsDrawing() && timer.GetTime()<SLEEP_MAX ) { #if defined(ANT_WINDOWS) Sleep(1); // milliseconds #elif defined(ANT_UNIX) || defined(ANT_OSX) usleep(1000); // microseconds #endif } if( g_TwMgr->m_Graph->IsDrawing() ) { g_TwMgr->SetLastError(g_ErrIsDrawing); return 0; } } return 1; } // --------------------------------------------------------------------------- /* static inline int TwFreeAsyncProcessing() { if( g_TwMgr && g_TwMgr->IsProcessing() ) { const double SLEEP_MAX = 0.25; // wait at most 1/4 second PerfTimer timer; while( g_TwMgr->IsProcessing() && timer.GetTime()<SLEEP_MAX ) { #if defined(ANT_WINDOWS) Sleep(1); // milliseconds #elif defined(ANT_UNIX) usleep(1000); // microseconds #endif } if( g_TwMgr->IsProcessing() ) { g_TwMgr->SetLastError(g_ErrIsProcessing); return 0; } } return 1; } static inline int TwBeginProcessing() { if( !TwFreeAsyncProcessing() ) return 0; if( g_TwMgr ) g_TwMgr->SetProcessing(true); } static inline int TwEndProcessing() { if( g_TwMgr ) g_TwMgr->SetProcessing(false); } */ // --------------------------------------------------------------------------- static int TwInitMgr() { assert( g_TwMasterMgr!=NULL ); assert( g_TwMgr!=NULL ); g_TwMgr->m_CurrentFont = g_DefaultNormalFont; g_TwMgr->m_Graph = g_TwMasterMgr->m_Graph; g_TwMgr->m_KeyPressedTextObj = g_TwMgr->m_Graph->NewTextObj(); g_TwMgr->m_InfoTextObj = g_TwMgr->m_Graph->NewTextObj(); g_TwMgr->m_HelpBar = TwNewBar("TW_HELP"); if( g_TwMgr->m_HelpBar ) { g_TwMgr->m_HelpBar->m_Label = "~ Help & Shortcuts ~"; g_TwMgr->m_HelpBar->m_PosX = 32; g_TwMgr->m_HelpBar->m_PosY = 32; g_TwMgr->m_HelpBar->m_Width = 400; g_TwMgr->m_HelpBar->m_Height = 200; g_TwMgr->m_HelpBar->m_ValuesWidth = 12*(g_TwMgr->m_HelpBar->m_Font->m_CharHeight/2); g_TwMgr->m_HelpBar->m_Color = 0xa05f5f5f; //0xd75f5f5f; g_TwMgr->m_HelpBar->m_DarkText = false; g_TwMgr->m_HelpBar->m_IsHelpBar = true; g_TwMgr->Minimize(g_TwMgr->m_HelpBar); } else return 0; CColorExt::CreateTypes(); CQuaternionExt::CreateTypes(); return 1; } int ANT_CALL TwInit(ETwGraphAPI _GraphAPI, void *_Device) { #if defined(_DEBUG) && defined(ANT_WINDOWS) _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF|_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF)); #endif if( g_TwMasterMgr!=NULL ) { g_TwMasterMgr->SetLastError(g_ErrInit); return 0; } assert( g_TwMgr==0 ); assert( g_Wnds.empty() ); g_TwMasterMgr = new CTwMgr(_GraphAPI, _Device, TW_MASTER_WINDOW_ID); g_Wnds[TW_MASTER_WINDOW_ID] = g_TwMasterMgr; g_TwMgr = g_TwMasterMgr; TwGenerateDefaultFonts(g_FontScaling); g_TwMgr->m_CurrentFont = g_DefaultNormalFont; int Res = TwCreateGraph(_GraphAPI); if( Res ) Res = TwInitMgr(); if( !Res ) TwTerminate(); return Res; } // --------------------------------------------------------------------------- int ANT_CALL TwSetLastError(const char *_StaticErrorMessage) { if( g_TwMasterMgr!=0 ) { g_TwMasterMgr->SetLastError(_StaticErrorMessage); return 1; } else return 0; } // --------------------------------------------------------------------------- int ANT_CALL TwTerminate() { if( g_TwMgr==NULL ) { //TwGlobalError(g_ErrShut); -> not an error return 0; // already shutdown } // For multi-thread safety if( !TwFreeAsyncDrawing() ) return 0; CTwWndMap::iterator it; for( it=g_Wnds.begin(); it!=g_Wnds.end(); it++ ) { g_TwMgr = it->second; g_TwMgr->m_Terminating = true; TwDeleteAllBars(); if( g_TwMgr->m_CursorsCreated ) g_TwMgr->FreeCursors(); if( g_TwMgr->m_Graph ) { if( g_TwMgr->m_KeyPressedTextObj ) { g_TwMgr->m_Graph->DeleteTextObj(g_TwMgr->m_KeyPressedTextObj); g_TwMgr->m_KeyPressedTextObj = NULL; } if( g_TwMgr->m_InfoTextObj ) { g_TwMgr->m_Graph->DeleteTextObj(g_TwMgr->m_InfoTextObj); g_TwMgr->m_InfoTextObj = NULL; } if (g_TwMgr != g_TwMasterMgr) g_TwMgr->m_Graph = NULL; } if (g_TwMgr != g_TwMasterMgr) { delete g_TwMgr; g_TwMgr = NULL; } } // delete g_TwMasterMgr int Res = 1; g_TwMgr = g_TwMasterMgr; if( g_TwMasterMgr->m_Graph ) { Res = g_TwMasterMgr->m_Graph->Shut(); delete g_TwMasterMgr->m_Graph; g_TwMasterMgr->m_Graph = NULL; } TwDeleteDefaultFonts(); delete g_TwMasterMgr; g_TwMasterMgr = NULL; g_TwMgr = NULL; g_Wnds.clear(); return Res; } // --------------------------------------------------------------------------- int ANT_CALL TwGetCurrentWindow() { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } return g_TwMgr->m_WndID; } int ANT_CALL TwSetCurrentWindow(int wndID) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if (wndID != g_TwMgr->m_WndID) { CTwWndMap::iterator foundWnd = g_Wnds.find(wndID); if (foundWnd == g_Wnds.end()) { // create a new CTwMgr g_TwMgr = new CTwMgr(g_TwMasterMgr->m_GraphAPI, g_TwMasterMgr->m_Device, wndID); g_Wnds[wndID] = g_TwMgr; return TwInitMgr(); } else { g_TwMgr = foundWnd->second; return 1; } } else return 1; } int ANT_CALL TwWindowExists(int wndID) { CTwWndMap::iterator foundWnd = g_Wnds.find(wndID); if (foundWnd == g_Wnds.end()) return 0; else return 1; } // --------------------------------------------------------------------------- int ANT_CALL TwDraw() { PERF( PerfTimer Timer; double DT; ) //CTwFPU fpu; // fpu precision only forced in update (do not modif dx draw calls) if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } assert(g_TwMgr->m_Bars.size()==g_TwMgr->m_Order.size()); // For multi-thread savety if( !TwFreeAsyncDrawing() ) return 0; // Create cursors #if defined(ANT_WINDOWS) || defined(ANT_OSX) if( !g_TwMgr->m_CursorsCreated ) g_TwMgr->CreateCursors(); #elif defined(ANT_UNIX) if( !g_TwMgr->m_CurrentXDisplay ) g_TwMgr->m_CurrentXDisplay = glXGetCurrentDisplay(); if( !g_TwMgr->m_CurrentXWindow ) g_TwMgr->m_CurrentXWindow = glXGetCurrentDrawable(); if( g_TwMgr->m_CurrentXDisplay && !g_TwMgr->m_CursorsCreated ) g_TwMgr->CreateCursors(); #endif // Autorepeat TW_MOUSE_PRESSED double CurrTime = g_TwMgr->m_Timer.GetTime(); double RepeatDT = CurrTime - g_TwMgr->m_LastMousePressedTime; double DrawDT = CurrTime - g_TwMgr->m_LastDrawTime; if( RepeatDT>2.0*g_TwMgr->m_RepeatMousePressedDelay || DrawDT>2.0*g_TwMgr->m_RepeatMousePressedDelay || abs(g_TwMgr->m_LastMousePressedPosition[0]-g_TwMgr->m_LastMouseX)>4 || abs(g_TwMgr->m_LastMousePressedPosition[1]-g_TwMgr->m_LastMouseY)>4 ) { g_TwMgr->m_CanRepeatMousePressed = false; g_TwMgr->m_IsRepeatingMousePressed = false; } if( g_TwMgr->m_CanRepeatMousePressed ) { if( (!g_TwMgr->m_IsRepeatingMousePressed && RepeatDT>g_TwMgr->m_RepeatMousePressedDelay) || (g_TwMgr->m_IsRepeatingMousePressed && RepeatDT>g_TwMgr->m_RepeatMousePressedPeriod) ) { g_TwMgr->m_IsRepeatingMousePressed = true; g_TwMgr->m_LastMousePressedTime = g_TwMgr->m_Timer.GetTime(); TwMouseMotion(g_TwMgr->m_LastMouseX,g_TwMgr->m_LastMouseY); TwMouseButton(TW_MOUSE_PRESSED, g_TwMgr->m_LastMousePressedButtonID); } } g_TwMgr->m_LastDrawTime = CurrTime; if( g_TwMgr->m_WndWidth<0 || g_TwMgr->m_WndHeight<0 ) { g_TwMgr->SetLastError(g_ErrBadSize); return 0; } else if( g_TwMgr->m_WndWidth==0 || g_TwMgr->m_WndHeight==0 ) // probably iconified return 1; // nothing to do // count number of bars to draw size_t i, j; int Nb = 0; for( i=0; i<g_TwMgr->m_Bars.size(); ++i ) if( g_TwMgr->m_Bars[i]!=NULL && g_TwMgr->m_Bars[i]->m_Visible ) ++Nb; if( Nb>0 ) { PERF( Timer.Reset(); ) g_TwMgr->m_Graph->BeginDraw(g_TwMgr->m_WndWidth, g_TwMgr->m_WndHeight); PERF( DT = Timer.GetTime(); printf("\nBegin=%.4fms ", 1000.0*DT); ) PERF( Timer.Reset(); ) vector<CRect> TopBarsRects, ClippedBarRects; for( i=0; i<g_TwMgr->m_Bars.size(); ++i ) { CTwBar *Bar = g_TwMgr->m_Bars[ g_TwMgr->m_Order[i] ]; if( Bar->m_Visible ) { if( g_TwMgr->m_OverlapContent || Bar->IsMinimized() ) Bar->Draw(); else { // Clip overlapped transparent bars to make them more readable const int Margin = 4; CRect BarRect(Bar->m_PosX - Margin, Bar->m_PosY - Margin, Bar->m_Width + 2*Margin, Bar->m_Height + 2*Margin); TopBarsRects.clear(); for( j=i+1; j<g_TwMgr->m_Bars.size(); ++j ) { CTwBar *TopBar = g_TwMgr->m_Bars[g_TwMgr->m_Order[j]]; if( TopBar->m_Visible && !TopBar->IsMinimized() ) TopBarsRects.push_back(CRect(TopBar->m_PosX, TopBar->m_PosY, TopBar->m_Width, TopBar->m_Height)); } ClippedBarRects.clear(); BarRect.Subtract(TopBarsRects, ClippedBarRects); if( ClippedBarRects.size()==1 && ClippedBarRects[0]==BarRect ) //g_TwMgr->m_Graph->DrawRect(Bar->m_PosX, Bar->m_PosY, Bar->m_PosX+Bar->m_Width-1, Bar->m_PosY+Bar->m_Height-1, 0x70ffffff); // Clipping test Bar->Draw(); // unclipped else { Bar->Draw(CTwBar::DRAW_BG); // draw background only // draw content for each clipped rectangle for( j=0; j<ClippedBarRects.size(); j++ ) if (ClippedBarRects[j].W>1 && ClippedBarRects[j].H>1) { g_TwMgr->m_Graph->SetScissor(ClippedBarRects[j].X+1, ClippedBarRects[j].Y, ClippedBarRects[j].W, ClippedBarRects[j].H-1); //g_TwMgr->m_Graph->DrawRect(0, 0, 1000, 1000, 0x70ffffff); // Clipping test Bar->Draw(CTwBar::DRAW_CONTENT); } g_TwMgr->m_Graph->SetScissor(0, 0, 0, 0); } } } } PERF( DT = Timer.GetTime(); printf("Draw=%.4fms ", 1000.0*DT); ) PERF( Timer.Reset(); ) g_TwMgr->m_Graph->EndDraw(); PERF( DT = Timer.GetTime(); printf("End=%.4fms\n", 1000.0*DT); ) } return 1; } // --------------------------------------------------------------------------- int ANT_CALL TwWindowSize(int _Width, int _Height) { g_InitWndWidth = _Width; g_InitWndHeight = _Height; if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) { //TwGlobalError(g_ErrNotInit); -> not an error here return 0; // not initialized } if( _Width<0 || _Height<0 ) { g_TwMgr->SetLastError(g_ErrBadSize); return 0; } // For multi-thread savety if( !TwFreeAsyncDrawing() ) return 0; // Delete the extra text objects if( g_TwMgr->m_KeyPressedTextObj ) { g_TwMgr->m_Graph->DeleteTextObj(g_TwMgr->m_KeyPressedTextObj); g_TwMgr->m_KeyPressedTextObj = NULL; } if( g_TwMgr->m_InfoTextObj ) { g_TwMgr->m_Graph->DeleteTextObj(g_TwMgr->m_InfoTextObj); g_TwMgr->m_InfoTextObj = NULL; } g_TwMgr->m_WndWidth = _Width; g_TwMgr->m_WndHeight = _Height; g_TwMgr->m_Graph->Restore(); // Recreate extra text objects if( g_TwMgr->m_WndWidth!=0 && g_TwMgr->m_WndHeight!=0 ) { if( g_TwMgr->m_KeyPressedTextObj==NULL ) { g_TwMgr->m_KeyPressedTextObj = g_TwMgr->m_Graph->NewTextObj(); g_TwMgr->m_KeyPressedBuildText = true; } if( g_TwMgr->m_InfoTextObj==NULL ) { g_TwMgr->m_InfoTextObj = g_TwMgr->m_Graph->NewTextObj(); g_TwMgr->m_InfoBuildText = true; } } for( std::vector<TwBar*>::iterator it=g_TwMgr->m_Bars.begin(); it!=g_TwMgr->m_Bars.end(); ++it ) (*it)->NotUpToDate(); return 1; } // --------------------------------------------------------------------------- CTwMgr::CTwMgr(ETwGraphAPI _GraphAPI, void *_Device, int _WndID) { m_GraphAPI = _GraphAPI; m_Device = _Device; m_WndID = _WndID; m_LastError = NULL; m_CurrentDbgFile = ""; m_CurrentDbgLine = 0; //m_Processing = false; m_Graph = NULL; m_WndWidth = g_InitWndWidth; m_WndHeight = g_InitWndHeight; m_CurrentFont = NULL; // set after by TwIntialize m_NbMinimizedBars = 0; m_HelpBar = NULL; m_HelpBarNotUpToDate = true; m_HelpBarUpdateNow = false; m_LastHelpUpdateTime = 0; m_LastMouseX = -1; m_LastMouseY = -1; m_LastMouseWheelPos = 0; m_IconPos = 0; m_IconAlign = 0; m_IconMarginX = m_IconMarginY = 8; m_FontResizable = true; m_KeyPressedTextObj = NULL; m_KeyPressedBuildText = false; m_KeyPressedTime = 0; m_InfoTextObj = NULL; m_InfoBuildText = true; m_BarInitColorHue = 155; m_PopupBar = NULL; m_TypeColor32 = TW_TYPE_UNDEF; m_TypeColor3F = TW_TYPE_UNDEF; m_TypeColor4F = TW_TYPE_UNDEF; m_LastMousePressedTime = 0; m_LastMousePressedButtonID = TW_MOUSE_MIDDLE; m_LastMousePressedPosition[0] = -1000; m_LastMousePressedPosition[1] = -1000; m_RepeatMousePressedDelay = 0.5; m_RepeatMousePressedPeriod = 0.1; m_CanRepeatMousePressed = false; m_IsRepeatingMousePressed = false; m_LastDrawTime = 0; m_UseOldColorScheme = false; m_Contained = false; m_ButtonAlign = BUTTON_ALIGN_RIGHT; m_OverlapContent = false; m_Terminating = false; m_CursorsCreated = false; #if defined(ANT_UNIX) m_CurrentXDisplay = NULL; m_CurrentXWindow = 0; #endif // defined(ANT_UNIX) m_CopyCDStringToClient = g_InitCopyCDStringToClient; m_CopyStdStringToClient = g_InitCopyStdStringToClient; m_ClientStdStringStructSize = 0; m_ClientStdStringBaseType = (TwType)0; } // --------------------------------------------------------------------------- CTwMgr::~CTwMgr() { } // --------------------------------------------------------------------------- int CTwMgr::FindBar(const char *_Name) const { if( _Name==NULL || strlen(_Name)<=0 ) return -1; int i; for( i=0; i<(int)m_Bars.size(); ++i ) if( m_Bars[i]!=NULL && strcmp(_Name, m_Bars[i]->m_Name.c_str())==0 ) return i; return -1; } // --------------------------------------------------------------------------- int CTwMgr::HasAttrib(const char *_Attrib, bool *_HasValue) const { *_HasValue = true; if( _stricmp(_Attrib, "help")==0 ) return MGR_HELP; else if( _stricmp(_Attrib, "fontsize")==0 ) return MGR_FONT_SIZE; else if( _stricmp(_Attrib, "fontstyle")==0 ) return MGR_FONT_STYLE; else if( _stricmp(_Attrib, "iconpos")==0 ) return MGR_ICON_POS; else if( _stricmp(_Attrib, "iconalign")==0 ) return MGR_ICON_ALIGN; else if( _stricmp(_Attrib, "iconmargin")==0 ) return MGR_ICON_MARGIN; else if( _stricmp(_Attrib, "fontresizable")==0 ) return MGR_FONT_RESIZABLE; else if( _stricmp(_Attrib, "colorscheme")==0 ) return MGR_COLOR_SCHEME; else if( _stricmp(_Attrib, "contained")==0 ) return MGR_CONTAINED; else if( _stricmp(_Attrib, "buttonalign")==0 ) return MGR_BUTTON_ALIGN; else if( _stricmp(_Attrib, "overlap")==0 ) return MGR_OVERLAP; *_HasValue = false; return 0; // not found } int CTwMgr::SetAttrib(int _AttribID, const char *_Value) { switch( _AttribID ) { case MGR_HELP: if( _Value && strlen(_Value)>0 ) { m_Help = _Value; m_HelpBarNotUpToDate = true; return 1; } else { SetLastError(g_ErrNoValue); return 0; } case MGR_FONT_SIZE: if( _Value && strlen(_Value)>0 ) { int s; int n = sscanf(_Value, "%d", &s); if( n==1 && s>=1 && s<=3 ) { if( s==1 ) SetFont(g_DefaultSmallFont, true); else if( s==2 ) SetFont(g_DefaultNormalFont, true); else if( s==3 ) SetFont(g_DefaultLargeFont, true); return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { SetLastError(g_ErrNoValue); return 0; } case MGR_FONT_STYLE: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "fixed")==0 ) { if( m_CurrentFont!=g_DefaultFixed1Font ) { SetFont(g_DefaultFixed1Font, true); m_FontResizable = false; // for now fixed font is not resizable } return 1; } else if( _stricmp(_Value, "default")==0 ) { if( m_CurrentFont!=g_DefaultSmallFont && m_CurrentFont!=g_DefaultNormalFont && m_CurrentFont!=g_DefaultLargeFont ) { if( m_CurrentFont == g_DefaultFixed1Font ) m_FontResizable = true; SetFont(g_DefaultNormalFont, true); } return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { SetLastError(g_ErrNoValue); return 0; } case MGR_ICON_POS: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "bl")==0 || _stricmp(_Value, "lb")==0 || _stricmp(_Value, "bottomleft")==0 || _stricmp(_Value, "leftbottom")==0 ) { m_IconPos = 0; return 1; } else if( _stricmp(_Value, "br")==0 || _stricmp(_Value, "rb")==0 || _stricmp(_Value, "bottomright")==0 || _stricmp(_Value, "rightbottom")==0 ) { m_IconPos = 1; return 1; } else if( _stricmp(_Value, "tl")==0 || _stricmp(_Value, "lt")==0 || _stricmp(_Value, "topleft")==0 || _stricmp(_Value, "lefttop")==0 ) { m_IconPos = 2; return 1; } else if( _stricmp(_Value, "tr")==0 || _stricmp(_Value, "rt")==0 || _stricmp(_Value, "topright")==0 || _stricmp(_Value, "righttop")==0 ) { m_IconPos = 3; return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { SetLastError(g_ErrNoValue); return 0; } case MGR_ICON_ALIGN: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "vert")==0 || _stricmp(_Value, "vertical")==0 ) { m_IconAlign = 0; return 1; } else if( _stricmp(_Value, "horiz")==0 || _stricmp(_Value, "horizontal")==0 ) { m_IconAlign = 1; return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { SetLastError(g_ErrNoValue); return 0; } case MGR_ICON_MARGIN: if( _Value && strlen(_Value)>0 ) { int x, y; int n = sscanf(_Value, "%d%d", &x, &y); if( n==2 && x>=0 && y>=0 ) { m_IconMarginX = x; m_IconMarginY = y; return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { SetLastError(g_ErrNoValue); return 0; } case MGR_FONT_RESIZABLE: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "1")==0 || _stricmp(_Value, "true")==0 ) { m_FontResizable = true; return 1; } else if( _stricmp(_Value, "0")==0 || _stricmp(_Value, "false")==0 ) { m_FontResizable = false; return 1; } else { g_TwMgr->SetLastError(g_ErrBadValue); return 0; } } else { g_TwMgr->SetLastError(g_ErrNoValue); return 0; } case MGR_COLOR_SCHEME: if( _Value && strlen(_Value)>0 ) { int s; int n = sscanf(_Value, "%d", &s); if( n==1 && s>=0 && s<=1 ) { if( s==0 ) m_UseOldColorScheme = true; else m_UseOldColorScheme = false; return 1; } else { SetLastError(g_ErrBadValue); return 0; } } else { g_TwMgr->SetLastError(g_ErrNoValue); return 0; } case MGR_CONTAINED: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "1")==0 || _stricmp(_Value, "true")==0 ) m_Contained = true; else if( _stricmp(_Value, "0")==0 || _stricmp(_Value, "false")==0 ) m_Contained = false; else { g_TwMgr->SetLastError(g_ErrBadValue); return 0; } vector<TwBar*>::iterator barIt; for( barIt=g_TwMgr->m_Bars.begin(); barIt!=g_TwMgr->m_Bars.end(); ++barIt ) if( (*barIt)!=NULL ) (*barIt)->m_Contained = m_Contained; return 1; } else { g_TwMgr->SetLastError(g_ErrNoValue); return 0; } case MGR_BUTTON_ALIGN: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "left")==0 ) m_ButtonAlign = BUTTON_ALIGN_LEFT; else if( _stricmp(_Value, "center")==0 ) m_ButtonAlign = BUTTON_ALIGN_CENTER; else if( _stricmp(_Value, "right")==0 ) m_ButtonAlign = BUTTON_ALIGN_RIGHT; else { g_TwMgr->SetLastError(g_ErrBadValue); return 0; } vector<TwBar*>::iterator barIt; for( barIt=g_TwMgr->m_Bars.begin(); barIt!=g_TwMgr->m_Bars.end(); ++barIt ) if( (*barIt)!=NULL ) (*barIt)->m_ButtonAlign = m_ButtonAlign; return 1; } else { g_TwMgr->SetLastError(g_ErrNoValue); return 0; } case MGR_OVERLAP: if( _Value && strlen(_Value)>0 ) { if( _stricmp(_Value, "1")==0 || _stricmp(_Value, "true")==0 ) { m_OverlapContent = true; return 1; } else if( _stricmp(_Value, "0")==0 || _stricmp(_Value, "false")==0 ) { m_OverlapContent = false; return 1; } else { g_TwMgr->SetLastError(g_ErrBadValue); return 0; } } else { g_TwMgr->SetLastError(g_ErrNoValue); return 0; } default: g_TwMgr->SetLastError(g_ErrUnknownAttrib); return 0; } } ERetType CTwMgr::GetAttrib(int _AttribID, std::vector<double>& outDoubles, std::ostringstream& outString) const { outDoubles.clear(); outString.clear(); switch( _AttribID ) { case MGR_HELP: outString << m_Help; return RET_STRING; case MGR_FONT_SIZE: if( m_CurrentFont==g_DefaultSmallFont ) outDoubles.push_back(1); else if( m_CurrentFont==g_DefaultNormalFont ) outDoubles.push_back(2); else if( m_CurrentFont==g_DefaultLargeFont ) outDoubles.push_back(3); else outDoubles.push_back(0); // should not happened return RET_DOUBLE; case MGR_FONT_STYLE: if( m_CurrentFont==g_DefaultFixed1Font ) outString << "fixed"; else outString << "default"; return RET_STRING; case MGR_ICON_POS: if( m_IconPos==0 ) outString << "bottomleft"; else if( m_IconPos==1 ) outString << "bottomright"; else if( m_IconPos==2 ) outString << "topleft"; else if( m_IconPos==3 ) outString << "topright"; else outString << "undefined"; // should not happened return RET_STRING; case MGR_ICON_ALIGN: if( m_IconAlign==0 ) outString << "vertical"; else if( m_IconAlign==1 ) outString << "horizontal"; else outString << "undefined"; // should not happened return RET_STRING; case MGR_ICON_MARGIN: outDoubles.push_back(m_IconMarginX); outDoubles.push_back(m_IconMarginY); return RET_DOUBLE; case MGR_FONT_RESIZABLE: outDoubles.push_back(m_FontResizable); return RET_DOUBLE; case MGR_COLOR_SCHEME: outDoubles.push_back(m_UseOldColorScheme ? 0 : 1); return RET_DOUBLE; case MGR_CONTAINED: { bool contained = m_Contained; /* if( contained ) { vector<TwBar*>::iterator barIt; for( barIt=g_TwMgr->m_Bars.begin(); barIt!=g_TwMgr->m_Bars.end(); ++barIt ) if( (*barIt)!=NULL && !(*barIt)->m_Contained ) { contained = false; break; } } */ outDoubles.push_back(contained); return RET_DOUBLE; } case MGR_BUTTON_ALIGN: if( m_ButtonAlign==BUTTON_ALIGN_LEFT ) outString << "left"; else if( m_ButtonAlign==BUTTON_ALIGN_CENTER ) outString << "center"; else outString << "right"; return RET_STRING; case MGR_OVERLAP: outDoubles.push_back(m_OverlapContent); return RET_DOUBLE; default: g_TwMgr->SetLastError(g_ErrUnknownAttrib); return RET_ERROR; } } // --------------------------------------------------------------------------- void CTwMgr::Minimize(TwBar *_Bar) { assert(m_Graph!=NULL && _Bar!=NULL); assert(m_Bars.size()==m_MinOccupied.size()); if( _Bar->m_IsMinimized ) return; if( _Bar->m_Visible ) { size_t i = m_NbMinimizedBars; m_NbMinimizedBars++; for( i=0; i<m_MinOccupied.size(); ++i ) if( !m_MinOccupied[i] ) break; if( i<m_MinOccupied.size() ) m_MinOccupied[i] = true; _Bar->m_MinNumber = (int)i; } else _Bar->m_MinNumber = -1; _Bar->m_IsMinimized = true; _Bar->NotUpToDate(); } // --------------------------------------------------------------------------- void CTwMgr::Maximize(TwBar *_Bar) { assert(m_Graph!=NULL && _Bar!=NULL); assert(m_Bars.size()==m_MinOccupied.size()); if( !_Bar->m_IsMinimized ) return; if( _Bar->m_Visible ) { --m_NbMinimizedBars; if( m_NbMinimizedBars<0 ) m_NbMinimizedBars = 0; if( _Bar->m_MinNumber>=0 && _Bar->m_MinNumber<(int)m_MinOccupied.size() ) m_MinOccupied[_Bar->m_MinNumber] = false; } _Bar->m_IsMinimized = false; _Bar->NotUpToDate(); if( _Bar->m_IsHelpBar ) m_HelpBarNotUpToDate = true; } // --------------------------------------------------------------------------- void CTwMgr::Hide(TwBar *_Bar) { assert(m_Graph!=NULL && _Bar!=NULL); if( !_Bar->m_Visible ) return; if( _Bar->IsMinimized() ) { Maximize(_Bar); _Bar->m_Visible = false; Minimize(_Bar); } else _Bar->m_Visible = false; if( !_Bar->m_IsHelpBar ) m_HelpBarNotUpToDate = true; } // --------------------------------------------------------------------------- void CTwMgr::Unhide(TwBar *_Bar) { assert(m_Graph!=NULL && _Bar!=NULL); if( _Bar->m_Visible ) return; if( _Bar->IsMinimized() ) { Maximize(_Bar); _Bar->m_Visible = true; Minimize(_Bar); } else _Bar->m_Visible = true; _Bar->NotUpToDate(); if( !_Bar->m_IsHelpBar ) m_HelpBarNotUpToDate = true; } // --------------------------------------------------------------------------- void CTwMgr::SetFont(const CTexFont *_Font, bool _ResizeBars) { assert(m_Graph!=NULL); assert(_Font!=NULL); m_CurrentFont = _Font; for( int i=0; i<(int)m_Bars.size(); ++i ) if( m_Bars[i]!=NULL ) { int fh = m_Bars[i]->m_Font->m_CharHeight; m_Bars[i]->m_Font = _Font; if( _ResizeBars ) { if( m_Bars[i]->m_Movable ) { m_Bars[i]->m_PosX += (3*(fh-_Font->m_CharHeight))/2; m_Bars[i]->m_PosY += (fh-_Font->m_CharHeight)/2; } if( m_Bars[i]->m_Resizable ) { m_Bars[i]->m_Width = (m_Bars[i]->m_Width*_Font->m_CharHeight)/fh; m_Bars[i]->m_Height = (m_Bars[i]->m_Height*_Font->m_CharHeight)/fh; m_Bars[i]->m_ValuesWidth = (m_Bars[i]->m_ValuesWidth*_Font->m_CharHeight)/fh; } } m_Bars[i]->NotUpToDate(); } if( g_TwMgr->m_HelpBar!=NULL ) g_TwMgr->m_HelpBar->Update(); g_TwMgr->m_InfoBuildText = true; g_TwMgr->m_KeyPressedBuildText = true; m_HelpBarNotUpToDate = true; } // --------------------------------------------------------------------------- void ANT_CALL TwGlobalError(const char *_ErrorMessage) // to be called when g_TwMasterMgr is not created { if( g_ErrorHandler==NULL ) { fprintf(stderr, "ERROR(AntTweakBar) >> %s\n", _ErrorMessage); #ifdef ANT_WINDOWS OutputDebugString("ERROR(AntTweakBar) >> "); OutputDebugString(_ErrorMessage); OutputDebugString("\n"); #endif // ANT_WINDOWS } else g_ErrorHandler(_ErrorMessage); if( g_BreakOnError ) abort(); } // --------------------------------------------------------------------------- void CTwMgr::SetLastError(const char *_ErrorMessage) // _ErrorMessage must be a static string { if (this != g_TwMasterMgr) { // route to master g_TwMasterMgr->SetLastError(_ErrorMessage); return; } m_LastError = _ErrorMessage; if( g_ErrorHandler==NULL ) { if( m_CurrentDbgFile!=NULL && strlen(m_CurrentDbgFile)>0 && m_CurrentDbgLine>0 ) fprintf(stderr, "%s(%d): ", m_CurrentDbgFile, m_CurrentDbgLine); fprintf(stderr, "ERROR(AntTweakBar) >> %s\n", m_LastError); #ifdef ANT_WINDOWS if( m_CurrentDbgFile!=NULL && strlen(m_CurrentDbgFile)>0 && m_CurrentDbgLine>0 ) { OutputDebugString(m_CurrentDbgFile); char sl[32]; sprintf(sl, "(%d): ", m_CurrentDbgLine); OutputDebugString(sl); } OutputDebugString("ERROR(AntTweakBar) >> "); OutputDebugString(m_LastError); OutputDebugString("\n"); #endif // ANT_WINDOWS } else g_ErrorHandler(_ErrorMessage); if( g_BreakOnError ) abort(); } // --------------------------------------------------------------------------- const char *CTwMgr::GetLastError() { if (this != g_TwMasterMgr) { // route to master return g_TwMasterMgr->GetLastError(); } const char *Err = m_LastError; m_LastError = NULL; return Err; } // --------------------------------------------------------------------------- const char *CTwMgr::CheckLastError() const { return m_LastError; } // --------------------------------------------------------------------------- void CTwMgr::SetCurrentDbgParams(const char *dbgFile, int dbgLine) { m_CurrentDbgFile = dbgFile; m_CurrentDbgLine = dbgLine; } // --------------------------------------------------------------------------- int ANT_CALL __TwDbg(const char *dbgFile, int dbgLine) { if( g_TwMgr!=NULL ) g_TwMgr->SetCurrentDbgParams(dbgFile, dbgLine); return 0; // always returns zero } // --------------------------------------------------------------------------- void ANT_CALL TwHandleErrors(TwErrorHandler _ErrorHandler, int _BreakOnError) { g_ErrorHandler = _ErrorHandler; g_BreakOnError = (_BreakOnError) ? true : false; } void ANT_CALL TwHandleErrors(TwErrorHandler _ErrorHandler) { TwHandleErrors(_ErrorHandler, false); } // --------------------------------------------------------------------------- const char *ANT_CALL TwGetLastError() { if( g_TwMasterMgr==NULL ) { TwGlobalError(g_ErrNotInit); return g_ErrNotInit; } else return g_TwMasterMgr->GetLastError(); } // --------------------------------------------------------------------------- TwBar *ANT_CALL TwNewBar(const char *_Name) { if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } TwFreeAsyncDrawing(); // For multi-thread savety if( _Name==NULL || strlen(_Name)<=0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return NULL; } if( g_TwMgr->FindBar(_Name)>=0 ) { g_TwMgr->SetLastError(g_ErrExist); return NULL; } if( strstr(_Name, "`")!=NULL ) { g_TwMgr->SetLastError(g_ErrNoBackQuote); return NULL; } if( g_TwMgr->m_PopupBar!=NULL ) // delete popup bar if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } TwBar *Bar = new CTwBar(_Name); g_TwMgr->m_Bars.push_back(Bar); g_TwMgr->m_Order.push_back((int)g_TwMgr->m_Bars.size()-1); g_TwMgr->m_MinOccupied.push_back(false); g_TwMgr->m_HelpBarNotUpToDate = true; return Bar; } // --------------------------------------------------------------------------- int ANT_CALL TwDeleteBar(TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( _Bar==g_TwMgr->m_HelpBar ) { g_TwMgr->SetLastError(g_ErrDelHelp); return 0; } TwFreeAsyncDrawing(); // For multi-thread savety vector<TwBar*>::iterator BarIt; int i = 0; for( BarIt=g_TwMgr->m_Bars.begin(); BarIt!=g_TwMgr->m_Bars.end(); ++BarIt, ++i ) if( (*BarIt)==_Bar ) break; if( BarIt==g_TwMgr->m_Bars.end() ) { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } if( g_TwMgr->m_PopupBar!=NULL && _Bar!=g_TwMgr->m_PopupBar ) // delete popup bar first if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } // force bar to un-minimize g_TwMgr->Maximize(_Bar); // find an empty MinOccupied vector<bool>::iterator itm; int j = 0; for( itm=g_TwMgr->m_MinOccupied.begin(); itm!=g_TwMgr->m_MinOccupied.end(); ++itm, ++j) if( (*itm)==false ) break; assert( itm!=g_TwMgr->m_MinOccupied.end() ); // shift MinNumbers and erase the empty MinOccupied for( size_t k=0; k<g_TwMgr->m_Bars.size(); ++k ) if( g_TwMgr->m_Bars[k]!=NULL && g_TwMgr->m_Bars[k]->m_MinNumber>j ) g_TwMgr->m_Bars[k]->m_MinNumber -= 1; g_TwMgr->m_MinOccupied.erase(itm); // erase _Bar order vector<int>::iterator BarOrderIt = g_TwMgr->m_Order.end(); for(vector<int>::iterator it=g_TwMgr->m_Order.begin(); it!=g_TwMgr->m_Order.end(); ++it ) if( (*it)==i ) BarOrderIt = it; else if( (*it)>i ) (*it) -= 1; assert( BarOrderIt!=g_TwMgr->m_Order.end() ); g_TwMgr->m_Order.erase(BarOrderIt); // erase & delete _Bar g_TwMgr->m_Bars.erase(BarIt); delete _Bar; g_TwMgr->m_HelpBarNotUpToDate = true; return 1; } // --------------------------------------------------------------------------- int ANT_CALL TwDeleteAllBars() { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } TwFreeAsyncDrawing(); // For multi-thread savety int n = 0; if( g_TwMgr->m_Terminating || g_TwMgr->m_HelpBar==NULL ) { for( size_t i=0; i<g_TwMgr->m_Bars.size(); ++i ) if( g_TwMgr->m_Bars[i]!=NULL ) { ++n; delete g_TwMgr->m_Bars[i]; g_TwMgr->m_Bars[i] = NULL; } g_TwMgr->m_Bars.clear(); g_TwMgr->m_Order.clear(); g_TwMgr->m_MinOccupied.clear(); g_TwMgr->m_HelpBarNotUpToDate = true; } else { vector<CTwBar *> bars = g_TwMgr->m_Bars; for( size_t i = 0; i < bars.size(); ++i ) if( bars[i]!=0 && bars[i]!=g_TwMgr->m_HelpBar) { ++n; TwDeleteBar(bars[i]); } g_TwMgr->m_HelpBarNotUpToDate = true; } if( n==0 ) { //g_TwMgr->SetLastError(g_ErrNthToDo); return 0; } else return 1; } // --------------------------------------------------------------------------- int ANT_CALL TwSetTopBar(const TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } TwFreeAsyncDrawing(); // For multi-thread savety if( _Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_BarAlwaysOnBottom.length()>0 ) { if( strcmp(_Bar->m_Name.c_str(), g_TwMgr->m_BarAlwaysOnBottom.c_str())==0 ) return TwSetBottomBar(_Bar); } int i = -1, iOrder; for( iOrder=0; iOrder<(int)g_TwMgr->m_Bars.size(); ++iOrder ) { i = g_TwMgr->m_Order[iOrder]; assert( i>=0 && i<(int)g_TwMgr->m_Bars.size() ); if( g_TwMgr->m_Bars[i]==_Bar ) break; } if( i<0 || iOrder>=(int)g_TwMgr->m_Bars.size() ) // bar not found { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } for( int j=iOrder; j<(int)g_TwMgr->m_Bars.size()-1; ++j ) g_TwMgr->m_Order[j] = g_TwMgr->m_Order[j+1]; g_TwMgr->m_Order[(int)g_TwMgr->m_Bars.size()-1] = i; if( _Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_BarAlwaysOnTop.length()>0 ) { int topIdx = g_TwMgr->FindBar(g_TwMgr->m_BarAlwaysOnTop.c_str()); TwBar *top = (topIdx>=0 && topIdx<(int)g_TwMgr->m_Bars.size()) ? g_TwMgr->m_Bars[topIdx] : NULL; if( top!=NULL && top!=_Bar ) TwSetTopBar(top); } if( g_TwMgr->m_PopupBar!=NULL && _Bar!=g_TwMgr->m_PopupBar ) TwSetTopBar(g_TwMgr->m_PopupBar); return 1; } // --------------------------------------------------------------------------- TwBar * ANT_CALL TwGetTopBar() { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } if( g_TwMgr->m_Bars.size()>0 && g_TwMgr->m_PopupBar==NULL ) return g_TwMgr->m_Bars[g_TwMgr->m_Order[ g_TwMgr->m_Bars.size()-1 ]]; else if( g_TwMgr->m_Bars.size()>1 && g_TwMgr->m_PopupBar!=NULL ) return g_TwMgr->m_Bars[g_TwMgr->m_Order[ g_TwMgr->m_Bars.size()-2 ]]; else return NULL; } // --------------------------------------------------------------------------- int ANT_CALL TwSetBottomBar(const TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } TwFreeAsyncDrawing(); // For multi-thread savety if( _Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_BarAlwaysOnTop.length()>0 ) { if( strcmp(_Bar->m_Name.c_str(), g_TwMgr->m_BarAlwaysOnTop.c_str())==0 ) return TwSetTopBar(_Bar); } int i = -1, iOrder; for( iOrder=0; iOrder<(int)g_TwMgr->m_Bars.size(); ++iOrder ) { i = g_TwMgr->m_Order[iOrder]; assert( i>=0 && i<(int)g_TwMgr->m_Bars.size() ); if( g_TwMgr->m_Bars[i]==_Bar ) break; } if( i<0 || iOrder>=(int)g_TwMgr->m_Bars.size() ) // bar not found { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } if( iOrder>0 ) for( int j=iOrder-1; j>=0; --j ) g_TwMgr->m_Order[j+1] = g_TwMgr->m_Order[j]; g_TwMgr->m_Order[0] = i; if( _Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_BarAlwaysOnBottom.length()>0 ) { int btmIdx = g_TwMgr->FindBar(g_TwMgr->m_BarAlwaysOnBottom.c_str()); TwBar *btm = (btmIdx>=0 && btmIdx<(int)g_TwMgr->m_Bars.size()) ? g_TwMgr->m_Bars[btmIdx] : NULL; if( btm!=NULL && btm!=_Bar ) TwSetBottomBar(btm); } return 1; } // --------------------------------------------------------------------------- TwBar* ANT_CALL TwGetBottomBar() { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } if( g_TwMgr->m_Bars.size()>0 ) return g_TwMgr->m_Bars[g_TwMgr->m_Order[0]]; else return NULL; } // --------------------------------------------------------------------------- int ANT_CALL TwSetBarState(TwBar *_Bar, TwState _State) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } TwFreeAsyncDrawing(); // For multi-thread savety switch( _State ) { case TW_STATE_SHOWN: g_TwMgr->Unhide(_Bar); return 1; case TW_STATE_ICONIFIED: //g_TwMgr->Unhide(_Bar); g_TwMgr->Minimize(_Bar); return 1; case TW_STATE_HIDDEN: //g_TwMgr->Maximize(_Bar); g_TwMgr->Hide(_Bar); return 1; case TW_STATE_UNICONIFIED: //g_TwMgr->Unhide(_Bar); g_TwMgr->Maximize(_Bar); return 1; default: g_TwMgr->SetLastError(g_ErrBadParam); return 0; } } // --------------------------------------------------------------------------- /* TwState ANT_CALL TwGetBarState(const TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return TW_STATE_ERROR; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return TW_STATE_ERROR; } if( !_Bar->m_Visible ) return TW_STATE_HIDDEN; else if( _Bar->IsMinimized() ) return TW_STATE_ICONIFIED; else return TW_STATE_SHOWN; } */ // --------------------------------------------------------------------------- const char * ANT_CALL TwGetBarName(const TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return NULL; } vector<TwBar*>::iterator BarIt; int i = 0; for( BarIt=g_TwMgr->m_Bars.begin(); BarIt!=g_TwMgr->m_Bars.end(); ++BarIt, ++i ) if( (*BarIt)==_Bar ) break; if( BarIt==g_TwMgr->m_Bars.end() ) { g_TwMgr->SetLastError(g_ErrNotFound); return NULL; } return _Bar->m_Name.c_str(); } // --------------------------------------------------------------------------- int ANT_CALL TwGetBarCount() { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } return (int)g_TwMgr->m_Bars.size(); } // --------------------------------------------------------------------------- TwBar * ANT_CALL TwGetBarByIndex(int index) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } if( index>=0 && index<(int)g_TwMgr->m_Bars.size() ) return g_TwMgr->m_Bars[index]; else { g_TwMgr->SetLastError(g_ErrOutOfRange); return NULL; } } // --------------------------------------------------------------------------- TwBar * ANT_CALL TwGetBarByName(const char *name) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return NULL; // not initialized } int idx = g_TwMgr->FindBar(name); if ( idx>=0 && idx<(int)g_TwMgr->m_Bars.size() ) return g_TwMgr->m_Bars[idx]; else return NULL; } // --------------------------------------------------------------------------- int ANT_CALL TwRefreshBar(TwBar *bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( bar==NULL ) { vector<TwBar*>::iterator BarIt; for( BarIt=g_TwMgr->m_Bars.begin(); BarIt!=g_TwMgr->m_Bars.end(); ++BarIt ) if( *BarIt!=NULL ) (*BarIt)->NotUpToDate(); } else { vector<TwBar*>::iterator BarIt; int i = 0; for( BarIt=g_TwMgr->m_Bars.begin(); BarIt!=g_TwMgr->m_Bars.end(); ++BarIt, ++i ) if( (*BarIt)==bar ) break; if( BarIt==g_TwMgr->m_Bars.end() ) { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } bar->NotUpToDate(); } return 1; } // --------------------------------------------------------------------------- int BarVarHasAttrib(CTwBar *_Bar, CTwVar *_Var, const char *_Attrib, bool *_HasValue); int BarVarSetAttrib(CTwBar *_Bar, CTwVar *_Var, CTwVarGroup *_VarParent, int _VarIndex, int _AttribID, const char *_Value); ERetType BarVarGetAttrib(CTwBar *_Bar, CTwVar *_Var, CTwVarGroup *_VarParent, int _VarIndex, int _AttribID, std::vector<double>& outDouble, std::ostringstream& outString); int ANT_CALL TwGetParam(TwBar *bar, const char *varName, const char *paramName, TwParamValueType paramValueType, unsigned int outValueMaxCount, void *outValues) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( paramName==NULL || strlen(paramName)<=0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( outValueMaxCount<=0 || outValues==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( bar==NULL ) bar = TW_GLOBAL_BAR; else { vector<TwBar*>::iterator barIt; int i = 0; for( barIt=g_TwMgr->m_Bars.begin(); barIt!=g_TwMgr->m_Bars.end(); ++barIt, ++i ) if( (*barIt)==bar ) break; if( barIt==g_TwMgr->m_Bars.end() ) { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } } CTwVarGroup *varParent = NULL; int varIndex = -1; CTwVar *var = NULL; if( varName!=NULL && strlen(varName)>0 ) { var = bar->Find(varName, &varParent, &varIndex); if( var==NULL ) { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unknown var '%s/%s'", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), varName); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } } bool hasValue = false; int paramID = BarVarHasAttrib(bar, var, paramName, &hasValue); if( paramID>0 ) { std::ostringstream valStr; std::vector<double> valDbl; const char *PrevLastErrorPtr = g_TwMgr->CheckLastError(); ERetType retType = BarVarGetAttrib(bar, var, varParent, varIndex, paramID, valDbl, valStr); unsigned int i, valDblCount = (unsigned int)valDbl.size(); if( valDblCount > outValueMaxCount ) valDblCount = outValueMaxCount; if( retType==RET_DOUBLE && valDblCount==0 ) { g_TwMgr->SetLastError(g_ErrHasNoValue); retType = RET_ERROR; } if( retType==RET_DOUBLE ) { switch( paramValueType ) { case TW_PARAM_INT32: for( i=0; i<valDblCount; i++ ) (static_cast<int *>(outValues))[i] = (int)valDbl[i]; return valDblCount; case TW_PARAM_FLOAT: for( i=0; i<valDblCount; i++ ) (static_cast<float *>(outValues))[i] = (float)valDbl[i]; return valDblCount; case TW_PARAM_DOUBLE: for( i=0; i<valDblCount; i++ ) (static_cast<double *>(outValues))[i] = valDbl[i]; return valDblCount; case TW_PARAM_CSTRING: valStr.clear(); for( i=0; i<(unsigned int)valDbl.size(); i++ ) // not valDblCount here valStr << ((i>0) ? " " : "") << valDbl[i]; strncpy(static_cast<char *>(outValues), valStr.str().c_str(), outValueMaxCount); i = (unsigned int)valStr.str().size(); if( i>outValueMaxCount-1 ) i = outValueMaxCount-1; (static_cast<char *>(outValues))[i] = '\0'; return 1; // always returns 1 for CSTRING default: g_TwMgr->SetLastError(g_ErrBadParam); // Unknown param value type retType = RET_ERROR; } } else if( retType==RET_STRING ) { if( paramValueType == TW_PARAM_CSTRING ) { strncpy(static_cast<char *>(outValues), valStr.str().c_str(), outValueMaxCount); i = (unsigned int)valStr.str().size(); if( i>outValueMaxCount-1 ) i = outValueMaxCount-1; (static_cast<char *>(outValues))[i] = '\0'; return 1; // always returns 1 for CSTRING } else { g_TwMgr->SetLastError(g_ErrBadType); // string cannot be converted to int or double retType = RET_ERROR; } } if( retType==RET_ERROR ) { bool errMsg = (g_TwMgr->CheckLastError()!=NULL && strlen(g_TwMgr->CheckLastError())>0 && PrevLastErrorPtr!=g_TwMgr->CheckLastError()); _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unable to get param '%s%s%s %s' %s%s", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), (var!=NULL) ? "/" : "", (var!=NULL) ? varName : "", paramName, errMsg ? " : " : "", errMsg ? g_TwMgr->CheckLastError() : ""); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); } return retType; } else { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unknown param '%s%s%s %s'", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), (var!=NULL) ? "/" : "", (var!=NULL) ? varName : "", paramName); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } } int ANT_CALL TwSetParam(TwBar *bar, const char *varName, const char *paramName, TwParamValueType paramValueType, unsigned int inValueCount, const void *inValues) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( paramName==NULL || strlen(paramName)<=0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( inValueCount>0 && inValues==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } TwFreeAsyncDrawing(); // For multi-thread savety if( bar==NULL ) bar = TW_GLOBAL_BAR; else { vector<TwBar*>::iterator barIt; int i = 0; for( barIt=g_TwMgr->m_Bars.begin(); barIt!=g_TwMgr->m_Bars.end(); ++barIt, ++i ) if( (*barIt)==bar ) break; if( barIt==g_TwMgr->m_Bars.end() ) { g_TwMgr->SetLastError(g_ErrNotFound); return 0; } } CTwVarGroup *varParent = NULL; int varIndex = -1; CTwVar *var = NULL; if( varName!=NULL && strlen(varName)>0 ) { var = bar->Find(varName, &varParent, &varIndex); if( var==NULL ) { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unknown var '%s/%s'", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), varName); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } } bool hasValue = false; int paramID = BarVarHasAttrib(bar, var, paramName, &hasValue); if( paramID>0 ) { int ret = 0; const char *PrevLastErrorPtr = g_TwMgr->CheckLastError(); if( hasValue ) { std::ostringstream valuesStr; unsigned int i; switch( paramValueType ) { case TW_PARAM_INT32: for( i=0; i<inValueCount; i++ ) valuesStr << (static_cast<const int *>(inValues))[i] << ((i<inValueCount-1) ? " " : ""); break; case TW_PARAM_FLOAT: for( i=0; i<inValueCount; i++ ) valuesStr << (static_cast<const float *>(inValues))[i] << ((i<inValueCount-1) ? " " : ""); break; case TW_PARAM_DOUBLE: for( i=0; i<inValueCount; i++ ) valuesStr << (static_cast<const double *>(inValues))[i] << ((i<inValueCount-1) ? " " : ""); break; case TW_PARAM_CSTRING: /* for( i=0; i<inValueCount; i++ ) { valuesStr << '`'; const char *str = (static_cast<char * const *>(inValues))[i]; for( const char *ch = str; *ch!=0; ch++ ) if( *ch=='`' ) valuesStr << "`'`'`"; else valuesStr << *ch; valuesStr << "` "; } */ if( inValueCount!=1 ) { g_TwMgr->SetLastError(g_ErrCStrParam); // count for CString param must be 1 return 0; } else valuesStr << static_cast<const char *>(inValues); break; default: g_TwMgr->SetLastError(g_ErrBadParam); // Unknown param value type return 0; } ret = BarVarSetAttrib(bar, var, varParent, varIndex, paramID, valuesStr.str().c_str()); } else ret = BarVarSetAttrib(bar, var, varParent, varIndex, paramID, NULL); if( ret==0 ) { bool errMsg = (g_TwMgr->CheckLastError()!=NULL && strlen(g_TwMgr->CheckLastError())>0 && PrevLastErrorPtr!=g_TwMgr->CheckLastError()); _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unable to set param '%s%s%s %s' %s%s", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), (var!=NULL) ? "/" : "", (var!=NULL) ? varName : "", paramName, errMsg ? " : " : "", errMsg ? g_TwMgr->CheckLastError() : ""); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); } return ret; } else { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Unknown param '%s%s%s %s'", (bar==TW_GLOBAL_BAR) ? "GLOBAL" : bar->m_Name.c_str(), (var!=NULL) ? "/" : "", (var!=NULL) ? varName : "", paramName); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } } // --------------------------------------------------------------------------- static int s_PassProxy = 0; void *CTwMgr::CStruct::s_PassProxyAsClientData = &s_PassProxy; // special tag CTwMgr::CStructProxy::CStructProxy() { memset(this, 0, sizeof(*this)); } CTwMgr::CStructProxy::~CStructProxy() { if( m_StructData!=NULL && m_DeleteStructData ) { //if( m_StructExtData==NULL && g_TwMgr!=NULL && m_Type>=TW_TYPE_STRUCT_BASE && m_Type<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() ) // g_TwMgr->UninitVarData(m_Type, m_StructData, g_TwMgr->m_Structs[m_Type-TW_TYPE_STRUCT_BASE].m_Size); delete[] (char*)m_StructData; } if( m_StructExtData!=NULL ) { //if( g_TwMgr!=NULL && m_Type>=TW_TYPE_STRUCT_BASE && m_Type<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() ) // g_TwMgr->UninitVarData(m_Type, m_StructExtData, g_TwMgr->m_Structs[m_Type-TW_TYPE_STRUCT_BASE].m_Size); delete[] (char*)m_StructExtData; } memset(this, 0, sizeof(*this)); } /* void CTwMgr::InitVarData(TwType _Type, void *_Data, size_t _Size) { if( _Data!=NULL ) { if( _Type>=TW_TYPE_STRUCT_BASE && _Type<TW_TYPE_STRUCT_BASE+(int)m_Structs.size() ) { CTwMgr::CStruct& s = m_Structs[_Type-TW_TYPE_STRUCT_BASE]; for( size_t i=0; i<s.m_Members.size(); ++i ) { CTwMgr::CStructMember& sm = s.m_Members[i]; assert( sm.m_Offset+sm.m_Size<=_Size ); InitVarData(sm.m_Type, (char *)_Data + sm.m_Offset, sm.m_Size); } } else if( _Type==TW_TYPE_STDSTRING ) ::new(_Data) std::string; else memset(_Data, 0, _Size); } } void CTwMgr::UninitVarData(TwType _Type, void *_Data, size_t _Size) { if( _Data!=NULL ) { if( _Type>=TW_TYPE_STRUCT_BASE && _Type<TW_TYPE_STRUCT_BASE+(int)m_Structs.size() ) { CTwMgr::CStruct& s = m_Structs[_Type-TW_TYPE_STRUCT_BASE]; for( size_t i=0; i<s.m_Members.size(); ++i ) { CTwMgr::CStructMember& sm = s.m_Members[i]; assert( sm.m_Offset+sm.m_Size<=_Size ); UninitVarData(sm.m_Type, (char *)_Data + sm.m_Offset, sm.m_Size); } } else if( _Type==TW_TYPE_STDSTRING ) { std::string *Str = (std::string *)_Data; Str->~string(); memset(_Data, 0, _Size); } else memset(_Data, 0, _Size); } } */ void CTwMgr::UnrollCDStdString(std::vector<CCDStdStringRecord>& _Records, TwType _Type, void *_Data) { if( _Data!=NULL ) { if( _Type>=TW_TYPE_STRUCT_BASE && _Type<TW_TYPE_STRUCT_BASE+(int)m_Structs.size() ) { CTwMgr::CStruct& s = m_Structs[_Type-TW_TYPE_STRUCT_BASE]; if( !s.m_IsExt ) for( size_t i=0; i<s.m_Members.size(); ++i ) { CTwMgr::CStructMember& sm = s.m_Members[i]; UnrollCDStdString(_Records, sm.m_Type, (char *)_Data + sm.m_Offset); } else { // nothing: // Ext struct cannot have var of type TW_TYPE_CDSTDSTRING (converted from TW_TYPE_STDSTRING) } } else if( _Type==TW_TYPE_STDSTRING || _Type==TW_TYPE_CDSTDSTRING ) { _Records.push_back(CCDStdStringRecord()); CCDStdStringRecord& Rec = _Records.back(); Rec.m_DataPtr = _Data; memcpy(Rec.m_PrevValue, _Data, m_ClientStdStringStructSize); const char *Str = *(const char **)_Data; if( Str!=NULL ) // Rec.m_StdString = Str; Rec.m_ClientStdString.FromLib(Str); memcpy(Rec.m_DataPtr, &(Rec.m_ClientStdString.ToClient()), sizeof(std::string)); } } } void CTwMgr::RestoreCDStdString(const std::vector<CCDStdStringRecord>& _Records) { for( size_t i=0; i<_Records.size(); ++i ) memcpy(_Records[i].m_DataPtr, _Records[i].m_PrevValue, m_ClientStdStringStructSize); } CTwMgr::CMemberProxy::CMemberProxy() { memset(this, 0, sizeof(*this)); } CTwMgr::CMemberProxy::~CMemberProxy() { memset(this, 0, sizeof(*this)); } void ANT_CALL CTwMgr::CMemberProxy::SetCB(const void *_Value, void *_ClientData) { if( _ClientData && _Value ) { const CMemberProxy *mProxy = static_cast<const CMemberProxy *>(_ClientData); if( g_TwMgr && mProxy ) { const CStructProxy *sProxy = mProxy->m_StructProxy; if( sProxy && sProxy->m_StructData && sProxy->m_Type>=TW_TYPE_STRUCT_BASE && sProxy->m_Type<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() ) { CTwMgr::CStruct& s = g_TwMgr->m_Structs[sProxy->m_Type-TW_TYPE_STRUCT_BASE]; if( mProxy->m_MemberIndex>=0 && mProxy->m_MemberIndex<(int)s.m_Members.size() ) { CTwMgr::CStructMember& m = s.m_Members[mProxy->m_MemberIndex]; if( m.m_Size>0 && m.m_Type!=TW_TYPE_BUTTON ) { if( s.m_IsExt ) { memcpy((char *)sProxy->m_StructExtData + m.m_Offset, _Value, m.m_Size); if( s.m_CopyVarFromExtCallback && sProxy->m_StructExtData ) s.m_CopyVarFromExtCallback(sProxy->m_StructData, sProxy->m_StructExtData, mProxy->m_MemberIndex, (s.m_ExtClientData==s.s_PassProxyAsClientData) ? _ClientData : s.m_ExtClientData); } else memcpy((char *)sProxy->m_StructData + m.m_Offset, _Value, m.m_Size); if( sProxy->m_StructSetCallback ) { g_TwMgr->m_CDStdStringRecords.resize(0); g_TwMgr->UnrollCDStdString(g_TwMgr->m_CDStdStringRecords, sProxy->m_Type, sProxy->m_StructData); sProxy->m_StructSetCallback(sProxy->m_StructData, sProxy->m_StructClientData); g_TwMgr->RestoreCDStdString(g_TwMgr->m_CDStdStringRecords); } } } } } } } void ANT_CALL CTwMgr::CMemberProxy::GetCB(void *_Value, void *_ClientData) { if( _ClientData && _Value ) { const CMemberProxy *mProxy = static_cast<const CMemberProxy *>(_ClientData); if( g_TwMgr && mProxy ) { const CStructProxy *sProxy = mProxy->m_StructProxy; if( sProxy && sProxy->m_StructData && sProxy->m_Type>=TW_TYPE_STRUCT_BASE && sProxy->m_Type<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() ) { CTwMgr::CStruct& s = g_TwMgr->m_Structs[sProxy->m_Type-TW_TYPE_STRUCT_BASE]; if( mProxy->m_MemberIndex>=0 && mProxy->m_MemberIndex<(int)s.m_Members.size() ) { CTwMgr::CStructMember& m = s.m_Members[mProxy->m_MemberIndex]; if( m.m_Size>0 && m.m_Type!=TW_TYPE_BUTTON ) { if( sProxy->m_StructGetCallback ) sProxy->m_StructGetCallback(sProxy->m_StructData, sProxy->m_StructClientData); if( s.m_IsExt ) { if( s.m_CopyVarToExtCallback && sProxy->m_StructExtData ) s.m_CopyVarToExtCallback(sProxy->m_StructData, sProxy->m_StructExtData, mProxy->m_MemberIndex, (s.m_ExtClientData==s.s_PassProxyAsClientData) ? _ClientData : s.m_ExtClientData); memcpy(_Value, (char *)sProxy->m_StructExtData + m.m_Offset, m.m_Size); } else memcpy(_Value, (char *)sProxy->m_StructData + m.m_Offset, m.m_Size); } } } } } } // --------------------------------------------------------------------------- void ANT_CALL CTwMgr::CCDStdString::SetCB(const void *_Value, void *_ClientData) { if( _Value==NULL || _ClientData==NULL || g_TwMgr==NULL ) return; CTwMgr::CCDStdString *CDStdString = (CTwMgr::CCDStdString *)_ClientData; const char *SrcStr = *(const char **)_Value; if( SrcStr==NULL ) { static char s_EmptyString[] = ""; SrcStr = s_EmptyString; } if( CDStdString->m_ClientSetCallback==NULL ) { if( g_TwMgr->m_CopyStdStringToClient && CDStdString->m_ClientStdStringPtr!=NULL ) { CTwMgr::CClientStdString clientSrcStr; // convert VC++ Release/Debug std::string clientSrcStr.FromLib(SrcStr); g_TwMgr->m_CopyStdStringToClient(*(CDStdString->m_ClientStdStringPtr), clientSrcStr.ToClient()); } } else { if( CDStdString->m_ClientSetCallback==CMemberProxy::SetCB ) CDStdString->m_ClientSetCallback(&SrcStr, CDStdString->m_ClientData); else { CTwMgr::CClientStdString clientSrcStr; // convert VC++ Release/Debug std::string clientSrcStr.FromLib(SrcStr); std::string& ValStr = clientSrcStr.ToClient(); CDStdString->m_ClientSetCallback(&ValStr, CDStdString->m_ClientData); } } } void ANT_CALL CTwMgr::CCDStdString::GetCB(void *_Value, void *_ClientData) { if( _Value==NULL || _ClientData==NULL || g_TwMgr==NULL ) return; CTwMgr::CCDStdString *CDStdString = (CTwMgr::CCDStdString *)_ClientData; char **DstStrPtr = (char **)_Value; if( CDStdString->m_ClientGetCallback==NULL ) { if( CDStdString->m_ClientStdStringPtr!=NULL ) { //*DstStrPtr = const_cast<char *>(CDStdString->m_ClientStdStringPtr->c_str()); static CTwMgr::CLibStdString s_LibStr; // static because it will be used as a returned value s_LibStr.FromClient(*CDStdString->m_ClientStdStringPtr); *DstStrPtr = const_cast<char *>(s_LibStr.ToLib().c_str()); } else { static char s_EmptyString[] = ""; *DstStrPtr = s_EmptyString; } } else { // m_ClientGetCallback uses TwCopyStdStringToLibrary to copy string // and TwCopyStdStringToLibrary does the VC++ Debug/Release std::string conversion. CDStdString->m_ClientGetCallback(&(CDStdString->m_LocalString[0]), CDStdString->m_ClientData); //*DstStrPtr = const_cast<char *>(CDStdString->m_LocalString.c_str()); char **StrPtr = (char **)&(CDStdString->m_LocalString[0]); *DstStrPtr = *StrPtr; } } // --------------------------------------------------------------------------- static int s_SeparatorTag = 0; // --------------------------------------------------------------------------- static int AddVar(TwBar *_Bar, const char *_Name, ETwType _Type, void *_VarPtr, bool _ReadOnly, TwSetVarCallback _SetCallback, TwGetVarCallback _GetCallback, TwButtonCallback _ButtonCallback, void *_ClientData, const char *_Def) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } char unnamedVarName[64]; if( _Name==NULL || strlen(_Name)==0 ) // create a name automatically { static unsigned int s_UnnamedVarCount = 0; _snprintf(unnamedVarName, sizeof(unnamedVarName), "TW_UNNAMED_%04X", s_UnnamedVarCount); _Name = unnamedVarName; ++s_UnnamedVarCount; } if( _Bar==NULL || _Name==NULL || strlen(_Name)==0 || (_VarPtr==NULL && _GetCallback==NULL && _Type!=TW_TYPE_BUTTON) ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( _Bar->Find(_Name)!=NULL ) { g_TwMgr->SetLastError(g_ErrExist); return 0; } if( strstr(_Name, "`")!=NULL ) { g_TwMgr->SetLastError(g_ErrNoBackQuote); return 0; } if( _VarPtr==NULL && _Type!=TW_TYPE_BUTTON && _GetCallback!=NULL && _SetCallback==NULL ) _ReadOnly = true; // force readonly in this case // Convert color types if( _Type==TW_TYPE_COLOR32 ) _Type = g_TwMgr->m_TypeColor32; else if( _Type==TW_TYPE_COLOR3F ) _Type = g_TwMgr->m_TypeColor3F; else if( _Type==TW_TYPE_COLOR4F ) _Type = g_TwMgr->m_TypeColor4F; // Convert rotation types if( _Type==TW_TYPE_QUAT4F ) _Type = g_TwMgr->m_TypeQuat4F; else if( _Type==TW_TYPE_QUAT4D ) _Type = g_TwMgr->m_TypeQuat4D; else if( _Type==TW_TYPE_DIR3F ) _Type = g_TwMgr->m_TypeDir3F; else if( _Type==TW_TYPE_DIR3D ) _Type = g_TwMgr->m_TypeDir3D; // VC++ uses a different definition of std::string in Debug and Release modes. // sizeof(std::string) is encoded in TW_TYPE_STDSTRING to overcome this issue. // With VS2010 the binary representation of std::string has changed too. This is // also detected here. if( (_Type&0xffff0000)==(TW_TYPE_STDSTRING&0xffff0000) || (_Type&0xffff0000)==TW_TYPE_STDSTRING_VS2010 || (_Type&0xffff0000)==TW_TYPE_STDSTRING_VS2008 ) { if( g_TwMgr->m_ClientStdStringBaseType==0 ) g_TwMgr->m_ClientStdStringBaseType = (TwType)(_Type&0xffff0000); size_t clientStdStringStructSize = (_Type&0xffff); if( g_TwMgr->m_ClientStdStringStructSize==0 ) g_TwMgr->m_ClientStdStringStructSize = clientStdStringStructSize; int diff = abs((int)g_TwMgr->m_ClientStdStringStructSize - (int)sizeof(std::string)); if( g_TwMgr->m_ClientStdStringStructSize!=clientStdStringStructSize || g_TwMgr->m_ClientStdStringStructSize==0 || (diff!=0 && diff!=sizeof(void*))) { g_TwMgr->SetLastError(g_ErrStdString); return 0; } _Type = TW_TYPE_STDSTRING; // force type to be our TW_TYPE_STDSTRING } if( _Type==TW_TYPE_STDSTRING ) { g_TwMgr->m_CDStdStrings.push_back(CTwMgr::CCDStdString()); CTwMgr::CCDStdString& CDStdString = g_TwMgr->m_CDStdStrings.back(); CDStdString.m_ClientStdStringPtr = (std::string *)_VarPtr; CDStdString.m_ClientSetCallback = _SetCallback; CDStdString.m_ClientGetCallback = _GetCallback; CDStdString.m_ClientData = _ClientData; //CDStdString.m_This = g_TwMgr->m_CDStdStrings.end(); //--CDStdString.m_This; TwGetVarCallback GetCB = CTwMgr::CCDStdString::GetCB; TwSetVarCallback SetCB = CTwMgr::CCDStdString::SetCB; if( _VarPtr==NULL && _SetCallback==NULL ) SetCB = NULL; if( _VarPtr==NULL && _GetCallback==NULL ) GetCB = NULL; return AddVar(_Bar, _Name, TW_TYPE_CDSTDSTRING, NULL, _ReadOnly, SetCB, GetCB, NULL, &CDStdString, _Def); } else if( (_Type>TW_TYPE_UNDEF && _Type<TW_TYPE_STRUCT_BASE) || (_Type>=TW_TYPE_ENUM_BASE && _Type<TW_TYPE_ENUM_BASE+(int)g_TwMgr->m_Enums.size()) || (_Type>TW_TYPE_CSSTRING_BASE && _Type<=TW_TYPE_CSSTRING_MAX) || _Type==TW_TYPE_CDSTDSTRING || IsCustomType(_Type) ) // (_Type>=TW_TYPE_CUSTOM_BASE && _Type<TW_TYPE_CUSTOM_BASE+(int)g_TwMgr->m_Customs.size()) ) { CTwVarAtom *Var = new CTwVarAtom; Var->m_Name = _Name; Var->m_Ptr = _VarPtr; Var->m_Type = _Type; Var->m_ColorPtr = &(_Bar->m_ColLabelText); if( _VarPtr!=NULL ) { assert( _GetCallback==NULL && _SetCallback==NULL && _ButtonCallback==NULL ); Var->m_ReadOnly = _ReadOnly; Var->m_GetCallback = NULL; Var->m_SetCallback = NULL; Var->m_ClientData = NULL; } else { assert( _GetCallback!=NULL || _Type==TW_TYPE_BUTTON ); Var->m_GetCallback = _GetCallback; Var->m_SetCallback = _SetCallback; Var->m_ClientData = _ClientData; if( _Type==TW_TYPE_BUTTON ) { Var->m_Val.m_Button.m_Callback = _ButtonCallback; if( _ButtonCallback==NULL && _ClientData==&s_SeparatorTag ) { Var->m_Val.m_Button.m_Separator = 1; Var->m_Label = " "; } else if( _ButtonCallback==NULL ) Var->m_ColorPtr = &(_Bar->m_ColStaticText); } if( _Type!=TW_TYPE_BUTTON ) Var->m_ReadOnly = (_SetCallback==NULL || _ReadOnly); else Var->m_ReadOnly = (_ButtonCallback==NULL); } Var->SetDefaults(); if( IsCustomType(_Type) ) // _Type>=TW_TYPE_CUSTOM_BASE && _Type<TW_TYPE_CUSTOM_BASE+(int)g_TwMgr->m_Customs.size() ) { if( Var->m_GetCallback==CTwMgr::CMemberProxy::GetCB && Var->m_SetCallback==CTwMgr::CMemberProxy::SetCB ) Var->m_Val.m_Custom.m_MemberProxy = static_cast<CTwMgr::CMemberProxy *>(Var->m_ClientData); else Var->m_Val.m_Custom.m_MemberProxy = NULL; } _Bar->m_VarRoot.m_Vars.push_back(Var); _Bar->NotUpToDate(); g_TwMgr->m_HelpBarNotUpToDate = true; if( _Def!=NULL && strlen(_Def)>0 ) { string d = '`' + _Bar->m_Name + "`/`" + _Name + "` " + _Def; return TwDefine(d.c_str()); } else return 1; } else if(_Type>=TW_TYPE_STRUCT_BASE && _Type<TW_TYPE_STRUCT_BASE+(TwType)g_TwMgr->m_Structs.size()) { CTwMgr::CStruct& s = g_TwMgr->m_Structs[_Type-TW_TYPE_STRUCT_BASE]; CTwMgr::CStructProxy *sProxy = NULL; void *vPtr; if( !s.m_IsExt ) { if( _VarPtr!=NULL ) vPtr = _VarPtr; else { assert( _GetCallback!=NULL || _SetCallback!=NULL ); assert( s.m_Size>0 ); vPtr = new char[s.m_Size]; memset(vPtr, 0, s.m_Size); // create a new StructProxy g_TwMgr->m_StructProxies.push_back(CTwMgr::CStructProxy()); sProxy = &(g_TwMgr->m_StructProxies.back()); sProxy->m_Type = _Type; sProxy->m_StructData = vPtr; sProxy->m_DeleteStructData = true; sProxy->m_StructSetCallback = _SetCallback; sProxy->m_StructGetCallback = _GetCallback; sProxy->m_StructClientData = _ClientData; sProxy->m_CustomDrawCallback = NULL; sProxy->m_CustomMouseButtonCallback = NULL; sProxy->m_CustomMouseMotionCallback = NULL; sProxy->m_CustomMouseLeaveCallback = NULL; sProxy->m_CustomCaptureFocus = false; sProxy->m_CustomIndexFirst = -1; sProxy->m_CustomIndexLast = -1; //g_TwMgr->InitVarData(sProxy->m_Type, sProxy->m_StructData, s.m_Size); } } else // s.m_IsExt { assert( s.m_Size>0 && s.m_ClientStructSize>0 ); vPtr = new char[s.m_Size]; // will be m_StructExtData memset(vPtr, 0, s.m_Size); // create a new StructProxy g_TwMgr->m_StructProxies.push_back(CTwMgr::CStructProxy()); sProxy = &(g_TwMgr->m_StructProxies.back()); sProxy->m_Type = _Type; sProxy->m_StructExtData = vPtr; sProxy->m_StructSetCallback = _SetCallback; sProxy->m_StructGetCallback = _GetCallback; sProxy->m_StructClientData = _ClientData; sProxy->m_CustomDrawCallback = NULL; sProxy->m_CustomMouseButtonCallback = NULL; sProxy->m_CustomMouseMotionCallback = NULL; sProxy->m_CustomMouseLeaveCallback = NULL; sProxy->m_CustomCaptureFocus = false; sProxy->m_CustomIndexFirst = -1; sProxy->m_CustomIndexLast = -1; //g_TwMgr->InitVarData(sProxy->m_Type, sProxy->m_StructExtData, s.m_Size); if( _VarPtr!=NULL ) { sProxy->m_StructData = _VarPtr; sProxy->m_DeleteStructData = false; } else { sProxy->m_StructData = new char[s.m_ClientStructSize]; memset(sProxy->m_StructData, 0, s.m_ClientStructSize); sProxy->m_DeleteStructData = true; //g_TwMgr->InitVarData(ClientStructType, sProxy->m_StructData, s.m_ClientStructSize); //ClientStructType is unknown } _VarPtr = NULL; // force use of TwAddVarCB for members // init m_StructExtdata if( s.m_ExtClientData==CTwMgr::CStruct::s_PassProxyAsClientData ) s.m_StructExtInitCallback(sProxy->m_StructExtData, sProxy); else s.m_StructExtInitCallback(sProxy->m_StructExtData, s.m_ExtClientData); } for( int i=0; i<(int)s.m_Members.size(); ++i ) { CTwMgr::CStructMember& m = s.m_Members[i]; string name = string(_Name) + '.' + m.m_Name; const char *access = ""; if( _ReadOnly ) access = "readonly "; string def = "label=`" + m.m_Name + "` group=`" + _Name + "` " + access; // + m.m_DefString; // member def must be done after group def if( _VarPtr!=NULL ) { if( TwAddVarRW(_Bar, name.c_str(), m.m_Type, (char*)vPtr+m.m_Offset, def.c_str())==0 ) return 0; } else { assert( sProxy!=NULL ); // create a new MemberProxy g_TwMgr->m_MemberProxies.push_back(CTwMgr::CMemberProxy()); CTwMgr::CMemberProxy& mProxy = g_TwMgr->m_MemberProxies.back(); mProxy.m_StructProxy = sProxy; mProxy.m_MemberIndex = i; assert( !(s.m_IsExt && (m.m_Type==TW_TYPE_STDSTRING || m.m_Type==TW_TYPE_CDSTDSTRING)) ); // forbidden because this case is not handled by UnrollCDStdString if( TwAddVarCB(_Bar, name.c_str(), m.m_Type, CTwMgr::CMemberProxy::SetCB, CTwMgr::CMemberProxy::GetCB, &mProxy, def.c_str())==0 ) return 0; mProxy.m_Var = _Bar->Find(name.c_str(), &mProxy.m_VarParent, NULL); mProxy.m_Bar = _Bar; } if( sProxy!=NULL && IsCustomType(m.m_Type) ) // m.m_Type>=TW_TYPE_CUSTOM_BASE && m.m_Type<TW_TYPE_CUSTOM_BASE+(int)g_TwMgr->m_Customs.size() ) { if( sProxy->m_CustomIndexFirst<0 ) sProxy->m_CustomIndexFirst = sProxy->m_CustomIndexLast = i; else sProxy->m_CustomIndexLast = i; } } char structInfo[64]; sprintf(structInfo, "typeid=%d valptr=%p close ", _Type, vPtr); string grpDef = '`' + _Bar->m_Name + "`/`" + _Name + "` " + structInfo; if( _Def!=NULL && strlen(_Def)>0 ) grpDef += _Def; int ret = TwDefine(grpDef.c_str()); for( int i=0; i<(int)s.m_Members.size(); ++i ) // members must be defined even if grpDef has error { CTwMgr::CStructMember& m = s.m_Members[i]; if( m.m_DefString.length()>0 ) { string memberDef = '`' + _Bar->m_Name + "`/`" + _Name + '.' + m.m_Name + "` " + m.m_DefString; if( !TwDefine(memberDef.c_str()) ) // all members must be defined even if memberDef has error ret = 0; } } return ret; } else { if( _Type==TW_TYPE_CSSTRING_BASE ) g_TwMgr->SetLastError(g_ErrBadSize); // static string of size null else g_TwMgr->SetLastError(g_ErrNotFound); return 0; } } // --------------------------------------------------------------------------- int ANT_CALL TwAddVarRW(TwBar *_Bar, const char *_Name, ETwType _Type, void *_Var, const char *_Def) { return AddVar(_Bar, _Name, _Type, _Var, false, NULL, NULL, NULL, NULL, _Def); } // --------------------------------------------------------------------------- int ANT_CALL TwAddVarRO(TwBar *_Bar, const char *_Name, ETwType _Type, const void *_Var, const char *_Def) { return AddVar(_Bar, _Name, _Type, const_cast<void *>(_Var), true, NULL, NULL, NULL, NULL, _Def); } // --------------------------------------------------------------------------- int ANT_CALL TwAddVarCB(TwBar *_Bar, const char *_Name, ETwType _Type, TwSetVarCallback _SetCallback, TwGetVarCallback _GetCallback, void *_ClientData, const char *_Def) { return AddVar(_Bar, _Name, _Type, NULL, false, _SetCallback, _GetCallback, NULL, _ClientData, _Def); } // --------------------------------------------------------------------------- int ANT_CALL TwAddButton(TwBar *_Bar, const char *_Name, TwButtonCallback _Callback, void *_ClientData, const char *_Def) { return AddVar(_Bar, _Name, TW_TYPE_BUTTON, NULL, false, NULL, NULL, _Callback, _ClientData, _Def); } // --------------------------------------------------------------------------- int ANT_CALL TwAddSeparator(TwBar *_Bar, const char *_Name, const char *_Def) { return AddVar(_Bar, _Name, TW_TYPE_BUTTON, NULL, true, NULL, NULL, NULL, &s_SeparatorTag, _Def); } // --------------------------------------------------------------------------- int ANT_CALL TwRemoveVar(TwBar *_Bar, const char *_Name) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL || _Name==NULL || strlen(_Name)==0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( g_TwMgr->m_PopupBar!=NULL && _Bar!=g_TwMgr->m_PopupBar ) // delete popup bar first if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } _Bar->StopEditInPlace(); // desactivate EditInPlace CTwVarGroup *Parent = NULL; int Index = -1; CTwVar *Var = _Bar->Find(_Name, &Parent, &Index); if( Var!=NULL && Parent!=NULL && Index>=0 ) { if( Parent->m_StructValuePtr!=NULL ) { g_TwMgr->SetLastError(g_ErrDelStruct); return 0; } delete Var; Parent->m_Vars.erase(Parent->m_Vars.begin()+Index); if( Parent!=&(_Bar->m_VarRoot) && Parent->m_Vars.size()<=0 ) TwRemoveVar(_Bar, Parent->m_Name.c_str()); _Bar->NotUpToDate(); if( _Bar!=g_TwMgr->m_HelpBar ) g_TwMgr->m_HelpBarNotUpToDate = true; return 1; } g_TwMgr->SetLastError(g_ErrNotFound); return 0; } // --------------------------------------------------------------------------- int ANT_CALL TwRemoveAllVars(TwBar *_Bar) { if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Bar==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } if( g_TwMgr->m_PopupBar!=NULL && _Bar!=g_TwMgr->m_PopupBar && _Bar!=g_TwMgr->m_HelpBar ) // delete popup bar first if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } _Bar->StopEditInPlace(); // desactivate EditInPlace for( vector<CTwVar*>::iterator it=_Bar->m_VarRoot.m_Vars.begin(); it!=_Bar->m_VarRoot.m_Vars.end(); ++it ) if( *it != NULL ) { delete *it; *it = NULL; } _Bar->m_VarRoot.m_Vars.resize(0); _Bar->NotUpToDate(); g_TwMgr->m_HelpBarNotUpToDate = true; return 1; } // --------------------------------------------------------------------------- int ParseToken(string& _Token, const char *_Def, int& Line, int& Column, bool _KeepQuotes, bool _EndCR, char _Sep1='\0', char _Sep2='\0') { const char *Cur = _Def; _Token = ""; // skip spaces while( *Cur==' ' || *Cur=='\t' || *Cur=='\r' || *Cur=='\n' ) { if( *Cur=='\n' && _EndCR ) return (int)(Cur-_Def); // a CR has been found ++Cur; if( *Cur=='\n' ) { ++Line; Column = 1; } else if( *Cur=='\t' ) Column += g_TabLength; else if( *Cur!='\r' ) ++Column; } // read token int QuoteLine=0, QuoteColumn=0; char Quote = 0; bool AddChar; bool LineJustIncremented = false; while( (Quote==0 && (*Cur!='\0' && *Cur!=' ' && *Cur!='\t' && *Cur!='\r' && *Cur!='\n' && *Cur!=_Sep1 && *Cur!=_Sep2)) || (Quote!=0 && (*Cur!='\0' /* && *Cur!='\r' && *Cur!='\n' */)) ) // allow multi-line strings { LineJustIncremented = false; AddChar = true; if( Quote==0 && (*Cur=='\'' || *Cur=='\"' || *Cur=='`') ) { Quote = *Cur; QuoteLine = Line; QuoteColumn = Column; AddChar = _KeepQuotes; } else if ( Quote!=0 && *Cur==Quote ) { Quote = 0; AddChar = _KeepQuotes; } if( AddChar ) _Token += *Cur; ++Cur; if( *Cur=='\t' ) Column += g_TabLength; else if( *Cur=='\n' ) { ++Line; LineJustIncremented = true; Column = 1; } else ++Column; } if( Quote!=0 ) { Line = QuoteLine; Column = QuoteColumn; return -(int)(Cur-_Def); // unclosed quote } else { if( *Cur=='\n' ) { if( !LineJustIncremented ) ++Line; Column = 1; } else if( *Cur=='\t' ) Column += g_TabLength; else if( *Cur!='\r' && *Cur!='\0' ) ++Column; return (int)(Cur-_Def); } } // --------------------------------------------------------------------------- int GetBarVarFromString(CTwBar **_Bar, CTwVar **_Var, CTwVarGroup **_VarParent, int *_VarIndex, const char *_Str) { *_Bar = NULL; *_Var = NULL; *_VarParent = NULL; *_VarIndex = -1; vector<string> Names; string Token; const char *Cur =_Str; int l=1, c=1, p=1; while( *Cur!='\0' && p>0 && Names.size()<=3 ) { p = ParseToken(Token, Cur, l, c, false, true, '/', '\\'); if( p>0 && Token.size()>0 ) { Names.push_back(Token); Cur += p + ((Cur[p]!='\0')?1:0); } } if( p<=0 || (Names.size()!=1 && Names.size()!=2) ) return 0; // parse error int BarIdx = g_TwMgr->FindBar(Names[0].c_str()); if( BarIdx<0 ) { if( Names.size()==1 && strcmp(Names[0].c_str(), "GLOBAL")==0 ) { *_Bar = TW_GLOBAL_BAR; return +3; // 'GLOBAL' found } else return -1; // bar not found } *_Bar = g_TwMgr->m_Bars[BarIdx]; if( Names.size()==1 ) return 1; // bar found, no var name parsed *_Var = (*_Bar)->Find(Names[1].c_str(), _VarParent, _VarIndex); if( *_Var==NULL ) return -2; // var not found return 2; // bar and var found } int BarVarHasAttrib(CTwBar *_Bar, CTwVar *_Var, const char *_Attrib, bool *_HasValue) { assert(_Bar!=NULL && _HasValue!=NULL && _Attrib!=NULL && strlen(_Attrib)>0); *_HasValue = false; if( _Bar==TW_GLOBAL_BAR ) { assert( _Var==NULL ); return g_TwMgr->HasAttrib(_Attrib, _HasValue); } else if( _Var==NULL ) return _Bar->HasAttrib(_Attrib, _HasValue); else return _Var->HasAttrib(_Attrib, _HasValue); } int BarVarSetAttrib(CTwBar *_Bar, CTwVar *_Var, CTwVarGroup *_VarParent, int _VarIndex, int _AttribID, const char *_Value) { assert(_Bar!=NULL && _AttribID>0); /* don't delete popupbar here: if any attrib is changed every frame by the app, popup will not work anymore. if( g_TwMgr->m_PopupBar!=NULL && _Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_PopupBar->m_BarLinkedToPopupList==_Bar ) // delete popup bar first if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } */ if( _Bar==TW_GLOBAL_BAR ) { assert( _Var==NULL ); return g_TwMgr->SetAttrib(_AttribID, _Value); } else if( _Var==NULL ) return _Bar->SetAttrib(_AttribID, _Value); else return _Var->SetAttrib(_AttribID, _Value, _Bar, _VarParent, _VarIndex); // don't make _Bar not-up-to-date here, should be done in SetAttrib if needed to avoid too frequent refreshs } ERetType BarVarGetAttrib(CTwBar *_Bar, CTwVar *_Var, CTwVarGroup *_VarParent, int _VarIndex, int _AttribID, std::vector<double>& outDoubles, std::ostringstream& outString) { assert(_Bar!=NULL && _AttribID>0); if( _Bar==TW_GLOBAL_BAR ) { assert( _Var==NULL ); return g_TwMgr->GetAttrib(_AttribID, outDoubles, outString); } else if( _Var==NULL ) return _Bar->GetAttrib(_AttribID, outDoubles, outString); else return _Var->GetAttrib(_AttribID, _Bar, _VarParent, _VarIndex, outDoubles, outString); } // --------------------------------------------------------------------------- static inline std::string ErrorPosition(bool _MultiLine, int _Line, int _Column) { if( !_MultiLine ) return ""; else { char pos[32]; //_snprintf(pos, sizeof(pos)-1, " line %d column %d", _Line, _Column); _snprintf(pos, sizeof(pos)-1, " line %d", _Line); (void)_Column; pos[sizeof(pos)-1] = '\0'; return pos; } } // --------------------------------------------------------------------------- int ANT_CALL TwDefine(const char *_Def) { CTwFPU fpu; // force fpu precision // hack to scale fonts artificially (for retina display for instance) if( g_TwMgr==NULL && _Def!=NULL ) { size_t l = strlen(_Def); const char *eq = strchr(_Def, '='); if( eq!=NULL && eq!=_Def && l>0 && l<512 ) { char *a = new char[l+1]; char *b = new char[l+1]; if( sscanf(_Def, "%s%s", a, b)==2 && strcmp(a, "GLOBAL")==0 ) { if( strchr(b, '=') != NULL ) *strchr(b, '=') = '\0'; double scal = 1.0; if( _stricmp(b, "fontscaling")==0 && sscanf(eq+1, "%lf", &scal)==1 && scal>0 ) { g_FontScaling = (float)scal; delete[] a; delete[] b; return 1; } } delete[] a; delete[] b; } } if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return 0; // not initialized } if( _Def==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return 0; } bool MultiLine = false; const char *Cur = _Def; while( *Cur!='\0' ) { if( *Cur=='\n' ) { MultiLine = true; break; } ++Cur; } int Line = 1; int Column = 1; enum EState { PARSE_NAME, PARSE_ATTRIB }; EState State = PARSE_NAME; string Token; string Value; CTwBar *Bar = NULL; CTwVar *Var = NULL; CTwVarGroup *VarParent = NULL; int VarIndex = -1; int p; Cur = _Def; while( *Cur!='\0' ) { const char *PrevCur = Cur; p = ParseToken(Token, Cur, Line, Column, (State==PARSE_NAME), (State==PARSE_ATTRIB), (State==PARSE_ATTRIB)?'=':'\0'); if( p<=0 || Token.size()<=0 ) { if( p>0 && Cur[p]=='\0' ) { Cur += p; continue; } _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), (p<0)?(Cur-p):PrevCur); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } char CurSep = Cur[p]; Cur += p + ((CurSep!='\0')?1:0); if( State==PARSE_NAME ) { int Err = GetBarVarFromString(&Bar, &Var, &VarParent, &VarIndex, Token.c_str()); if( Err<=0 ) { if( Err==-1 ) _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: Bar not found%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); else if( Err==-2 ) _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: Variable not found%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); else _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } State = PARSE_ATTRIB; } else // State==PARSE_ATTRIB { assert(State==PARSE_ATTRIB); assert(Bar!=NULL); bool HasValue = false; Value = ""; int AttribID = BarVarHasAttrib(Bar, Var, Token.c_str(), &HasValue); if( AttribID<=0 ) { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: Unknown attribute%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } // special case for backward compatibility if( HasValue && ( _stricmp(Token.c_str(), "readonly")==0 || _stricmp(Token.c_str(), "hexa")==0 ) ) { if( CurSep==' ' || CurSep=='\t' ) { const char *ch = Cur; while( *ch==' ' || *ch=='\t' ) // find next non-space character ++ch; if( *ch!='=' ) // if this is not '=' the param has no value HasValue = false; } } if( HasValue ) { if( CurSep!='=' ) { string EqualStr; p = ParseToken(EqualStr, Cur, Line, Column, true, true, '='); CurSep = Cur[p]; if( p<0 || EqualStr.size()>0 || CurSep!='=' ) { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: '=' not found while reading attribute value%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } Cur += p + 1; } p = ParseToken(Value, Cur, Line, Column, false, true); if( p<=0 ) { _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: can't read attribute value%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } CurSep = Cur[p]; Cur += p + ((CurSep!='\0')?1:0); } const char *PrevLastErrorPtr = g_TwMgr->CheckLastError(); if( BarVarSetAttrib(Bar, Var, VarParent, VarIndex, AttribID, HasValue?Value.c_str():NULL)==0 ) { if( g_TwMgr->CheckLastError()==NULL || strlen(g_TwMgr->CheckLastError())<=0 || g_TwMgr->CheckLastError()==PrevLastErrorPtr ) _snprintf(g_ErrParse, sizeof(g_ErrParse), "Parsing error in def string: wrong attribute value%s [%-16s...]", ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); else _snprintf(g_ErrParse, sizeof(g_ErrParse), "%s%s [%-16s...]", g_TwMgr->CheckLastError(), ErrorPosition(MultiLine, Line, Column).c_str(), Token.c_str()); g_ErrParse[sizeof(g_ErrParse)-1] = '\0'; g_TwMgr->SetLastError(g_ErrParse); return 0; } // sweep spaces to detect next attrib while( *Cur==' ' || *Cur=='\t' || *Cur=='\r' ) { ++Cur; if( *Cur=='\t' ) Column += g_TabLength; else if( *Cur!='\r' ) ++Column; } if( *Cur=='\n' ) // new line detected { ++Line; Column = 1; State = PARSE_NAME; } } } g_TwMgr->m_HelpBarNotUpToDate = true; return 1; } // --------------------------------------------------------------------------- TwType ANT_CALL TwDefineEnum(const char *_Name, const TwEnumVal *_EnumValues, unsigned int _NbValues) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return TW_TYPE_UNDEF; // not initialized } if( _EnumValues==NULL && _NbValues!=0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return TW_TYPE_UNDEF; } if( g_TwMgr->m_PopupBar!=NULL ) // delete popup bar first if it exists { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } size_t enumIndex = g_TwMgr->m_Enums.size(); if( _Name!=NULL && strlen(_Name)>0 ) for( size_t j=0; j<g_TwMgr->m_Enums.size(); ++j ) if( strcmp(_Name, g_TwMgr->m_Enums[j].m_Name.c_str())==0 ) { enumIndex = j; break; } if( enumIndex==g_TwMgr->m_Enums.size() ) g_TwMgr->m_Enums.push_back(CTwMgr::CEnum()); assert( enumIndex>=0 && enumIndex<g_TwMgr->m_Enums.size() ); CTwMgr::CEnum& e = g_TwMgr->m_Enums[enumIndex]; if( _Name!=NULL && strlen(_Name)>0 ) e.m_Name = _Name; else e.m_Name = ""; e.m_Entries.clear(); for(unsigned int i=0; i<_NbValues; ++i) { CTwMgr::CEnum::CEntries::value_type Entry(_EnumValues[i].Value, (_EnumValues[i].Label!=NULL)?_EnumValues[i].Label:""); pair<CTwMgr::CEnum::CEntries::iterator, bool> Result = e.m_Entries.insert(Entry); if( !Result.second ) (Result.first)->second = Entry.second; } return TwType( TW_TYPE_ENUM_BASE + enumIndex ); } // --------------------------------------------------------------------------- TwType TW_CALL TwDefineEnumFromString(const char *_Name, const char *_EnumString) { if (_EnumString == NULL) return TwDefineEnum(_Name, NULL, 0); // split enumString stringstream EnumStream(_EnumString); string Label; vector<string> Labels; while( getline(EnumStream, Label, ',') ) { // trim Label size_t Start = Label.find_first_not_of(" \n\r\t"); size_t End = Label.find_last_not_of(" \n\r\t"); if( Start==string::npos || End==string::npos ) Label = ""; else Label = Label.substr(Start, (End-Start)+1); // store Label Labels.push_back(Label); } // create TwEnumVal array vector<TwEnumVal> Vals(Labels.size()); for( int i=0; i<(int)Labels.size(); i++ ) { Vals[i].Value = i; Vals[i].Label = Labels[i].c_str(); } return TwDefineEnum(_Name, Vals.empty() ? NULL : &(Vals[0]), (unsigned int)Vals.size()); } // --------------------------------------------------------------------------- void ANT_CALL CTwMgr::CStruct::DefaultSummary(char *_SummaryString, size_t _SummaryMaxLength, const void *_Value, void *_ClientData) { const CTwVarGroup *varGroup = static_cast<const CTwVarGroup *>(_Value); // special case if( _SummaryString && _SummaryMaxLength>0 ) _SummaryString[0] = '\0'; size_t structIndex = (size_t)(_ClientData); if( g_TwMgr && _SummaryString && _SummaryMaxLength>2 && varGroup && static_cast<const CTwVar *>(varGroup)->IsGroup() && structIndex>=0 && structIndex<=g_TwMgr->m_Structs.size() ) { // return g_TwMgr->m_Structs[structIndex].m_Name.c_str(); CTwMgr::CStruct& s = g_TwMgr->m_Structs[structIndex]; _SummaryString[0] = '{'; _SummaryString[1] = '\0'; bool separator = false; for( size_t i=0; i<s.m_Members.size(); ++i ) { string varName = varGroup->m_Name + '.' + s.m_Members[i].m_Name; const CTwVar *var = varGroup->Find(varName.c_str(), NULL, NULL); if( var ) { if( var->IsGroup() ) { const CTwVarGroup *grp = static_cast<const CTwVarGroup *>(var); if( grp->m_SummaryCallback!=NULL ) { size_t l = strlen(_SummaryString); if( separator ) { _SummaryString[l++] = ','; _SummaryString[l++] = '\0'; } if( grp->m_SummaryCallback==CTwMgr::CStruct::DefaultSummary ) grp->m_SummaryCallback(_SummaryString+l, _SummaryMaxLength-l, grp, grp->m_SummaryClientData); else grp->m_SummaryCallback(_SummaryString+l, _SummaryMaxLength-l, grp->m_StructValuePtr, grp->m_SummaryClientData); separator = true; } } else { size_t l = strlen(_SummaryString); if( separator ) { _SummaryString[l++] = ','; _SummaryString[l++] = '\0'; } string valString; const CTwVarAtom *atom = static_cast<const CTwVarAtom *>(var); atom->ValueToString(&valString); if( atom->m_Type==TW_TYPE_BOOLCPP || atom->m_Type==TW_TYPE_BOOL8 || atom->m_Type==TW_TYPE_BOOL16 || atom->m_Type==TW_TYPE_BOOL32 ) { if (valString == "0") valString = "-"; else if (valString == "1") valString = "\x7f"; // check sign } strncat(_SummaryString, valString.c_str(), _SummaryMaxLength-l); separator = true; } if( strlen(_SummaryString)>_SummaryMaxLength-2 ) break; } } size_t l = strlen(_SummaryString); if( l>_SummaryMaxLength-2 ) { _SummaryString[_SummaryMaxLength-2] = '.'; _SummaryString[_SummaryMaxLength-1] = '.'; _SummaryString[_SummaryMaxLength+0] = '\0'; } else { _SummaryString[l+0] = '}'; _SummaryString[l+1] = '\0'; } } } // --------------------------------------------------------------------------- TwType ANT_CALL TwDefineStruct(const char *_StructName, const TwStructMember *_StructMembers, unsigned int _NbMembers, size_t _StructSize, TwSummaryCallback _SummaryCallback, void *_SummaryClientData) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return TW_TYPE_UNDEF; // not initialized } if( _StructMembers==NULL || _NbMembers==0 || _StructSize==0 ) { g_TwMgr->SetLastError(g_ErrBadParam); return TW_TYPE_UNDEF; } if( _StructName!=NULL && strlen(_StructName)>0 ) for( size_t j=0; j<g_TwMgr->m_Structs.size(); ++j ) if( strcmp(_StructName, g_TwMgr->m_Structs[j].m_Name.c_str())==0 ) { g_TwMgr->SetLastError(g_ErrExist); return TW_TYPE_UNDEF; } size_t structIndex = g_TwMgr->m_Structs.size(); CTwMgr::CStruct s; s.m_Size = _StructSize; if( _StructName!=NULL && strlen(_StructName)>0 ) s.m_Name = _StructName; else s.m_Name = ""; s.m_Members.resize(_NbMembers); if( _SummaryCallback!=NULL ) { s.m_SummaryCallback = _SummaryCallback; s.m_SummaryClientData = _SummaryClientData; } else { s.m_SummaryCallback = CTwMgr::CStruct::DefaultSummary; s.m_SummaryClientData = (void *)(structIndex); } for( unsigned int i=0; i<_NbMembers; ++i ) { CTwMgr::CStructMember& m = s.m_Members[i]; if( _StructMembers[i].Name!=NULL ) m.m_Name = _StructMembers[i].Name; else { char name[16]; sprintf(name, "%u", i); m.m_Name = name; } m.m_Type = _StructMembers[i].Type; m.m_Size = 0; // to avoid endless recursivity in GetDataSize m.m_Size = CTwVar::GetDataSize(m.m_Type); if( _StructMembers[i].Offset<_StructSize ) m.m_Offset = _StructMembers[i].Offset; else { g_TwMgr->SetLastError(g_ErrOffset); return TW_TYPE_UNDEF; } if( _StructMembers[i].DefString!=NULL && strlen(_StructMembers[i].DefString)>0 ) m.m_DefString = _StructMembers[i].DefString; else m.m_DefString = ""; } g_TwMgr->m_Structs.push_back(s); assert( g_TwMgr->m_Structs.size()==structIndex+1 ); return TwType( TW_TYPE_STRUCT_BASE + structIndex ); } // --------------------------------------------------------------------------- TwType ANT_CALL TwDefineStructExt(const char *_StructName, const TwStructMember *_StructExtMembers, unsigned int _NbExtMembers, size_t _StructSize, size_t _StructExtSize, TwStructExtInitCallback _StructExtInitCallback, TwCopyVarFromExtCallback _CopyVarFromExtCallback, TwCopyVarToExtCallback _CopyVarToExtCallback, TwSummaryCallback _SummaryCallback, void *_ClientData, const char *_Help) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL ) { TwGlobalError(g_ErrNotInit); return TW_TYPE_UNDEF; // not initialized } if( _StructSize==0 || _StructExtInitCallback==NULL || _CopyVarFromExtCallback==NULL || _CopyVarToExtCallback==NULL ) { g_TwMgr->SetLastError(g_ErrBadParam); return TW_TYPE_UNDEF; } TwType type = TwDefineStruct(_StructName, _StructExtMembers, _NbExtMembers, _StructExtSize, _SummaryCallback, _ClientData); if( type>=TW_TYPE_STRUCT_BASE && type<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() ) { CTwMgr::CStruct& s = g_TwMgr->m_Structs[type-TW_TYPE_STRUCT_BASE]; s.m_IsExt = true; s.m_ClientStructSize = _StructSize; s.m_StructExtInitCallback = _StructExtInitCallback; s.m_CopyVarFromExtCallback = _CopyVarFromExtCallback; s.m_CopyVarToExtCallback = _CopyVarToExtCallback; s.m_ExtClientData = _ClientData; if( _Help!=NULL ) s.m_Help = _Help; } return type; } // --------------------------------------------------------------------------- bool TwGetKeyCode(int *_Code, int *_Modif, const char *_String) { assert(_Code!=NULL && _Modif!=NULL); bool Ok = true; *_Modif = TW_KMOD_NONE; *_Code = 0; size_t Start = strlen(_String)-1; if( Start<0 ) return false; while( Start>0 && _String[Start-1]!='+' ) --Start; while( _String[Start]==' ' || _String[Start]=='\t' ) ++Start; char *CodeStr = _strdup(_String+Start); for( size_t i=strlen(CodeStr)-1; i>=0; ++i ) if( CodeStr[i]==' ' || CodeStr[i]=='\t' ) CodeStr[i] = '\0'; else break; /* if( strstr(_String, "SHIFT")!=NULL || strstr(_String, "shift")!=NULL ) *_Modif |= TW_KMOD_SHIFT; if( strstr(_String, "CTRL")!=NULL || strstr(_String, "ctrl")!=NULL ) *_Modif |= TW_KMOD_CTRL; if( strstr(_String, "META")!=NULL || strstr(_String, "meta")!=NULL ) *_Modif |= TW_KMOD_META; if( strstr(_String, "ALTGR")!=NULL || strstr(_String, "altgr")!=NULL ) ((void)(0)); // *_Modif |= TW_KMOD_ALTGR; else // ALT and ALTGR are exclusive if( strstr(_String, "ALT")!=NULL || strstr(_String, "alt")!=NULL ) *_Modif |= TW_KMOD_ALT; */ char *up = _strdup(_String); // _strupr(up); for( char *upch=up; *upch!='\0'; ++upch ) *upch = (char)toupper(*upch); if( strstr(up, "SHIFT")!=NULL ) *_Modif |= TW_KMOD_SHIFT; if( strstr(up, "CTRL")!=NULL ) *_Modif |= TW_KMOD_CTRL; if( strstr(up, "META")!=NULL ) *_Modif |= TW_KMOD_META; if( strstr(up, "ALTGR")!=NULL ) ((void)(0)); // *_Modif |= TW_KMOD_ALTGR; else // ALT and ALTGR are exclusive if( strstr(up, "ALT")!=NULL ) *_Modif |= TW_KMOD_ALT; free(up); if( strlen(CodeStr)==1 ) *_Code = (unsigned char)(CodeStr[0]); else if( _stricmp(CodeStr, "backspace")==0 || _stricmp(CodeStr, "bs")==0 ) *_Code = TW_KEY_BACKSPACE; else if( _stricmp(CodeStr, "tab")==0 ) *_Code = TW_KEY_TAB; else if( _stricmp(CodeStr, "clear")==0 || _stricmp(CodeStr, "clr")==0 ) *_Code = TW_KEY_CLEAR; else if( _stricmp(CodeStr, "return")==0 || _stricmp(CodeStr, "ret")==0 ) *_Code = TW_KEY_RETURN; else if( _stricmp(CodeStr, "pause")==0 ) *_Code = TW_KEY_PAUSE; else if( _stricmp(CodeStr, "escape")==0 || _stricmp(CodeStr, "esc")==0 ) *_Code = TW_KEY_ESCAPE; else if( _stricmp(CodeStr, "space")==0 ) *_Code = TW_KEY_SPACE; else if( _stricmp(CodeStr, "delete")==0 || _stricmp(CodeStr, "del")==0 ) *_Code = TW_KEY_DELETE; /* else if( strlen(CodeStr)==4 && CodeStr[3]>='0' && CodeStr[3]<='9' && (strstr(CodeStr, "pad")==CodeStr || strstr(CodeStr, "PAD")==CodeStr) ) *_Code = TW_KEY_PAD_0 + CodeStr[3]-'0'; else if( _stricmp(CodeStr, "pad.")==0 ) *_Code = TW_KEY_PAD_PERIOD; else if( _stricmp(CodeStr, "pad/")==0 ) *_Code = TW_KEY_PAD_DIVIDE; else if( _stricmp(CodeStr, "pad*")==0 ) *_Code = TW_KEY_PAD_MULTIPLY; else if( _stricmp(CodeStr, "pad+")==0 ) *_Code = TW_KEY_PAD_PLUS; else if( _stricmp(CodeStr, "pad-")==0 ) *_Code = TW_KEY_PAD_MINUS; else if( _stricmp(CodeStr, "padenter")==0 ) *_Code = TW_KEY_PAD_ENTER; else if( _stricmp(CodeStr, "pad=")==0 ) *_Code = TW_KEY_PAD_EQUALS; */ else if( _stricmp(CodeStr, "up")==0 ) *_Code = TW_KEY_UP; else if( _stricmp(CodeStr, "down")==0 ) *_Code = TW_KEY_DOWN; else if( _stricmp(CodeStr, "right")==0 ) *_Code = TW_KEY_RIGHT; else if( _stricmp(CodeStr, "left")==0 ) *_Code = TW_KEY_LEFT; else if( _stricmp(CodeStr, "insert")==0 || _stricmp(CodeStr, "ins")==0 ) *_Code = TW_KEY_INSERT; else if( _stricmp(CodeStr, "home")==0 ) *_Code = TW_KEY_HOME; else if( _stricmp(CodeStr, "end")==0 ) *_Code = TW_KEY_END; else if( _stricmp(CodeStr, "pgup")==0 ) *_Code = TW_KEY_PAGE_UP; else if( _stricmp(CodeStr, "pgdown")==0 ) *_Code = TW_KEY_PAGE_DOWN; else if( (strlen(CodeStr)==2 || strlen(CodeStr)==3) && (CodeStr[0]=='f' || CodeStr[0]=='F') ) { int n = 0; if( sscanf(CodeStr+1, "%d", &n)==1 && n>0 && n<16 ) *_Code = TW_KEY_F1 + n-1; else Ok = false; } free(CodeStr); return Ok; } bool TwGetKeyString(std::string *_String, int _Code, int _Modif) { assert(_String!=NULL); bool Ok = true; if( _Modif & TW_KMOD_SHIFT ) *_String += "SHIFT+"; if( _Modif & TW_KMOD_CTRL ) *_String += "CTRL+"; if ( _Modif & TW_KMOD_ALT ) *_String += "ALT+"; if ( _Modif & TW_KMOD_META ) *_String += "META+"; // if ( _Modif & TW_KMOD_ALTGR ) // *_String += "ALTGR+"; switch( _Code ) { case TW_KEY_BACKSPACE: *_String += "BackSpace"; break; case TW_KEY_TAB: *_String += "Tab"; break; case TW_KEY_CLEAR: *_String += "Clear"; break; case TW_KEY_RETURN: *_String += "Return"; break; case TW_KEY_PAUSE: *_String += "Pause"; break; case TW_KEY_ESCAPE: *_String += "Esc"; break; case TW_KEY_SPACE: *_String += "Space"; break; case TW_KEY_DELETE: *_String += "Delete"; break; /* case TW_KEY_PAD_0: *_String += "PAD0"; break; case TW_KEY_PAD_1: *_String += "PAD1"; break; case TW_KEY_PAD_2: *_String += "PAD2"; break; case TW_KEY_PAD_3: *_String += "PAD3"; break; case TW_KEY_PAD_4: *_String += "PAD4"; break; case TW_KEY_PAD_5: *_String += "PAD5"; break; case TW_KEY_PAD_6: *_String += "PAD6"; break; case TW_KEY_PAD_7: *_String += "PAD7"; break; case TW_KEY_PAD_8: *_String += "PAD8"; break; case TW_KEY_PAD_9: *_String += "PAD9"; break; case TW_KEY_PAD_PERIOD: *_String += "PAD."; break; case TW_KEY_PAD_DIVIDE: *_String += "PAD/"; break; case TW_KEY_PAD_MULTIPLY: *_String += "PAD*"; break; case TW_KEY_PAD_MINUS: *_String += "PAD-"; break; case TW_KEY_PAD_PLUS: *_String += "PAD+"; break; case TW_KEY_PAD_ENTER: *_String += "PADEnter"; break; case TW_KEY_PAD_EQUALS: *_String += "PAD="; break; */ case TW_KEY_UP: *_String += "Up"; break; case TW_KEY_DOWN: *_String += "Down"; break; case TW_KEY_RIGHT: *_String += "Right"; break; case TW_KEY_LEFT: *_String += "Left"; break; case TW_KEY_INSERT: *_String += "Insert"; break; case TW_KEY_HOME: *_String += "Home"; break; case TW_KEY_END: *_String += "End"; break; case TW_KEY_PAGE_UP: *_String += "PgUp"; break; case TW_KEY_PAGE_DOWN: *_String += "PgDown"; break; case TW_KEY_F1: *_String += "F1"; break; case TW_KEY_F2: *_String += "F2"; break; case TW_KEY_F3: *_String += "F3"; break; case TW_KEY_F4: *_String += "F4"; break; case TW_KEY_F5: *_String += "F5"; break; case TW_KEY_F6: *_String += "F6"; break; case TW_KEY_F7: *_String += "F7"; break; case TW_KEY_F8: *_String += "F8"; break; case TW_KEY_F9: *_String += "F9"; break; case TW_KEY_F10: *_String += "F10"; break; case TW_KEY_F11: *_String += "F11"; break; case TW_KEY_F12: *_String += "F12"; break; case TW_KEY_F13: *_String += "F13"; break; case TW_KEY_F14: *_String += "F14"; break; case TW_KEY_F15: *_String += "F15"; break; default: if( _Code>0 && _Code<256 ) *_String += char(_Code); else { *_String += "Unknown"; Ok = false; } } return Ok; } // --------------------------------------------------------------------------- const int TW_MOUSE_NOMOTION = -1; ETwMouseAction TW_MOUSE_MOTION = (ETwMouseAction)(-2); ETwMouseAction TW_MOUSE_WHEEL = (ETwMouseAction)(-3); ETwMouseButtonID TW_MOUSE_NA = (ETwMouseButtonID)(-1); static int TwMouseEvent(ETwMouseAction _EventType, TwMouseButtonID _Button, int _MouseX, int _MouseY, int _WheelPos) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) { // TwGlobalError(g_ErrNotInit); -> not an error here return 0; // not initialized } if( g_TwMgr->m_WndHeight<=0 || g_TwMgr->m_WndWidth<=0 ) { //g_TwMgr->SetLastError(g_ErrBadWndSize); // not an error, windows not yet ready. return 0; } // For multi-thread safety if( !TwFreeAsyncDrawing() ) return 0; if( _MouseX==TW_MOUSE_NOMOTION ) _MouseX = g_TwMgr->m_LastMouseX; else g_TwMgr->m_LastMouseX = _MouseX; if( _MouseY==TW_MOUSE_NOMOTION ) _MouseY = g_TwMgr->m_LastMouseY; else g_TwMgr->m_LastMouseY = _MouseY; // for autorepeat if( (!g_TwMgr->m_IsRepeatingMousePressed || !g_TwMgr->m_CanRepeatMousePressed) && _EventType==TW_MOUSE_PRESSED ) { g_TwMgr->m_LastMousePressedTime = g_TwMgr->m_Timer.GetTime(); g_TwMgr->m_LastMousePressedButtonID = _Button; g_TwMgr->m_LastMousePressedPosition[0] = _MouseX; g_TwMgr->m_LastMousePressedPosition[1] = _MouseY; g_TwMgr->m_CanRepeatMousePressed = true; g_TwMgr->m_IsRepeatingMousePressed = false; } else if( _EventType==TW_MOUSE_RELEASED || _EventType==TW_MOUSE_WHEEL ) { g_TwMgr->m_CanRepeatMousePressed = false; g_TwMgr->m_IsRepeatingMousePressed = false; } bool Handled = false; bool wasPopup = (g_TwMgr->m_PopupBar!=NULL); CTwBar *Bar = NULL; int i; // search for a bar with mousedrag enabled CTwBar *BarDragging = NULL; for( i=((int)g_TwMgr->m_Bars.size())-1; i>=0; --i ) { Bar = g_TwMgr->m_Bars[g_TwMgr->m_Order[i]]; if( Bar!=NULL && Bar->m_Visible && Bar->IsDragging() ) { BarDragging = Bar; break; } } for( i=(int)g_TwMgr->m_Bars.size(); i>=0; --i ) { if( i==(int)g_TwMgr->m_Bars.size() ) // first try the bar with mousedrag enabled (this bar has the focus) Bar = BarDragging; else { Bar = g_TwMgr->m_Bars[g_TwMgr->m_Order[i]]; if( Bar==BarDragging ) continue; } if( Bar!=NULL && Bar->m_Visible ) { if( _EventType==TW_MOUSE_MOTION ) Handled = Bar->MouseMotion(_MouseX, _MouseY); else if( _EventType==TW_MOUSE_PRESSED || _EventType==TW_MOUSE_RELEASED ) Handled = Bar->MouseButton(_Button, (_EventType==TW_MOUSE_PRESSED), _MouseX, _MouseY); else if( _EventType==TW_MOUSE_WHEEL ) { if( abs(_WheelPos-g_TwMgr->m_LastMouseWheelPos)<4 ) // avoid crazy wheel positions Handled = Bar->MouseWheel(_WheelPos, g_TwMgr->m_LastMouseWheelPos, _MouseX, _MouseY); } if( Handled ) break; } } if( g_TwMgr==NULL ) // Mgr might have been destroyed by the client inside a callback call return 1; /* if( i>=0 && Bar!=NULL && Handled && (_EventType==TW_MOUSE_PRESSED || Bar->IsMinimized()) && i!=((int)g_TwMgr->m_Bars.size())-1 ) { int iOrder = g_TwMgr->m_Order[i]; for( int j=i; j<(int)g_TwMgr->m_Bars.size()-1; ++j ) g_TwMgr->m_Order[j] = g_TwMgr->m_Order[j+1]; g_TwMgr->m_Order[(int)g_TwMgr->m_Bars.size()-1] = iOrder; } */ if( _EventType==TW_MOUSE_PRESSED || (Bar!=NULL && Bar->IsMinimized() && Handled) ) { if( wasPopup && Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_PopupBar!=NULL ) // delete popup { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } if( i>=0 && Bar!=NULL && Handled && !wasPopup ) TwSetTopBar(Bar); } if( _EventType==TW_MOUSE_WHEEL ) g_TwMgr->m_LastMouseWheelPos = _WheelPos; return Handled ? 1 : 0; } int ANT_CALL TwMouseButton(ETwMouseAction _EventType, TwMouseButtonID _Button) { return TwMouseEvent(_EventType, _Button, TW_MOUSE_NOMOTION, TW_MOUSE_NOMOTION, 0); } int ANT_CALL TwMouseMotion(int _MouseX, int _MouseY) { return TwMouseEvent(TW_MOUSE_MOTION, TW_MOUSE_NA, _MouseX, _MouseY, 0); } int ANT_CALL TwMouseWheel(int _Pos) { return TwMouseEvent(TW_MOUSE_WHEEL, TW_MOUSE_NA, TW_MOUSE_NOMOTION, TW_MOUSE_NOMOTION, _Pos); } // --------------------------------------------------------------------------- static int TranslateKey(int _Key, int _Modifiers) { // CTRL special cases //if( (_Modifiers&TW_KMOD_CTRL) && !(_Modifiers&TW_KMOD_ALT || _Modifiers&TW_KMOD_META) && _Key>0 && _Key<32 ) // _Key += 'a'-1; if( (_Modifiers&TW_KMOD_CTRL) ) { if( _Key>='a' && _Key<='z' && ( ((_Modifiers&0x2000) && !(_Modifiers&TW_KMOD_SHIFT)) || (!(_Modifiers&0x2000) && (_Modifiers&TW_KMOD_SHIFT)) )) // 0x2000 is SDL's KMOD_CAPS _Key += 'A'-'a'; else if ( _Key>='A' && _Key<='Z' && ( ((_Modifiers&0x2000) && (_Modifiers&TW_KMOD_SHIFT)) || (!(_Modifiers&0x2000) && !(_Modifiers&TW_KMOD_SHIFT)) )) // 0x2000 is SDL's KMOD_CAPS _Key += 'a'-'A'; } // PAD translation (for SDL keysym) if( _Key>=256 && _Key<=272 ) // 256=SDLK_KP0 ... 272=SDLK_KP_EQUALS { //bool Num = ((_Modifiers&TW_KMOD_SHIFT) && !(_Modifiers&0x1000)) || (!(_Modifiers&TW_KMOD_SHIFT) && (_Modifiers&0x1000)); // 0x1000 is SDL's KMOD_NUM //_Modifiers &= ~TW_KMOD_SHIFT; // remove shift modifier bool Num = (!(_Modifiers&TW_KMOD_SHIFT) && (_Modifiers&0x1000)); // 0x1000 is SDL's KMOD_NUM if( _Key==266 ) // SDLK_KP_PERIOD _Key = Num ? '.' : TW_KEY_DELETE; else if( _Key==267 ) // SDLK_KP_DIVIDE _Key = '/'; else if( _Key==268 ) // SDLK_KP_MULTIPLY _Key = '*'; else if( _Key==269 ) // SDLK_KP_MINUS _Key = '-'; else if( _Key==270 ) // SDLK_KP_PLUS _Key = '+'; else if( _Key==271 ) // SDLK_KP_ENTER _Key = TW_KEY_RETURN; else if( _Key==272 ) // SDLK_KP_EQUALS _Key = '='; else if( Num ) // num SDLK_KP0..9 _Key += '0' - 256; else if( _Key==256 ) // non-num SDLK_KP01 _Key = TW_KEY_INSERT; else if( _Key==257 ) // non-num SDLK_KP1 _Key = TW_KEY_END; else if( _Key==258 ) // non-num SDLK_KP2 _Key = TW_KEY_DOWN; else if( _Key==259 ) // non-num SDLK_KP3 _Key = TW_KEY_PAGE_DOWN; else if( _Key==260 ) // non-num SDLK_KP4 _Key = TW_KEY_LEFT; else if( _Key==262 ) // non-num SDLK_KP6 _Key = TW_KEY_RIGHT; else if( _Key==263 ) // non-num SDLK_KP7 _Key = TW_KEY_HOME; else if( _Key==264 ) // non-num SDLK_KP8 _Key = TW_KEY_UP; else if( _Key==265 ) // non-num SDLK_KP9 _Key = TW_KEY_PAGE_UP; } return _Key; } // --------------------------------------------------------------------------- static int KeyPressed(int _Key, int _Modifiers, bool _TestOnly) { CTwFPU fpu; // force fpu precision if( g_TwMgr==NULL || g_TwMgr->m_Graph==NULL ) { // TwGlobalError(g_ErrNotInit); -> not an error here return 0; // not initialized } if( g_TwMgr->m_WndHeight<=0 || g_TwMgr->m_WndWidth<=0 ) { //g_TwMgr->SetLastError(g_ErrBadWndSize); // not an error, windows not yet ready. return 0; } // For multi-thread savety if( !TwFreeAsyncDrawing() ) return 0; /* // Test for TwDeleteBar if( _Key>='0' && _Key<='9' ) { int n = _Key-'0'; if( (int)g_TwMgr->m_Bars.size()>n && g_TwMgr->m_Bars[n]!=NULL ) { printf("Delete %s\n", g_TwMgr->m_Bars[n]->m_Name.c_str()); TwDeleteBar(g_TwMgr->m_Bars[n]); } else printf("can't delete %d\n", n); return 1; } */ //char s[256]; //sprintf(s, "twkeypressed k=%d m=%x\n", _Key, _Modifiers); //OutputDebugString(s); _Key = TranslateKey(_Key, _Modifiers); if( _Key>' ' && _Key<256 ) // don't test SHIFT if _Key is a common key _Modifiers &= ~TW_KMOD_SHIFT; // complete partial modifiers comming from SDL if( _Modifiers & TW_KMOD_SHIFT ) _Modifiers |= TW_KMOD_SHIFT; if( _Modifiers & TW_KMOD_CTRL ) _Modifiers |= TW_KMOD_CTRL; if( _Modifiers & TW_KMOD_ALT ) _Modifiers |= TW_KMOD_ALT; if( _Modifiers & TW_KMOD_META ) _Modifiers |= TW_KMOD_META; bool Handled = false; CTwBar *Bar = NULL; CTwBar *PopupBar = g_TwMgr->m_PopupBar; //int Order = 0; int i; if( _Key>0 && _Key<TW_KEY_LAST ) { // First send it to bar which includes the mouse pointer int MouseX = g_TwMgr->m_LastMouseX; int MouseY = g_TwMgr->m_LastMouseY; for( i=((int)g_TwMgr->m_Bars.size())-1; i>=0 && !Handled; --i ) { Bar = g_TwMgr->m_Bars[g_TwMgr->m_Order[i]]; if( Bar!=NULL && Bar->m_Visible && !Bar->IsMinimized() && ( (MouseX>=Bar->m_PosX && MouseX<Bar->m_PosX+Bar->m_Width && MouseY>=Bar->m_PosY && MouseY<Bar->m_PosY+Bar->m_Height) || Bar==PopupBar) ) { if (_TestOnly) Handled = Bar->KeyTest(_Key, _Modifiers); else Handled = Bar->KeyPressed(_Key, _Modifiers); } } // If not handled, send it to non-iconified bars in the right order for( i=((int)g_TwMgr->m_Bars.size())-1; i>=0 && !Handled; --i ) { Bar = g_TwMgr->m_Bars[g_TwMgr->m_Order[i]]; /* for( size_t j=0; j<g_TwMgr->m_Bars.size(); ++j ) if( g_TwMgr->m_Order[j]==i ) { Bar = g_TwMgr->m_Bars[j]; break; } Order = i; */ if( Bar!=NULL && Bar->m_Visible && !Bar->IsMinimized() ) { if( _TestOnly ) Handled = Bar->KeyTest(_Key, _Modifiers); else Handled = Bar->KeyPressed(_Key, _Modifiers); if( g_TwMgr==NULL ) // Mgr might have been destroyed by the client inside a callback call return 1; } } // If not handled, send it to iconified bars in the right order for( i=((int)g_TwMgr->m_Bars.size())-1; i>=0 && !Handled; --i ) { Bar = g_TwMgr->m_Bars[g_TwMgr->m_Order[i]]; if( Bar!=NULL && Bar->m_Visible && Bar->IsMinimized() ) { if( _TestOnly ) Handled = Bar->KeyTest(_Key, _Modifiers); else Handled = Bar->KeyPressed(_Key, _Modifiers); } } if( g_TwMgr->m_HelpBar!=NULL && g_TwMgr->m_Graph && !_TestOnly ) { string Str; TwGetKeyString(&Str, _Key, _Modifiers); char Msg[256]; sprintf(Msg, "Key pressed: %s", Str.c_str()); g_TwMgr->m_KeyPressedStr = Msg; g_TwMgr->m_KeyPressedBuildText = true; // OutputDebugString(Msg); } } if( Handled && Bar!=g_TwMgr->m_PopupBar && g_TwMgr->m_PopupBar!=NULL && g_TwMgr->m_PopupBar==PopupBar ) // delete popup { TwDeleteBar(g_TwMgr->m_PopupBar); g_TwMgr->m_PopupBar = NULL; } if( Handled && Bar!=NULL && Bar!=g_TwMgr->m_PopupBar && Bar!=PopupBar ) // popup bar may have been destroyed TwSetTopBar(Bar); return Handled ? 1 : 0; } int ANT_CALL TwKeyPressed(int _Key, int _Modifiers) { return KeyPressed(_Key, _Modifiers, false); } int ANT_CALL TwKeyTest(int _Key, int _Modifiers) { return KeyPressed(_Key, _Modifiers, true); } // --------------------------------------------------------------------------- struct StructCompare : public binary_function<TwType, TwType, bool> { bool operator()(const TwType& _Left, const TwType& _Right) const { assert( g_TwMgr!=NULL ); int i0 = _Left-TW_TYPE_STRUCT_BASE; int i1 = _Right-TW_TYPE_STRUCT_BASE; if( i0>=0 && i0<(int)g_TwMgr->m_Structs.size() && i1>=0 && i1<(int)g_TwMgr->m_Structs.size() ) return g_TwMgr->m_Structs[i0].m_Name < g_TwMgr->m_Structs[i1].m_Name; else return false; } }; typedef set<TwType, StructCompare> StructSet; static void InsertUsedStructs(StructSet& _Set, const CTwVarGroup *_Grp) { assert( g_TwMgr!=NULL && _Grp!=NULL ); for( size_t i=0; i<_Grp->m_Vars.size(); ++i ) if( _Grp->m_Vars[i]!=NULL && _Grp->m_Vars[i]->m_Visible && _Grp->m_Vars[i]->IsGroup() )// && _Grp->m_Vars[i]->m_Help.length()>0 ) { const CTwVarGroup *SubGrp = static_cast<const CTwVarGroup *>(_Grp->m_Vars[i]); if( SubGrp->m_StructValuePtr!=NULL && SubGrp->m_StructType>=TW_TYPE_STRUCT_BASE && SubGrp->m_StructType<TW_TYPE_STRUCT_BASE+(int)g_TwMgr->m_Structs.size() && g_TwMgr->m_Structs[SubGrp->m_StructType-TW_TYPE_STRUCT_BASE].m_Name.length()>0 ) { if( SubGrp->m_Help.length()>0 ) _Set.insert(SubGrp->m_StructType); else { int idx = SubGrp->m_StructType - TW_TYPE_STRUCT_BASE; if( idx>=0 && idx<(int)g_TwMgr->m_Structs.size() && g_TwMgr->m_Structs[idx].m_Name.length()>0 ) { for( size_t j=0; j<g_TwMgr->m_Structs[idx].m_Members.size(); ++j ) if( g_TwMgr->m_Structs[idx].m_Members[j].m_Help.length()>0 ) { _Set.insert(SubGrp->m_StructType); break; } } } } InsertUsedStructs(_Set, SubGrp); } } static void SplitString(vector<string>& _OutSplits, const char *_String, int _Width, const CTexFont *_Font) { assert( _Font!=NULL && _String!=NULL ); _OutSplits.resize(0); int l = (int)strlen(_String); if( l==0 ) { _String = " "; l = 1; } if( _String!=NULL && l>0 && _Width>0 ) { int w = 0; int i = 0; int First = 0; int Last = 0; bool PrevNotBlank = true; unsigned char c; bool Tab = false, CR = false; string Split; const string TabString(g_TabLength, ' '); while( i<l ) { c = _String[i]; if( c=='\t' ) { w += g_TabLength * _Font->m_CharWidth[(int)' ']; Tab = true; } else if( c=='\n' ) { w += _Width+1; // force split Last = i; CR = true; } else w += _Font->m_CharWidth[(int)c]; if( w>_Width || i==l-1 ) { if( Last<=First || i==l-1 ) Last = i; if( Tab ) { Split.resize(0); for(int k=0; k<Last-First+(CR?0:1); ++k) if( _String[First+k]=='\t' ) Split += TabString; else Split += _String[First+k]; Tab = false; } else Split.assign(_String+First, Last-First+(CR?0:1)); _OutSplits.push_back(Split); First = Last+1; if( !CR ) while( First<l && (_String[First]==' ' || _String[First]=='\t') ) // skip blanks ++First; Last = First; w = 0; PrevNotBlank = true; i = First; CR = false; } else if( c==' ' || c=='\t' ) { if( PrevNotBlank ) Last = i-1; PrevNotBlank = false; ++i; } else { PrevNotBlank = true; ++i; } } } } static int AppendHelpString(CTwVarGroup *_Grp, const char *_String, int _Level, int _Width, ETwType _Type) { assert( _Grp!=NULL && g_TwMgr!=NULL && g_TwMgr->m_HelpBar!=NULL); assert( _String!=NULL ); int n = 0; const CTexFont *Font = g_TwMgr->m_HelpBar->m_Font; assert(Font!=NULL); string Decal; for( int s=0; s<_Level; ++s ) Decal += ' '; int DecalWidth = (_Level+2)*Font->m_CharWidth[(int)' ']; if( _Width>DecalWidth ) { vector<string> Split; SplitString(Split, _String, _Width-DecalWidth, Font); for( int i=0; i<(int)Split.size(); ++i ) { CTwVarAtom *Var = new CTwVarAtom; Var->m_Name = Decal + Split[i]; Var->m_Ptr = NULL; if( _Type==TW_TYPE_HELP_HEADER ) Var->m_ReadOnly = false; else Var->m_ReadOnly = true; Var->m_NoSlider = true; Var->m_DontClip = true; Var->m_Type = _Type; Var->m_LeftMargin = (signed short)((_Level+1)*Font->m_CharWidth[(int)' ']); Var->m_TopMargin = (signed short)(-g_TwMgr->m_HelpBar->m_Sep); //Var->m_TopMargin = 1; Var->m_ColorPtr = &(g_TwMgr->m_HelpBar->m_ColHelpText); Var->SetDefaults(); _Grp->m_Vars.push_back(Var); ++n; } } return n; } static int AppendHelp(CTwVarGroup *_Grp, const CTwVarGroup *_ToAppend, int _Level, int _Width) { assert( _Grp!=NULL ); assert( _ToAppend!=NULL ); int n = 0; string Decal; for( int s=0; s<_Level; ++s ) Decal += ' '; if( _ToAppend->m_Help.size()>0 ) n += AppendHelpString(_Grp, _ToAppend->m_Help.c_str(), _Level, _Width, TW_TYPE_HELP_GRP); for( size_t i=0; i<_ToAppend->m_Vars.size(); ++i ) if( _ToAppend->m_Vars[i]!=NULL && _ToAppend->m_Vars[i]->m_Visible ) { bool append = true; if( !_ToAppend->m_Vars[i]->IsGroup() ) { const CTwVarAtom *a = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i]); if( a->m_Type==TW_TYPE_BUTTON && a->m_Val.m_Button.m_Callback==NULL ) append = false; else if( a->m_KeyIncr[0]==0 && a->m_KeyIncr[1]==0 && a->m_KeyDecr[0]==0 && a->m_KeyDecr[1]==0 && a->m_Help.length()<=0 ) append = false; } else if( _ToAppend->m_Vars[i]->IsGroup() && static_cast<const CTwVarGroup *>(_ToAppend->m_Vars[i])->m_StructValuePtr!=NULL // that's a struct var && _ToAppend->m_Vars[i]->m_Help.length()<=0 ) append = false; if( append ) { CTwVarAtom *Var = new CTwVarAtom; Var->m_Name = Decal; if( _ToAppend->m_Vars[i]->m_Label.size()>0 ) Var->m_Name += _ToAppend->m_Vars[i]->m_Label; else Var->m_Name += _ToAppend->m_Vars[i]->m_Name; Var->m_Ptr = NULL; if( _ToAppend->m_Vars[i]->IsGroup() && static_cast<const CTwVarGroup *>(_ToAppend->m_Vars[i])->m_StructValuePtr!=NULL ) { // That's a struct var Var->m_Type = TW_TYPE_HELP_STRUCT; Var->m_Val.m_HelpStruct.m_StructType = static_cast<const CTwVarGroup *>(_ToAppend->m_Vars[i])->m_StructType; Var->m_ReadOnly = true; Var->m_NoSlider = true; } else if( !_ToAppend->m_Vars[i]->IsGroup() ) { Var->m_Type = TW_TYPE_SHORTCUT; Var->m_Val.m_Shortcut.m_Incr[0] = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i])->m_KeyIncr[0]; Var->m_Val.m_Shortcut.m_Incr[1] = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i])->m_KeyIncr[1]; Var->m_Val.m_Shortcut.m_Decr[0] = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i])->m_KeyDecr[0]; Var->m_Val.m_Shortcut.m_Decr[1] = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i])->m_KeyDecr[1]; Var->m_ReadOnly = static_cast<const CTwVarAtom *>(_ToAppend->m_Vars[i])->m_ReadOnly; Var->m_NoSlider = true; } else { Var->m_Type = TW_TYPE_HELP_GRP; Var->m_DontClip = true; Var->m_LeftMargin = (signed short)((_Level+2)*g_TwMgr->m_HelpBar->m_Font->m_CharWidth[(int)' ']); //Var->m_TopMargin = (signed short)(g_TwMgr->m_HelpBar->m_Font->m_CharHeight/2-2+2*(_Level-1)); Var->m_TopMargin = 2; if( Var->m_TopMargin>g_TwMgr->m_HelpBar->m_Font->m_CharHeight-3 ) Var->m_TopMargin = (signed short)(g_TwMgr->m_HelpBar->m_Font->m_CharHeight-3); Var->m_ReadOnly = true; } Var->SetDefaults(); _Grp->m_Vars.push_back(Var); size_t VarIndex = _Grp->m_Vars.size()-1; ++n; if( _ToAppend->m_Vars[i]->IsGroup() && static_cast<const CTwVarGroup *>(_ToAppend->m_Vars[i])->m_StructValuePtr==NULL ) { int nAppended = AppendHelp(_Grp, static_cast<const CTwVarGroup *>(_ToAppend->m_Vars[i]), _Level+1, _Width); if( _Grp->m_Vars.size()==VarIndex+1 ) { delete _Grp->m_Vars[VarIndex]; _Grp->m_Vars.resize(VarIndex); } else n += nAppended; } else if( _ToAppend->m_Vars[i]->m_Help.length()>0 ) n += AppendHelpString(_Grp, _ToAppend->m_Vars[i]->m_Help.c_str(), _Level+1, _Width, TW_TYPE_HELP_ATOM); } } return n; } static void CopyHierarchy(CTwVarGroup *dst, const CTwVarGroup *src) { if( dst==NULL || src==NULL ) return; dst->m_Name = src->m_Name; dst->m_Open = src->m_Open; dst->m_Visible = src->m_Visible; dst->m_ColorPtr = src->m_ColorPtr; dst->m_DontClip = src->m_DontClip; dst->m_IsRoot = src->m_IsRoot; dst->m_LeftMargin = src->m_LeftMargin; dst->m_TopMargin = src->m_TopMargin; dst->m_Vars.resize(src->m_Vars.size()); for(size_t i=0; i<src->m_Vars.size(); ++i) if( src->m_Vars[i]!=NULL && src->m_Vars[i]->IsGroup() ) { CTwVarGroup *grp = new CTwVarGroup; CopyHierarchy(grp, static_cast<const CTwVarGroup *>(src->m_Vars[i])); dst->m_Vars[i] = grp; } else dst->m_Vars[i] = NULL; } // copy the 'open' flag from original hierarchy to current hierarchy static void SynchroHierarchy(CTwVarGroup *cur, const CTwVarGroup *orig) { if( cur==NULL || orig==NULL ) return; if( strcmp(cur->m_Name.c_str(), orig->m_Name.c_str())==0 ) cur->m_Open = orig->m_Open; size_t j = 0; while( j<orig->m_Vars.size() && (orig->m_Vars[j]==NULL || !orig->m_Vars[j]->IsGroup()) ) ++j; for(size_t i=0; i<cur->m_Vars.size(); ++i) if( cur->m_Vars[i]!=NULL && cur->m_Vars[i]->IsGroup() && j<orig->m_Vars.size() && orig->m_Vars[j]!=NULL && orig->m_Vars[j]->IsGroup() ) { CTwVarGroup *curGrp = static_cast<CTwVarGroup *>(cur->m_Vars[i]); const CTwVarGroup *origGrp = static_cast<const CTwVarGroup *>(orig->m_Vars[j]); if( strcmp(curGrp->m_Name.c_str(), origGrp->m_Name.c_str())==0 ) { curGrp->m_Open = origGrp->m_Open; SynchroHierarchy(curGrp, origGrp); ++j; while( j<orig->m_Vars.size() && (orig->m_Vars[j]==NULL || !orig->m_Vars[j]->IsGroup()) ) ++j; } } } void CTwMgr::UpdateHelpBar() { if( m_HelpBar==NULL || m_HelpBar->IsMinimized() ) return; if( !m_HelpBarUpdateNow && (float)m_Timer.GetTime()<m_LastHelpUpdateTime+2 ) // update at most every 2 seconds return; m_HelpBarUpdateNow = false; m_LastHelpUpdateTime = (float)m_Timer.GetTime(); #ifdef _DEBUG //printf("UPDATE HELPBAR\n"); #endif // _DEBUG CTwVarGroup prevHierarchy; CopyHierarchy(&prevHierarchy, &m_HelpBar->m_VarRoot); TwRemoveAllVars(m_HelpBar); if( m_HelpBar->m_UpToDate ) m_HelpBar->Update(); if( m_Help.size()>0 ) AppendHelpString(&(m_HelpBar->m_VarRoot), m_Help.c_str(), 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); if( m_HelpBar->m_Help.size()>0 ) AppendHelpString(&(m_HelpBar->m_VarRoot), m_HelpBar->m_Help.c_str(), 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); AppendHelpString(&(m_HelpBar->m_VarRoot), "", 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_HEADER); for( size_t ib=0; ib<m_Bars.size(); ++ib ) if( m_Bars[ib]!=NULL && !(m_Bars[ib]->m_IsHelpBar) && m_Bars[ib]!=m_PopupBar && m_Bars[ib]->m_Visible ) { // Create a group CTwVarGroup *Grp = new CTwVarGroup; Grp->m_SummaryCallback = NULL; Grp->m_SummaryClientData = NULL; Grp->m_StructValuePtr = NULL; if( m_Bars[ib]->m_Label.size()<=0 ) Grp->m_Name = m_Bars[ib]->m_Name; else Grp->m_Name = m_Bars[ib]->m_Label; Grp->m_Open = true; Grp->m_ColorPtr = &(m_HelpBar->m_ColGrpText); m_HelpBar->m_VarRoot.m_Vars.push_back(Grp); if( m_Bars[ib]->m_Help.size()>0 ) AppendHelpString(Grp, m_Bars[ib]->m_Help.c_str(), 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_GRP); // Append variables (recursive) AppendHelp(Grp, &(m_Bars[ib]->m_VarRoot), 1, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0); // Append structures StructSet UsedStructs; InsertUsedStructs(UsedStructs, &(m_Bars[ib]->m_VarRoot)); CTwVarGroup *StructGrp = NULL; int MemberCount = 0; for( StructSet::iterator it=UsedStructs.begin(); it!=UsedStructs.end(); ++it ) { int idx = (*it) - TW_TYPE_STRUCT_BASE; if( idx>=0 && idx<(int)g_TwMgr->m_Structs.size() && g_TwMgr->m_Structs[idx].m_Name.length()>0 ) { if( StructGrp==NULL ) { StructGrp = new CTwVarGroup; StructGrp->m_StructType = TW_TYPE_HELP_STRUCT; // a special line background color will be used StructGrp->m_Name = "Structures"; StructGrp->m_Open = false; StructGrp->m_ColorPtr = &(m_HelpBar->m_ColStructText); //Grp->m_Vars.push_back(StructGrp); MemberCount = 0; } CTwVarAtom *Var = new CTwVarAtom; Var->m_Ptr = NULL; Var->m_Type = TW_TYPE_HELP_GRP; Var->m_DontClip = true; Var->m_LeftMargin = (signed short)(3*g_TwMgr->m_HelpBar->m_Font->m_CharWidth[(int)' ']); Var->m_TopMargin = 2; Var->m_ReadOnly = true; Var->m_NoSlider = true; Var->m_Name = '{'+g_TwMgr->m_Structs[idx].m_Name+'}'; StructGrp->m_Vars.push_back(Var); size_t structIndex = StructGrp->m_Vars.size()-1; if( g_TwMgr->m_Structs[idx].m_Help.size()>0 ) AppendHelpString(StructGrp, g_TwMgr->m_Structs[idx].m_Help.c_str(), 2, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0-2*Var->m_LeftMargin, TW_TYPE_HELP_ATOM); // Append struct members for( size_t im=0; im<g_TwMgr->m_Structs[idx].m_Members.size(); ++im ) { if( g_TwMgr->m_Structs[idx].m_Members[im].m_Help.size()>0 ) { CTwVarAtom *Var = new CTwVarAtom; Var->m_Ptr = NULL; Var->m_Type = TW_TYPE_SHORTCUT; Var->m_Val.m_Shortcut.m_Incr[0] = 0; Var->m_Val.m_Shortcut.m_Incr[1] = 0; Var->m_Val.m_Shortcut.m_Decr[0] = 0; Var->m_Val.m_Shortcut.m_Decr[1] = 0; Var->m_ReadOnly = false; Var->m_NoSlider = true; if( g_TwMgr->m_Structs[idx].m_Members[im].m_Label.length()>0 ) Var->m_Name = " "+g_TwMgr->m_Structs[idx].m_Members[im].m_Label; else Var->m_Name = " "+g_TwMgr->m_Structs[idx].m_Members[im].m_Name; StructGrp->m_Vars.push_back(Var); //if( g_TwMgr->m_Structs[idx].m_Members[im].m_Help.size()>0 ) AppendHelpString(StructGrp, g_TwMgr->m_Structs[idx].m_Members[im].m_Help.c_str(), 3, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0-4*Var->m_LeftMargin, TW_TYPE_HELP_ATOM); } } if( StructGrp->m_Vars.size()==structIndex+1 ) // remove struct from help { delete StructGrp->m_Vars[structIndex]; StructGrp->m_Vars.resize(structIndex); } else ++MemberCount; } } if( StructGrp!=NULL ) { if( MemberCount==1 ) StructGrp->m_Name = "Structure"; if( StructGrp->m_Vars.size()>0 ) Grp->m_Vars.push_back(StructGrp); else { delete StructGrp; StructGrp = NULL; } } } // Append RotoSlider CTwVarGroup *RotoGrp = new CTwVarGroup; RotoGrp->m_SummaryCallback = NULL; RotoGrp->m_SummaryClientData = NULL; RotoGrp->m_StructValuePtr = NULL; RotoGrp->m_Name = "RotoSlider"; RotoGrp->m_Open = false; RotoGrp->m_ColorPtr = &(m_HelpBar->m_ColGrpText); m_HelpBar->m_VarRoot.m_Vars.push_back(RotoGrp); AppendHelpString(RotoGrp, "The RotoSlider allows rapid editing of numerical values.", 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); AppendHelpString(RotoGrp, "To modify a numerical value, click on its label or on its roto [.] button, then move the mouse outside of the grey circle while keeping the mouse button pressed, and turn around the circle to increase or decrease the numerical value.", 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); AppendHelpString(RotoGrp, "The two grey lines depict the min and max bounds.", 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); AppendHelpString(RotoGrp, "Moving the mouse far form the circle allows precise increase or decrease, while moving near the circle allows fast increase or decrease.", 0, m_HelpBar->m_VarX2-m_HelpBar->m_VarX0, TW_TYPE_HELP_ATOM); SynchroHierarchy(&m_HelpBar->m_VarRoot, &prevHierarchy); m_HelpBarNotUpToDate = false; } // --------------------------------------------------------------------------- #if defined(ANT_WINDOWS) #include "res/TwXCursors.h" void CTwMgr::CreateCursors() { if( m_CursorsCreated ) return; m_CursorArrow = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_ARROW)); m_CursorMove = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZEALL)); m_CursorWE = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZEWE)); m_CursorNS = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZENS)); m_CursorTopRight = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZENESW)); m_CursorTopLeft = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZENWSE)); m_CursorBottomLeft = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZENESW)); m_CursorBottomRight = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_SIZENWSE)); m_CursorHelp = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_HELP)); m_CursorCross = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_CROSS)); m_CursorUpArrow = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_UPARROW)); m_CursorNo = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_NO)); m_CursorIBeam = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_IBEAM)); #ifdef IDC_HAND m_CursorHand = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_HAND)); #else m_CursorHand = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_UPARROW)); #endif int cur; HMODULE hdll = GetModuleHandle(ANT_TWEAK_BAR_DLL); if( hdll==NULL ) g_UseCurRsc = false; // force the use of built-in cursors (not using resources) if( g_UseCurRsc ) m_CursorCenter = ::LoadCursor(hdll, MAKEINTRESOURCE(IDC_CURSOR1+0)); else m_CursorCenter = PixmapCursor(0); if( m_CursorCenter==NULL ) m_CursorCenter = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_CROSS)); if( g_UseCurRsc ) m_CursorPoint = ::LoadCursor(hdll, MAKEINTRESOURCE(IDC_CURSOR1+1)); else m_CursorPoint = PixmapCursor(1); if( m_CursorPoint==NULL ) m_CursorPoint = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_CROSS)); for( cur=0; cur<NB_ROTO_CURSORS; ++cur ) { if( g_UseCurRsc ) m_RotoCursors[cur] = ::LoadCursor(hdll, MAKEINTRESOURCE(IDC_CURSOR1+2+cur)); else m_RotoCursors[cur] = PixmapCursor(cur+2); if( m_RotoCursors[cur]==NULL ) m_RotoCursors[cur] = ::LoadCursor(NULL ,MAKEINTRESOURCE(IDC_CROSS)); } m_CursorsCreated = true; } CTwMgr::CCursor CTwMgr::PixmapCursor(int _CurIdx) { int x, y; unsigned char mask[32*4]; unsigned char pict[32*4]; for( y=0; y<32; ++y ) { mask[y*4+0] = pict[y*4+0] = 0; mask[y*4+1] = pict[y*4+1] = 0; mask[y*4+2] = pict[y*4+2] = 0; mask[y*4+3] = pict[y*4+3] = 0; for( x=0; x<32; ++x ) { mask[y*4+x/8] |= (((unsigned int)(g_CurMask[_CurIdx][x+y*32]))<<(7-(x%8))); pict[y*4+x/8] |= (((unsigned int)(g_CurPict[_CurIdx][x+y*32]))<<(7-(x%8))); } } unsigned char ands[32*4]; unsigned char xors[32*4]; for( y=0; y<32*4; ++y ) { ands[y] = ~mask[y]; xors[y] = pict[y]; } HMODULE hdll = GetModuleHandle(ANT_TWEAK_BAR_DLL); CCursor cursor = ::CreateCursor(hdll, g_CurHot[_CurIdx][0], g_CurHot[_CurIdx][1], 32, 32, ands, xors); return cursor; } void CTwMgr::FreeCursors() { if( !g_UseCurRsc ) { if( m_CursorCenter!=NULL ) { ::DestroyCursor(m_CursorCenter); m_CursorCenter = NULL; } if( m_CursorPoint!=NULL ) { ::DestroyCursor(m_CursorPoint); m_CursorPoint = NULL; } for( int cur=0; cur<NB_ROTO_CURSORS; ++cur ) if( m_RotoCursors[cur]!=NULL ) { ::DestroyCursor(m_RotoCursors[cur]); m_RotoCursors[cur] = NULL; } } m_CursorsCreated = false; } void CTwMgr::SetCursor(CTwMgr::CCursor _Cursor) { if( m_CursorsCreated ) { CURSORINFO ci; memset(&ci, 0, sizeof(ci)); ci.cbSize = sizeof(ci); BOOL ok = ::GetCursorInfo(&ci); if( ok && (ci.flags & CURSOR_SHOWING) ) ::SetCursor(_Cursor); } } #elif defined(ANT_OSX) #include "res/TwXCursors.h" CTwMgr::CCursor CTwMgr::PixmapCursor(int _CurIdx) { unsigned char *data; int x,y; NSBitmapImageRep *imgr = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: NULL pixelsWide: 32 pixelsHigh: 32 bitsPerSample: 1 samplesPerPixel: 2 hasAlpha: YES isPlanar: NO colorSpaceName: NSCalibratedWhiteColorSpace bitmapFormat: NSAlphaNonpremultipliedBitmapFormat bytesPerRow: 8 bitsPerPixel: 2 ]; data = [imgr bitmapData]; memset(data,0x0,32*8); for (y=0;y<32;y++) { for (x=0;x<32;x++) { //printf("%d",g_CurMask[_CurIdx][x+y*32]); data[(x>>2) + y*8] |= (unsigned char)(g_CurPict[_CurIdx][x+y*32] << 2*(3-(x&3))+1); //turn whiteon data[(x>>2) + y*8] |= (unsigned char)(g_CurMask[_CurIdx][x+y*32] << 2*(3-(x&3))); //turn the alpha all the way up } //printf("\n"); } NSImage *img = [[NSImage alloc] initWithSize: [imgr size]]; [img addRepresentation: imgr]; NSCursor *cur = [[NSCursor alloc] initWithImage: img hotSpot: NSMakePoint(g_CurHot[_CurIdx][0],g_CurHot[_CurIdx][1])]; [imgr autorelease]; [img autorelease]; if (cur) return cur; else return [NSCursor arrowCursor]; } void CTwMgr::CreateCursors() { if (m_CursorsCreated) return; m_CursorArrow = [[NSCursor arrowCursor] retain]; m_CursorMove = [[NSCursor crosshairCursor] retain]; m_CursorWE = [[NSCursor resizeLeftRightCursor] retain]; m_CursorNS = [[NSCursor resizeUpDownCursor] retain]; m_CursorTopRight = [[NSCursor arrowCursor] retain]; //osx not have one m_CursorTopLeft = [[NSCursor arrowCursor] retain]; //osx not have one m_CursorBottomRight = [[NSCursor arrowCursor] retain]; //osx not have one m_CursorBottomLeft = [[NSCursor arrowCursor] retain]; //osx not have one m_CursorHelp = [[NSCursor arrowCursor] retain]; //osx not have one m_CursorHand = [[NSCursor pointingHandCursor] retain]; m_CursorCross = [[NSCursor arrowCursor] retain]; m_CursorUpArrow = [[NSCursor arrowCursor] retain]; m_CursorNo = [[NSCursor arrowCursor] retain]; m_CursorIBeam = [[NSCursor IBeamCursor] retain]; for (int i=0;i<NB_ROTO_CURSORS; i++) { m_RotoCursors[i] = [PixmapCursor(i+2) retain]; } m_CursorCenter = [PixmapCursor(0) retain]; m_CursorPoint = [PixmapCursor(1) retain]; m_CursorsCreated = true; } void CTwMgr::FreeCursors() { [m_CursorArrow release]; [m_CursorMove release]; [m_CursorWE release]; [m_CursorNS release]; [m_CursorTopRight release]; [m_CursorTopLeft release]; [m_CursorBottomRight release]; [m_CursorBottomLeft release]; [m_CursorHelp release]; [m_CursorHand release]; [m_CursorCross release]; [m_CursorUpArrow release]; [m_CursorNo release]; [m_CursorIBeam release]; for( int i=0; i<NB_ROTO_CURSORS; ++i ) [m_RotoCursors[i] release]; [m_CursorCenter release]; [m_CursorPoint release]; m_CursorsCreated = false; } void CTwMgr::SetCursor(CTwMgr::CCursor _Cursor) { if (m_CursorsCreated && _Cursor) { [_Cursor set]; } } #elif defined(ANT_UNIX) #include "res/TwXCursors.h" static XErrorHandler s_PrevErrorHandler = NULL; static int InactiveErrorHandler(Display *display, XErrorEvent *err) { fprintf(stderr, "Ignoring Xlib error: error code %d request code %d\n", err->error_code, err->request_code); // No exit! return 0 ; } static void IgnoreXErrors() { if( g_TwMgr!=NULL && g_TwMgr->m_CurrentXDisplay==glXGetCurrentDisplay() ) { XFlush(g_TwMgr->m_CurrentXDisplay); XSync(g_TwMgr->m_CurrentXDisplay, False); } s_PrevErrorHandler = XSetErrorHandler(InactiveErrorHandler); } static void RestoreXErrors() { if( g_TwMgr!=NULL && g_TwMgr->m_CurrentXDisplay==glXGetCurrentDisplay() ) { XFlush(g_TwMgr->m_CurrentXDisplay); XSync(g_TwMgr->m_CurrentXDisplay, False); } XSetErrorHandler(s_PrevErrorHandler); } CTwMgr::CCursor CTwMgr::PixmapCursor(int _CurIdx) { if( !m_CurrentXDisplay || !m_CurrentXWindow ) return XC_left_ptr; IgnoreXErrors(); XColor black, white, exact; Colormap colmap = DefaultColormap(m_CurrentXDisplay, DefaultScreen(m_CurrentXDisplay)); Status s1 = XAllocNamedColor(m_CurrentXDisplay, colmap, "black", &black, &exact); Status s2 = XAllocNamedColor(m_CurrentXDisplay, colmap, "white", &white, &exact); if( s1==0 || s2==0 ) return XC_left_ptr; // cannot allocate colors! int x, y; unsigned int mask[32]; unsigned int pict[32]; for( y=0; y<32; ++y ) { mask[y] = pict[y] = 0; for( x=0; x<32; ++x ) { mask[y] |= (((unsigned int)(g_CurMask[_CurIdx][x+y*32]))<<x); pict[y] |= (((unsigned int)(g_CurPict[_CurIdx][x+y*32]))<<x); } } Pixmap maskPix = XCreateBitmapFromData(m_CurrentXDisplay, m_CurrentXWindow, (char*)mask, 32, 32); Pixmap pictPix = XCreateBitmapFromData(m_CurrentXDisplay, m_CurrentXWindow, (char*)pict, 32, 32); Cursor cursor = XCreatePixmapCursor(m_CurrentXDisplay, pictPix, maskPix, &white, &black, g_CurHot[_CurIdx][0], g_CurHot[_CurIdx][1]); XFreePixmap(m_CurrentXDisplay, maskPix); XFreePixmap(m_CurrentXDisplay, pictPix); RestoreXErrors(); if( cursor!=0 ) return cursor; else return XC_left_ptr; } void CTwMgr::CreateCursors() { if( m_CursorsCreated || !m_CurrentXDisplay || !m_CurrentXWindow ) return; IgnoreXErrors(); m_CursorArrow = XCreateFontCursor(m_CurrentXDisplay, XC_left_ptr); m_CursorMove = XCreateFontCursor(m_CurrentXDisplay, XC_plus); m_CursorWE = XCreateFontCursor(m_CurrentXDisplay, XC_left_side); m_CursorNS = XCreateFontCursor(m_CurrentXDisplay, XC_top_side); m_CursorTopRight= XCreateFontCursor(m_CurrentXDisplay, XC_top_right_corner); m_CursorTopLeft = XCreateFontCursor(m_CurrentXDisplay, XC_top_left_corner); m_CursorBottomRight = XCreateFontCursor(m_CurrentXDisplay, XC_bottom_right_corner); m_CursorBottomLeft = XCreateFontCursor(m_CurrentXDisplay, XC_bottom_left_corner); m_CursorHelp = XCreateFontCursor(m_CurrentXDisplay, XC_question_arrow); m_CursorHand = XCreateFontCursor(m_CurrentXDisplay, XC_hand1); m_CursorCross = XCreateFontCursor(m_CurrentXDisplay, XC_X_cursor); m_CursorUpArrow = XCreateFontCursor(m_CurrentXDisplay, XC_center_ptr); m_CursorNo = XCreateFontCursor(m_CurrentXDisplay, XC_left_ptr); m_CursorIBeam = XCreateFontCursor(m_CurrentXDisplay, XC_xterm); for( int i=0; i<NB_ROTO_CURSORS; ++i ) { m_RotoCursors[i] = PixmapCursor(i+2); } m_CursorCenter = PixmapCursor(0); m_CursorPoint = PixmapCursor(1); m_CursorsCreated = true; RestoreXErrors(); } void CTwMgr::FreeCursors() { IgnoreXErrors(); XFreeCursor(m_CurrentXDisplay, m_CursorArrow); XFreeCursor(m_CurrentXDisplay, m_CursorMove); XFreeCursor(m_CurrentXDisplay, m_CursorWE); XFreeCursor(m_CurrentXDisplay, m_CursorNS); XFreeCursor(m_CurrentXDisplay, m_CursorTopRight); XFreeCursor(m_CurrentXDisplay, m_CursorTopLeft); XFreeCursor(m_CurrentXDisplay, m_CursorBottomRight); XFreeCursor(m_CurrentXDisplay, m_CursorBottomLeft); XFreeCursor(m_CurrentXDisplay, m_CursorHelp); XFreeCursor(m_CurrentXDisplay, m_CursorHand); XFreeCursor(m_CurrentXDisplay, m_CursorCross); XFreeCursor(m_CurrentXDisplay, m_CursorUpArrow); XFreeCursor(m_CurrentXDisplay, m_CursorNo); for( int i=0; i<NB_ROTO_CURSORS; ++i ) XFreeCursor(m_CurrentXDisplay, m_RotoCursors[i]); XFreeCursor(m_CurrentXDisplay, m_CursorCenter); XFreeCursor(m_CurrentXDisplay, m_CursorPoint); m_CursorsCreated = false; RestoreXErrors(); } void CTwMgr::SetCursor(CTwMgr::CCursor _Cursor) { if( m_CursorsCreated && m_CurrentXDisplay && m_CurrentXWindow ) { Display *dpy = glXGetCurrentDisplay(); if( dpy==g_TwMgr->m_CurrentXDisplay ) { Window wnd = glXGetCurrentDrawable(); if( wnd!=g_TwMgr->m_CurrentXWindow ) { FreeCursors(); g_TwMgr->m_CurrentXWindow = wnd; CreateCursors(); // now _Cursor is not a valid cursor ID. } else { IgnoreXErrors(); XDefineCursor(m_CurrentXDisplay, m_CurrentXWindow, _Cursor); RestoreXErrors(); } } } } #endif //defined(ANT_UNIX) // --------------------------------------------------------------------------- void ANT_CALL TwCopyCDStringToClientFunc(TwCopyCDStringToClient copyCDStringToClientFunc) { g_InitCopyCDStringToClient = copyCDStringToClientFunc; if( g_TwMgr!=NULL ) g_TwMgr->m_CopyCDStringToClient = copyCDStringToClientFunc; } void ANT_CALL TwCopyCDStringToLibrary(char **destinationLibraryStringPtr, const char *sourceClientString) { if( g_TwMgr==NULL ) { if( destinationLibraryStringPtr!=NULL ) *destinationLibraryStringPtr = const_cast<char *>(sourceClientString); return; } // static buffer to store sourceClientString copy associated to sourceClientString pointer std::vector<char>& Buf = g_TwMgr->m_CDStdStringCopyBuffers[(void *)sourceClientString]; size_t len = (sourceClientString!=NULL) ? strlen(sourceClientString) : 0; if( Buf.size()<len+1 ) Buf.resize(len+128); // len + some margin char *SrcStrCopy = &(Buf[0]); SrcStrCopy[0] = '\0'; if( sourceClientString!=NULL ) memcpy(SrcStrCopy, sourceClientString, len+1); SrcStrCopy[len] = '\0'; if( destinationLibraryStringPtr!=NULL ) *destinationLibraryStringPtr = SrcStrCopy; } void ANT_CALL TwCopyStdStringToClientFunc(TwCopyStdStringToClient copyStdStringToClientFunc) { g_InitCopyStdStringToClient = copyStdStringToClientFunc; if( g_TwMgr!=NULL ) g_TwMgr->m_CopyStdStringToClient = copyStdStringToClientFunc; } void ANT_CALL TwCopyStdStringToLibrary(std::string& destLibraryString, const std::string& srcClientString) { /* // check if destLibraryString should be initialized char *Mem = (char *)&destLibraryString; bool Init = true; for( int i=0; i<sizeof(std::string) && Init; ++i ) if( Mem[i]!=0 ) Init = false; // has already been initialized assert( !Init ); // ::new(&destLibraryString) std::string; // copy string destLibraryString = srcClientString; */ if( g_TwMgr==NULL ) return; CTwMgr::CLibStdString srcLibString; // Convert VC++ Debug/Release std::string srcLibString.FromClient(srcClientString); const char *SrcStr = srcLibString.ToLib().c_str(); const char **DstStrPtr = (const char **)&destLibraryString; // SrcStr can be defined locally by the caller, so we need to copy it // ( *DstStrPtr = copy of SrcStr ) // static buffer to store srcClientString copy associated to srcClientString pointer std::vector<char>& Buf = g_TwMgr->m_CDStdStringCopyBuffers[(void *)&srcClientString]; size_t len = strlen(SrcStr); if( Buf.size()<len+1 ) Buf.resize(len+128); // len + some margin char *SrcStrCopy = &(Buf[0]); memcpy(SrcStrCopy, SrcStr, len+1); SrcStrCopy[len] = '\0'; *DstStrPtr = SrcStrCopy; //*(const char **)&destLibraryString = srcClientString.c_str(); } // --------------------------------------------------------------------------- bool CRect::Subtract(const CRect& _Rect, vector<CRect>& _OutRects) const { if( Empty() ) return false; if( _Rect.Empty() || _Rect.Y>=Y+H || _Rect.Y+_Rect.H<=Y || _Rect.X>=X+W || _Rect.X+_Rect.W<=X ) { _OutRects.push_back(*this); return true; } bool Ret = false; int Y0 = Y; int Y1 = Y+H-1; if( _Rect.Y>Y ) { Y0 = _Rect.Y; _OutRects.push_back(CRect(X, Y, W, Y0-Y+1)); Ret = true; } if( _Rect.Y+_Rect.H<Y+H ) { Y1 = _Rect.Y+_Rect.H; _OutRects.push_back(CRect(X, Y1, W, Y+H-Y1)); Ret = true; } int X0 = X; int X1 = X+W-1; if( _Rect.X>X ) { X0 = _Rect.X; //-2; _OutRects.push_back(CRect(X, Y0, X0-X+1, Y1-Y0+1)); Ret = true; } if( _Rect.X+_Rect.W<X+W ) { X1 = _Rect.X+_Rect.W; //-1; _OutRects.push_back(CRect(X1, Y0, X+W-X1, Y1-Y0+1)); Ret = true; } return Ret; } bool CRect::Subtract(const vector<CRect>& _Rects, vector<CRect>& _OutRects) const { _OutRects.clear(); size_t i, j, NbRects = _Rects.size(); if( NbRects==0 ) { _OutRects.push_back(*this); return true; } else { vector<CRect> TmpRects; Subtract(_Rects[0], _OutRects); for( i=1; i<NbRects; i++) { for( j=0; j<_OutRects.size(); j++ ) _OutRects[j].Subtract(_Rects[i], TmpRects); _OutRects.swap(TmpRects); TmpRects.clear(); } return _OutRects.empty(); } } // ---------------------------------------------------------------------------
; A172178: 99n+1. ; 1,100,199,298,397,496,595,694,793,892,991,1090,1189,1288,1387,1486,1585,1684,1783,1882,1981,2080,2179,2278,2377,2476,2575,2674,2773,2872,2971,3070,3169,3268,3367,3466,3565,3664,3763,3862,3961,4060,4159,4258 mul $0,99 add $0,1
; Title: Win32 Network Shell ; Platforms: Windows NT 4.0, Windows 2000, Windows XP, Windows 2003 ; Author: hdm[at]metasploit.com [BITS 32] %include "win32_stage_boot_bind.asm" %include "win32_stage_shell.asm"
; A070361: a(n) = 3^n mod 41. ; 1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27,40,38,32,14,1,3,9,27 mov $1,1 mov $2,$0 lpb $2 mul $1,3 mod $1,41 sub $2,1 lpe mov $0,$1
// Copyright 2017 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "bucket/BucketInputIterator.h" #include "bucket/BucketTests.h" #include "herder/Herder.h" #include "herder/HerderImpl.h" #include "herder/LedgerCloseData.h" #include "herder/Upgrades.h" #include "history/HistoryArchiveManager.h" #include "history/test/HistoryTestsUtils.h" #include "ledger/LedgerTxn.h" #include "ledger/LedgerTxnEntry.h" #include "ledger/LedgerTxnHeader.h" #include "ledger/TrustLineWrapper.h" #include "lib/catch.hpp" #include "simulation/Simulation.h" #include "test/TestExceptions.h" #include "test/TestMarket.h" #include "test/TestUtils.h" #include "test/test.h" #include "transactions/SignatureUtils.h" #include "transactions/SponsorshipUtils.h" #include "transactions/TransactionUtils.h" #include "util/StatusManager.h" #include "util/Timer.h" #include <fmt/format.h> #include <optional> #include <xdrpp/marshal.h> using namespace stellar; using namespace stellar::txtest; struct LedgerUpgradeableData { LedgerUpgradeableData() { } LedgerUpgradeableData(uint32_t v, uint32_t f, uint32_t txs, uint32_t r) : ledgerVersion(v), baseFee(f), maxTxSetSize(txs), baseReserve(r) { } uint32_t ledgerVersion{0}; uint32_t baseFee{0}; uint32_t maxTxSetSize{0}; uint32_t baseReserve{0}; }; struct LedgerUpgradeNode { LedgerUpgradeableData desiredUpgrades; VirtualClock::system_time_point preferredUpgradeDatetime; }; struct LedgerUpgradeCheck { VirtualClock::system_time_point time; std::vector<LedgerUpgradeableData> expected; }; namespace { void simulateUpgrade(std::vector<LedgerUpgradeNode> const& nodes, std::vector<LedgerUpgradeCheck> const& checks, bool checkUpgradeStatus = false) { auto networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); historytestutils::TmpDirHistoryConfigurator configurator{}; auto simulation = std::make_shared<Simulation>(Simulation::OVER_LOOPBACK, networkID); simulation->setCurrentVirtualTime(genesis(0, 0)); // configure nodes auto keys = std::vector<SecretKey>{}; auto configs = std::vector<Config>{}; for (size_t i = 0; i < nodes.size(); i++) { keys.push_back( SecretKey::fromSeed(sha256("NODE_SEED_" + std::to_string(i)))); configs.push_back(simulation->newConfig()); // disable upgrade from config configs.back().TESTING_UPGRADE_DATETIME = VirtualClock::system_time_point(); configs.back().USE_CONFIG_FOR_GENESIS = false; // first node can write to history, all can read configurator.configure(configs.back(), i == 0); } // first two only depend on each other // this allows to test for v-blocking properties // on the 3rd node auto qSet = SCPQuorumSet{}; qSet.threshold = 2; qSet.validators.push_back(keys[0].getPublicKey()); qSet.validators.push_back(keys[1].getPublicKey()); qSet.validators.push_back(keys[2].getPublicKey()); auto setUpgrade = [](std::optional<uint32>& o, uint32 v) { o = std::make_optional<uint32>(v); }; // create nodes for (size_t i = 0; i < nodes.size(); i++) { auto app = simulation->addNode(keys[i], qSet, &configs[i]); auto& upgradeTime = nodes[i].preferredUpgradeDatetime; if (upgradeTime.time_since_epoch().count() != 0) { auto& du = nodes[i].desiredUpgrades; Upgrades::UpgradeParameters upgrades; setUpgrade(upgrades.mBaseFee, du.baseFee); setUpgrade(upgrades.mBaseReserve, du.baseReserve); setUpgrade(upgrades.mMaxTxSetSize, du.maxTxSetSize); setUpgrade(upgrades.mProtocolVersion, du.ledgerVersion); upgrades.mUpgradeTime = upgradeTime; app->getHerder().setUpgrades(upgrades); } } simulation->getNode(keys[0].getPublicKey()) ->getHistoryArchiveManager() .initializeHistoryArchive("test"); for (size_t i = 0; i < nodes.size(); i++) { for (size_t j = i + 1; j < nodes.size(); j++) { simulation->addPendingConnection(keys[i].getPublicKey(), keys[j].getPublicKey()); } } simulation->startAllNodes(); auto statesMatch = [&](std::vector<LedgerUpgradeableData> const& state) { for (size_t i = 0; i < nodes.size(); i++) { auto const& node = simulation->getNode(keys[i].getPublicKey()); REQUIRE(node->getLedgerManager() .getLastClosedLedgerHeader() .header.ledgerVersion == state[i].ledgerVersion); REQUIRE(node->getLedgerManager().getLastTxFee() == state[i].baseFee); REQUIRE(node->getLedgerManager().getLastMaxTxSetSize() == state[i].maxTxSetSize); REQUIRE(node->getLedgerManager().getLastReserve() == state[i].baseReserve); } }; for (auto const& result : checks) { simulation->crankUntil(result.time, false); statesMatch(result.expected); } auto allSynced = [&]() { return std::all_of( std::begin(keys), std::end(keys), [&](SecretKey const& key) { auto const& node = simulation->getNode(key.getPublicKey()); return node->getLedgerManager().getState() == LedgerManager::LM_SYNCED_STATE; }); }; // all nodes are synced as there was no disagreement about upgrades REQUIRE(allSynced()); if (checkUpgradeStatus) { // at least one node should show message that it has some // pending upgrades REQUIRE(std::any_of( std::begin(keys), std::end(keys), [&](SecretKey const& key) { auto const& node = simulation->getNode(key.getPublicKey()); return !node->getStatusManager() .getStatusMessage(StatusCategory::REQUIRES_UPGRADES) .empty(); })); } } LedgerUpgrade makeProtocolVersionUpgrade(int version) { auto result = LedgerUpgrade{LEDGER_UPGRADE_VERSION}; result.newLedgerVersion() = version; return result; } LedgerUpgrade makeBaseFeeUpgrade(int baseFee) { auto result = LedgerUpgrade{LEDGER_UPGRADE_BASE_FEE}; result.newBaseFee() = baseFee; return result; } LedgerUpgrade makeTxCountUpgrade(int txCount) { auto result = LedgerUpgrade{LEDGER_UPGRADE_MAX_TX_SET_SIZE}; result.newMaxTxSetSize() = txCount; return result; } LedgerUpgrade makeFlagsUpgrade(int flags) { auto result = LedgerUpgrade{LEDGER_UPGRADE_FLAGS}; result.newFlags() = flags; return result; } void testListUpgrades(VirtualClock::system_time_point preferredUpgradeDatetime, bool shouldListAny) { auto cfg = getTestConfig(); cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION = 10; cfg.TESTING_UPGRADE_DESIRED_FEE = 100; cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE = 50; cfg.TESTING_UPGRADE_RESERVE = 100000000; cfg.TESTING_UPGRADE_DATETIME = preferredUpgradeDatetime; auto header = LedgerHeader{}; header.ledgerVersion = cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION; header.baseFee = cfg.TESTING_UPGRADE_DESIRED_FEE; header.baseReserve = cfg.TESTING_UPGRADE_RESERVE; header.maxTxSetSize = cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE; header.scpValue.closeTime = VirtualClock::to_time_t(genesis(0, 0)); auto protocolVersionUpgrade = makeProtocolVersionUpgrade(cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION); auto baseFeeUpgrade = makeBaseFeeUpgrade(cfg.TESTING_UPGRADE_DESIRED_FEE); auto txCountUpgrade = makeTxCountUpgrade(cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE); auto baseReserveUpgrade = makeBaseReserveUpgrade(cfg.TESTING_UPGRADE_RESERVE); SECTION("protocol version upgrade needed") { header.ledgerVersion--; auto upgrades = Upgrades{cfg}.createUpgradesFor(header); auto expected = shouldListAny ? std::vector<LedgerUpgrade>{protocolVersionUpgrade} : std::vector<LedgerUpgrade>{}; REQUIRE(upgrades == expected); } SECTION("base fee upgrade needed") { header.baseFee /= 2; auto upgrades = Upgrades{cfg}.createUpgradesFor(header); auto expected = shouldListAny ? std::vector<LedgerUpgrade>{baseFeeUpgrade} : std::vector<LedgerUpgrade>{}; REQUIRE(upgrades == expected); } SECTION("tx count upgrade needed") { header.maxTxSetSize /= 2; auto upgrades = Upgrades{cfg}.createUpgradesFor(header); auto expected = shouldListAny ? std::vector<LedgerUpgrade>{txCountUpgrade} : std::vector<LedgerUpgrade>{}; REQUIRE(upgrades == expected); } SECTION("base reserve upgrade needed") { header.baseReserve /= 2; auto upgrades = Upgrades{cfg}.createUpgradesFor(header); auto expected = shouldListAny ? std::vector<LedgerUpgrade>{baseReserveUpgrade} : std::vector<LedgerUpgrade>{}; REQUIRE(upgrades == expected); } SECTION("all upgrades needed") { header.ledgerVersion--; header.baseFee /= 2; header.maxTxSetSize /= 2; header.baseReserve /= 2; auto upgrades = Upgrades{cfg}.createUpgradesFor(header); auto expected = shouldListAny ? std::vector<LedgerUpgrade>{protocolVersionUpgrade, baseFeeUpgrade, txCountUpgrade, baseReserveUpgrade} : std::vector<LedgerUpgrade>{}; REQUIRE(upgrades == expected); } } void testValidateUpgrades(VirtualClock::system_time_point preferredUpgradeDatetime, bool canBeValid) { auto cfg = getTestConfig(); cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION = 10; cfg.TESTING_UPGRADE_DESIRED_FEE = 100; cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE = 50; cfg.TESTING_UPGRADE_RESERVE = 100000000; cfg.TESTING_UPGRADE_DATETIME = preferredUpgradeDatetime; auto checkTime = VirtualClock::to_time_t(genesis(0, 0)); auto ledgerUpgradeType = LedgerUpgradeType{}; // a ledgerheader used for base cases LedgerHeader baseLH; baseLH.ledgerVersion = 8; baseLH.scpValue.closeTime = checkTime; auto checkWith = [&](bool nomination) { SECTION("invalid upgrade data") { REQUIRE(!Upgrades{cfg}.isValid(UpgradeType{}, ledgerUpgradeType, nomination, cfg, baseLH)); } SECTION("version") { if (nomination) { REQUIRE(canBeValid == Upgrades{cfg}.isValid( toUpgradeType(makeProtocolVersionUpgrade(10)), ledgerUpgradeType, nomination, cfg, baseLH)); } else { REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeProtocolVersionUpgrade(10)), ledgerUpgradeType, nomination, cfg, baseLH)); } // 10 is queued, so this upgrade is only valid when not nominating bool v9Upgrade = Upgrades{cfg}.isValid( toUpgradeType(makeProtocolVersionUpgrade(9)), ledgerUpgradeType, nomination, cfg, baseLH); if (nomination) { REQUIRE(!v9Upgrade); } else { REQUIRE(v9Upgrade); } // rollback not allowed REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeProtocolVersionUpgrade(7)), ledgerUpgradeType, nomination, cfg, baseLH)); // version is not supported REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeProtocolVersionUpgrade(11)), ledgerUpgradeType, nomination, cfg, baseLH)); } SECTION("base fee") { if (nomination) { REQUIRE(canBeValid == Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(100)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(99)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(101)), ledgerUpgradeType, nomination, cfg, baseLH)); } else { REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(100)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(99)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseFeeUpgrade(101)), ledgerUpgradeType, nomination, cfg, baseLH)); } REQUIRE(!Upgrades{cfg}.isValid(toUpgradeType(makeBaseFeeUpgrade(0)), ledgerUpgradeType, nomination, cfg, baseLH)); } SECTION("tx count") { if (nomination) { REQUIRE(canBeValid == Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(50)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(49)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(51)), ledgerUpgradeType, nomination, cfg, baseLH)); } else { REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(50)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(49)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeTxCountUpgrade(51)), ledgerUpgradeType, nomination, cfg, baseLH)); } auto cfg0TxSize = cfg; cfg0TxSize.TESTING_UPGRADE_MAX_TX_SET_SIZE = 0; REQUIRE(canBeValid == Upgrades{cfg0TxSize}.isValid( toUpgradeType(makeTxCountUpgrade(0)), ledgerUpgradeType, nomination, cfg, baseLH)); } SECTION("reserve") { if (nomination) { REQUIRE(canBeValid == Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(100000000)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(99999999)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(100000001)), ledgerUpgradeType, nomination, cfg, baseLH)); } else { REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(100000000)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(99999999)), ledgerUpgradeType, nomination, cfg, baseLH)); REQUIRE(Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(100000001)), ledgerUpgradeType, nomination, cfg, baseLH)); } REQUIRE(!Upgrades{cfg}.isValid( toUpgradeType(makeBaseReserveUpgrade(0)), ledgerUpgradeType, nomination, cfg, baseLH)); } }; checkWith(true); checkWith(false); } } TEST_CASE("list upgrades when no time set for upgrade", "[upgrades]") { testListUpgrades({}, true); } TEST_CASE("list upgrades just before upgrade time", "[upgrades]") { testListUpgrades(genesis(0, 1), false); } TEST_CASE("list upgrades at upgrade time", "[upgrades]") { testListUpgrades(genesis(0, 0), true); } TEST_CASE("validate upgrades when no time set for upgrade", "[upgrades]") { testValidateUpgrades({}, true); } TEST_CASE("validate upgrades just before upgrade time", "[upgrades]") { testValidateUpgrades(genesis(0, 1), false); } TEST_CASE("validate upgrades at upgrade time", "[upgrades]") { testValidateUpgrades(genesis(0, 0), true); } TEST_CASE("Ledger Manager applies upgrades properly", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(0); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); auto const& lcl = app->getLedgerManager().getLastClosedLedgerHeader(); REQUIRE(lcl.header.ledgerVersion == LedgerManager::GENESIS_LEDGER_VERSION); REQUIRE(lcl.header.baseFee == LedgerManager::GENESIS_LEDGER_BASE_FEE); REQUIRE(lcl.header.maxTxSetSize == LedgerManager::GENESIS_LEDGER_MAX_TX_SIZE); REQUIRE(lcl.header.baseReserve == LedgerManager::GENESIS_LEDGER_BASE_RESERVE); SECTION("ledger version") { REQUIRE(executeUpgrade(*app, makeProtocolVersionUpgrade( cfg.LEDGER_PROTOCOL_VERSION)) .ledgerVersion == cfg.LEDGER_PROTOCOL_VERSION); } SECTION("base fee") { REQUIRE(executeUpgrade(*app, makeBaseFeeUpgrade(1000)).baseFee == 1000); } SECTION("max tx") { REQUIRE(executeUpgrade(*app, makeTxCountUpgrade(1300)).maxTxSetSize == 1300); } SECTION("base reserve") { REQUIRE( executeUpgrade(*app, makeBaseReserveUpgrade(1000)).baseReserve == 1000); } SECTION("all") { auto header = executeUpgrades( *app, {toUpgradeType( makeProtocolVersionUpgrade(cfg.LEDGER_PROTOCOL_VERSION)), toUpgradeType(makeBaseFeeUpgrade(1000)), toUpgradeType(makeTxCountUpgrade(1300)), toUpgradeType(makeBaseReserveUpgrade(1000))}); REQUIRE(header.ledgerVersion == cfg.LEDGER_PROTOCOL_VERSION); REQUIRE(header.baseFee == 1000); REQUIRE(header.maxTxSetSize == 1300); REQUIRE(header.baseReserve == 1000); } } TEST_CASE("upgrade to version 10", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(0); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); executeUpgrade(*app, makeProtocolVersionUpgrade(9)); auto& lm = app->getLedgerManager(); auto txFee = lm.getLastTxFee(); auto const& lcl = lm.getLastClosedLedgerHeader(); auto txSet = std::make_shared<TxSetFrame const>(lcl.hash); auto root = TestAccount::createRoot(*app); auto issuer = root.create("issuer", lm.getLastMinBalance(0) + 100 * txFee); auto native = txtest::makeNativeAsset(); auto cur1 = issuer.asset("CUR1"); auto cur2 = issuer.asset("CUR2"); auto market = TestMarket{*app}; auto executeUpgrade = [&] { REQUIRE(::executeUpgrade(*app, makeProtocolVersionUpgrade(10)) .ledgerVersion == 10); }; auto getLiabilities = [&](TestAccount& acc) { Liabilities res; LedgerTxn ltx(app->getLedgerTxnRoot()); auto account = stellar::loadAccount(ltx, acc.getPublicKey()); res.selling = getSellingLiabilities(ltx.loadHeader(), account); res.buying = getBuyingLiabilities(ltx.loadHeader(), account); return res; }; auto getAssetLiabilities = [&](TestAccount& acc, Asset const& asset) { Liabilities res; if (acc.hasTrustLine(asset)) { LedgerTxn ltx(app->getLedgerTxnRoot()); auto trust = stellar::loadTrustLine(ltx, acc.getPublicKey(), asset); res.selling = trust.getSellingLiabilities(ltx.loadHeader()); res.buying = trust.getBuyingLiabilities(ltx.loadHeader()); } return res; }; auto createOffer = [&](TestAccount& acc, Asset const& selling, Asset const& buying, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{2, 1}, 1000}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; SECTION("one account, multiple offers, one asset pair") { SECTION("valid native") { auto a1 = root.create("A", lm.getLastMinBalance(5) + 2000 + 5 * txFee); a1.changeTrust(cur1, 6000); issuer.pay(a1, cur1, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 2000}); } SECTION("invalid selling native") { auto a1 = root.create("A", lm.getLastMinBalance(5) + 1000 + 5 * txFee); a1.changeTrust(cur1, 6000); issuer.pay(a1, cur1, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 2000}); } SECTION("invalid buying native") { auto createOfferQuantity = [&](TestAccount& acc, Asset const& selling, Asset const& buying, int64_t quantity, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{2, 1}, quantity}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; auto a1 = root.create("A", lm.getLastMinBalance(5) + 2000 + 5 * txFee); a1.changeTrust(cur1, INT64_MAX); issuer.pay(a1, cur1, INT64_MAX - 4000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); createOfferQuantity(a1, cur1, native, INT64_MAX / 4 - 2000, offers, OfferState::DELETED); createOfferQuantity(a1, cur1, native, INT64_MAX / 4 - 2000, offers, OfferState::DELETED); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 0}); } SECTION("valid non-native") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 2000}); } SECTION("invalid non-native") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.pay(a1, cur1, 1000); issuer.pay(a1, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 2000}); } SECTION("valid non-native issued by account") { auto a1 = root.create("A", lm.getLastMinBalance(4) + 4 * txFee); auto issuedCur1 = a1.asset("CUR1"); auto issuedCur2 = a1.asset("CUR2"); std::vector<TestMarketOffer> offers; createOffer(a1, issuedCur1, issuedCur2, offers); createOffer(a1, issuedCur1, issuedCur2, offers); createOffer(a1, issuedCur2, issuedCur1, offers); createOffer(a1, issuedCur2, issuedCur1, offers); market.requireChanges(offers, executeUpgrade); } } SECTION("one account, multiple offers, multiple asset pairs") { SECTION("all valid") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur2, offers); createOffer(a1, native, cur2, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{8000, 4000}); } SECTION("one invalid native") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 2000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur2, offers, OfferState::DELETED); createOffer(a1, native, cur2, offers, OfferState::DELETED); createOffer(a1, cur2, native, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 4000}); } SECTION("one invalid non-native") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 1000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur2, offers); createOffer(a1, native, cur2, offers); createOffer(a1, cur2, native, offers, OfferState::DELETED); createOffer(a1, cur2, native, offers, OfferState::DELETED); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{8000, 0}); } } SECTION("multiple accounts, multiple offers, multiple asset pairs") { SECTION("all valid") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); auto a2 = root.create("B", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a2.changeTrust(cur1, 12000); a2.changeTrust(cur2, 12000); issuer.pay(a2, cur1, 4000); issuer.pay(a2, cur2, 4000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur2, offers); createOffer(a1, native, cur2, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); createOffer(a2, native, cur1, offers); createOffer(a2, native, cur1, offers); createOffer(a2, cur1, native, offers); createOffer(a2, cur1, native, offers); createOffer(a2, native, cur2, offers); createOffer(a2, native, cur2, offers); createOffer(a2, cur2, native, offers); createOffer(a2, cur2, native, offers); createOffer(a2, cur1, cur2, offers); createOffer(a2, cur1, cur2, offers); createOffer(a2, cur2, cur1, offers); createOffer(a2, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{8000, 4000}); REQUIRE(getLiabilities(a2) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a2, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a2, cur2) == Liabilities{8000, 4000}); } SECTION("one invalid per account") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 2000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); auto a2 = root.create("B", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a2.changeTrust(cur1, 12000); a2.changeTrust(cur2, 12000); issuer.pay(a2, cur1, 4000); issuer.pay(a2, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur2, offers, OfferState::DELETED); createOffer(a1, native, cur2, offers, OfferState::DELETED); createOffer(a1, cur2, native, offers); createOffer(a1, cur2, native, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); createOffer(a2, native, cur1, offers); createOffer(a2, native, cur1, offers); createOffer(a2, cur1, native, offers); createOffer(a2, cur1, native, offers); createOffer(a2, native, cur2, offers); createOffer(a2, native, cur2, offers); createOffer(a2, cur2, native, offers, OfferState::DELETED); createOffer(a2, cur2, native, offers, OfferState::DELETED); createOffer(a2, cur1, cur2, offers); createOffer(a2, cur1, cur2, offers); createOffer(a2, cur2, cur1, offers, OfferState::DELETED); createOffer(a2, cur2, cur1, offers, OfferState::DELETED); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 4000}); REQUIRE(getLiabilities(a2) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a2, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a2, cur2) == Liabilities{8000, 0}); } } SECTION("liabilities overflow") { auto createOfferLarge = [&](TestAccount& acc, Asset const& selling, Asset const& buying, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{2, 1}, INT64_MAX / 3}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; SECTION("non-native for non-native, all invalid") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, INT64_MAX); a1.changeTrust(cur2, INT64_MAX); issuer.pay(a1, cur1, INT64_MAX / 3); issuer.pay(a1, cur2, INT64_MAX / 3); std::vector<TestMarketOffer> offers; createOfferLarge(a1, cur1, cur2, offers, OfferState::DELETED); createOfferLarge(a1, cur1, cur2, offers, OfferState::DELETED); createOfferLarge(a1, cur2, cur1, offers, OfferState::DELETED); createOfferLarge(a1, cur2, cur1, offers, OfferState::DELETED); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } SECTION("non-native for non-native, half invalid") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, INT64_MAX); a1.changeTrust(cur2, INT64_MAX); issuer.pay(a1, cur1, INT64_MAX / 3); issuer.pay(a1, cur2, INT64_MAX / 3); std::vector<TestMarketOffer> offers; createOfferLarge(a1, cur1, cur2, offers, OfferState::DELETED); createOfferLarge(a1, cur1, cur2, offers, OfferState::DELETED); createOfferLarge(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{INT64_MAX / 3 * 2, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, INT64_MAX / 3}); } SECTION("issued asset for issued asset") { auto a1 = root.create("A", lm.getLastMinBalance(4) + 4 * txFee); auto issuedCur1 = a1.asset("CUR1"); auto issuedCur2 = a1.asset("CUR2"); std::vector<TestMarketOffer> offers; createOfferLarge(a1, issuedCur1, issuedCur2, offers); createOfferLarge(a1, issuedCur1, issuedCur2, offers); createOfferLarge(a1, issuedCur2, issuedCur1, offers); createOfferLarge(a1, issuedCur2, issuedCur1, offers); market.requireChanges(offers, executeUpgrade); } } SECTION("adjust offers") { SECTION("offers that do not satisfy thresholds are deleted") { auto createOfferQuantity = [&](TestAccount& acc, Asset const& selling, Asset const& buying, int64_t quantity, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{3, 2}, quantity}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, 1000); a1.changeTrust(cur2, 1000); issuer.pay(a1, cur1, 500); issuer.pay(a1, cur2, 500); std::vector<TestMarketOffer> offers; createOfferQuantity(a1, cur1, cur2, 27, offers, OfferState::DELETED); createOfferQuantity(a1, cur1, cur2, 28, offers); createOfferQuantity(a1, cur2, cur1, 27, offers, OfferState::DELETED); createOfferQuantity(a1, cur2, cur1, 28, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{42, 28}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{42, 28}); } SECTION("offers that need rounding are rounded") { auto createOfferQuantity = [&](TestAccount& acc, Asset const& selling, Asset const& buying, int64_t quantity, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{2, 3}, quantity}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; auto a1 = root.create("A", lm.getLastMinBalance(4) + 4 * txFee); a1.changeTrust(cur1, 1000); a1.changeTrust(cur2, 1000); issuer.pay(a1, cur1, 500); std::vector<TestMarketOffer> offers; createOfferQuantity(a1, cur1, cur2, 201, offers); createOfferQuantity(a1, cur1, cur2, 202, offers, {cur1, cur2, Price{2, 3}, 201}); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 402}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{268, 0}); } SECTION("offers that do not satisfy thresholds still contribute " "liabilities") { auto createOfferQuantity = [&](TestAccount& acc, Asset const& selling, Asset const& buying, int64_t quantity, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{3, 2}, quantity}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; auto a1 = root.create("A", lm.getLastMinBalance(10) + 2000 + 12 * txFee); a1.changeTrust(cur1, 5125); a1.changeTrust(cur2, 5125); issuer.pay(a1, cur1, 2050); issuer.pay(a1, cur2, 2050); SECTION("normal offers remain without liabilities from" " offers that do not satisfy thresholds") { // Pay txFee to send 4*baseReserve + 3*txFee for net balance // decrease of 4*baseReserve + 4*txFee. This matches the balance // decrease from creating 4 offers as in the next test section. a1.pay(root, 4 * lm.getLastReserve() + 3 * txFee); std::vector<TestMarketOffer> offers; createOfferQuantity(a1, cur1, native, 1000, offers); createOfferQuantity(a1, cur1, native, 1000, offers); createOfferQuantity(a1, native, cur1, 1000, offers); createOfferQuantity(a1, native, cur1, 1000, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{3000, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{3000, 2000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } SECTION("normal offers deleted with liabilities from" " offers that do not satisfy thresholds") { std::vector<TestMarketOffer> offers; createOfferQuantity(a1, cur1, cur2, 27, offers, OfferState::DELETED); createOfferQuantity(a1, cur1, cur2, 27, offers, OfferState::DELETED); createOfferQuantity(a1, cur1, native, 1000, offers, OfferState::DELETED); createOfferQuantity(a1, cur1, native, 1000, offers, OfferState::DELETED); createOfferQuantity(a1, cur2, cur1, 27, offers, OfferState::DELETED); createOfferQuantity(a1, cur2, cur1, 27, offers, OfferState::DELETED); createOfferQuantity(a1, native, cur1, 1000, offers, OfferState::DELETED); createOfferQuantity(a1, native, cur1, 1000, offers, OfferState::DELETED); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } } } SECTION("unauthorized offers") { auto toSet = static_cast<uint32_t>(AUTH_REQUIRED_FLAG) | static_cast<uint32_t>(AUTH_REVOCABLE_FLAG); issuer.setOptions(txtest::setFlags(toSet)); SECTION("both assets require authorization and authorized") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.allowTrust(cur1, a1); issuer.allowTrust(cur2, a1); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers); createOffer(a1, cur1, cur2, offers); createOffer(a1, cur2, cur1, offers); createOffer(a1, cur2, cur1, offers); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 2000}); } SECTION("selling asset not authorized") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 4000 + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.allowTrust(cur1, a1); issuer.allowTrust(cur2, a1); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur2, native, offers); createOffer(a1, cur2, native, offers); issuer.denyTrust(cur1, a1); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 2000}); } SECTION("buying asset not authorized") { auto a1 = root.create("A", lm.getLastMinBalance(6) + 4000 + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.allowTrust(cur1, a1); issuer.allowTrust(cur2, a1); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur2, offers); createOffer(a1, native, cur2, offers); issuer.denyTrust(cur1, a1); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 0}); } SECTION("unauthorized offers still contribute liabilities") { auto a1 = root.create("A", lm.getLastMinBalance(10) + 2000 + 10 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.allowTrust(cur1, a1); issuer.allowTrust(cur2, a1); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); SECTION("authorized offers remain without liabilities from" " unauthorized offers") { // Pay txFee to send 4*baseReserve + 3*txFee for net balance // decrease of 4*baseReserve + 4*txFee. This matches the balance // decrease from creating 4 offers as in the next test section. a1.pay(root, 4 * lm.getLastReserve() + 3 * txFee); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); issuer.denyTrust(cur2, a1); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } SECTION("authorized offers deleted with liabilities from" " unauthorized offers") { std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); issuer.denyTrust(cur2, a1); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } } } SECTION("deleted trust lines") { auto a1 = root.create("A", lm.getLastMinBalance(4) + 6 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.pay(a1, cur1, 2000); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, cur2, offers, OfferState::DELETED); SECTION("deleted selling trust line") { a1.pay(issuer, cur1, 2000); a1.changeTrust(cur1, 0); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } SECTION("deleted buying trust line") { a1.changeTrust(cur2, 0); market.requireChanges(offers, executeUpgrade); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } } SECTION("offers with deleted trust lines still contribute liabilities") { auto a1 = root.create("A", lm.getLastMinBalance(10) + 2000 + 12 * txFee); a1.changeTrust(cur1, 6000); a1.changeTrust(cur2, 6000); issuer.pay(a1, cur1, 2000); issuer.pay(a1, cur2, 2000); SECTION("normal offers remain without liabilities from" " offers with deleted trust lines") { // Pay txFee to send 4*baseReserve + 3*txFee for net balance // decrease of 4*baseReserve + 4*txFee. This matches the balance // decrease from creating 4 offers as in the next test section. a1.pay(root, 4 * lm.getLastReserve() + 3 * txFee); std::vector<TestMarketOffer> offers; createOffer(a1, cur1, native, offers); createOffer(a1, cur1, native, offers); createOffer(a1, native, cur1, offers); createOffer(a1, native, cur1, offers); a1.pay(issuer, cur2, 2000); a1.changeTrust(cur2, 0); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 2000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } SECTION("normal offers deleted with liabilities from" " offers with deleted trust lines") { std::vector<TestMarketOffer> offers; createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, cur2, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur1, native, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); createOffer(a1, cur2, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); createOffer(a1, native, cur1, offers, OfferState::DELETED); a1.pay(issuer, cur2, 2000); a1.changeTrust(cur2, 0); market.requireChanges(offers, executeUpgrade); REQUIRE(getLiabilities(a1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{0, 0}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{0, 0}); } } } TEST_CASE("upgrade to version 11", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(0); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); executeUpgrade(*app, makeProtocolVersionUpgrade(10)); auto& lm = app->getLedgerManager(); uint32_t newProto = 11; auto root = TestAccount{*app, txtest::getRoot(app->getNetworkID())}; for (size_t i = 0; i < 10; ++i) { auto stranger = TestAccount{*app, txtest::getAccount(fmt::format("stranger{}", i))}; uint32_t ledgerSeq = lm.getLastClosedLedgerNum() + 1; uint64_t minBalance = lm.getLastMinBalance(5); uint64_t big = minBalance + ledgerSeq; uint64_t closeTime = 60 * 5 * ledgerSeq; TxSetFrameConstPtr txSet = std::make_shared<TxSetFrame const>( lm.getLastClosedLedgerHeader().hash, TxSetFrame::Transactions{ root.tx({txtest::createAccount(stranger, big)})}); // On 4th iteration of advance (a.k.a. ledgerSeq 5), perform a // ledger-protocol version upgrade to the new protocol, to activate // INITENTRY behaviour. auto upgrades = xdr::xvector<UpgradeType, 6>{}; if (ledgerSeq == 5) { auto ledgerUpgrade = LedgerUpgrade{LEDGER_UPGRADE_VERSION}; ledgerUpgrade.newLedgerVersion() = newProto; auto v = xdr::xdr_to_opaque(ledgerUpgrade); upgrades.push_back(UpgradeType{v.begin(), v.end()}); CLOG_INFO(Ledger, "Ledger {} upgrading to v{}", ledgerSeq, newProto); } StellarValue sv = app->getHerder().makeStellarValue( txSet->getContentsHash(), closeTime, upgrades, app->getConfig().NODE_SEED); lm.closeLedger(LedgerCloseData(ledgerSeq, txSet, sv)); auto& bm = app->getBucketManager(); auto& bl = bm.getBucketList(); while (!bl.futuresAllResolved()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); bl.resolveAnyReadyFutures(); } auto mc = bm.readMergeCounters(); CLOG_INFO(Bucket, "Ledger {} did {} old-protocol merges, {} new-protocol " "merges, {} new INITENTRYs, {} old INITENTRYs", ledgerSeq, mc.mPreInitEntryProtocolMerges, mc.mPostInitEntryProtocolMerges, mc.mNewInitEntries, mc.mOldInitEntries); for (uint32_t level = 0; level < BucketList::kNumLevels; ++level) { auto& lev = bm.getBucketList().getLevel(level); BucketTests::EntryCounts currCounts(lev.getCurr()); BucketTests::EntryCounts snapCounts(lev.getSnap()); CLOG_INFO( Bucket, "post-ledger {} close, init counts: level {}, {} in curr, " "{} in snap", ledgerSeq, level, currCounts.nInit, snapCounts.nInit); } if (ledgerSeq < 5) { // Check that before upgrade, we did not do any INITENTRY. REQUIRE(mc.mPreInitEntryProtocolMerges != 0); REQUIRE(mc.mPostInitEntryProtocolMerges == 0); REQUIRE(mc.mNewInitEntries == 0); REQUIRE(mc.mOldInitEntries == 0); } else { // Check several subtle characteristics of the post-upgrade // environment: // - Old-protocol merges stop happening (there should have // been 6 before the upgrade, but we re-use a merge we did at // ledger 1 for ledger 2 spill, so the counter is at 5) // - New-protocol merges start happening. // - At the upgrade (5), we find 1 INITENTRY in lev[0].curr // - The next two (6, 7), propagate INITENTRYs to lev[0].snap // - From 8 on, the INITENTRYs propagate to lev[1].curr REQUIRE(mc.mPreInitEntryProtocolMerges == 5); REQUIRE(mc.mPostInitEntryProtocolMerges != 0); auto& lev0 = bm.getBucketList().getLevel(0); auto& lev1 = bm.getBucketList().getLevel(1); auto lev0Curr = lev0.getCurr(); auto lev0Snap = lev0.getSnap(); auto lev1Curr = lev1.getCurr(); auto lev1Snap = lev1.getSnap(); BucketTests::EntryCounts lev0CurrCounts(lev0Curr); BucketTests::EntryCounts lev0SnapCounts(lev0Snap); BucketTests::EntryCounts lev1CurrCounts(lev1Curr); auto getVers = [](std::shared_ptr<Bucket> b) -> uint32_t { return BucketInputIterator(b).getMetadata().ledgerVersion; }; switch (ledgerSeq) { default: case 8: REQUIRE(getVers(lev1Curr) == newProto); REQUIRE(lev1CurrCounts.nInit != 0); case 7: case 6: REQUIRE(getVers(lev0Snap) == newProto); REQUIRE(lev0SnapCounts.nInit != 0); case 5: REQUIRE(getVers(lev0Curr) == newProto); REQUIRE(lev0CurrCounts.nInit != 0); } } } } TEST_CASE("upgrade to version 12", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); executeUpgrade(*app, makeProtocolVersionUpgrade(11)); auto& lm = app->getLedgerManager(); uint32_t oldProto = 11; uint32_t newProto = 12; auto root = TestAccount{*app, txtest::getRoot(app->getNetworkID())}; for (size_t i = 0; i < 10; ++i) { auto stranger = TestAccount{*app, txtest::getAccount(fmt::format("stranger{}", i))}; uint32_t ledgerSeq = lm.getLastClosedLedgerNum() + 1; uint64_t minBalance = lm.getLastMinBalance(5); uint64_t big = minBalance + ledgerSeq; uint64_t closeTime = 60 * 5 * ledgerSeq; TxSetFrameConstPtr txSet = std::make_shared<TxSetFrame const>( lm.getLastClosedLedgerHeader().hash, TxSetFrame::Transactions{ root.tx({txtest::createAccount(stranger, big)})}); // On 4th iteration of advance (a.k.a. ledgerSeq 5), perform a // ledger-protocol version upgrade to the new protocol, to // start new-style merges (no shadows) auto upgrades = xdr::xvector<UpgradeType, 6>{}; if (ledgerSeq == 5) { auto ledgerUpgrade = LedgerUpgrade{LEDGER_UPGRADE_VERSION}; ledgerUpgrade.newLedgerVersion() = newProto; auto v = xdr::xdr_to_opaque(ledgerUpgrade); upgrades.push_back(UpgradeType{v.begin(), v.end()}); CLOG_INFO(Ledger, "Ledger {} upgrading to v{}", ledgerSeq, newProto); } StellarValue sv = app->getHerder().makeStellarValue( txSet->getContentsHash(), closeTime, upgrades, app->getConfig().NODE_SEED); lm.closeLedger(LedgerCloseData(ledgerSeq, txSet, sv)); auto& bm = app->getBucketManager(); auto& bl = bm.getBucketList(); while (!bl.futuresAllResolved()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); bl.resolveAnyReadyFutures(); } auto mc = bm.readMergeCounters(); if (ledgerSeq < 5) { REQUIRE(mc.mPreShadowRemovalProtocolMerges != 0); } else { auto& lev0 = bm.getBucketList().getLevel(0); auto& lev1 = bm.getBucketList().getLevel(1); auto lev0Curr = lev0.getCurr(); auto lev0Snap = lev0.getSnap(); auto lev1Curr = lev1.getCurr(); auto lev1Snap = lev1.getSnap(); auto getVers = [](std::shared_ptr<Bucket> b) -> uint32_t { return BucketInputIterator(b).getMetadata().ledgerVersion; }; switch (ledgerSeq) { case 8: REQUIRE(getVers(lev1Curr) == newProto); REQUIRE(getVers(lev1Snap) == oldProto); REQUIRE(mc.mPostShadowRemovalProtocolMerges == 6); // One more old-style merge despite the upgrade // At ledger 8, level 2 spills, and starts an old-style merge, // as level 1 snap is still of old version REQUIRE(mc.mPreShadowRemovalProtocolMerges == 6); break; case 7: REQUIRE(getVers(lev0Snap) == newProto); REQUIRE(getVers(lev1Curr) == oldProto); REQUIRE(mc.mPostShadowRemovalProtocolMerges == 4); REQUIRE(mc.mPreShadowRemovalProtocolMerges == 5); break; case 6: REQUIRE(getVers(lev0Snap) == newProto); REQUIRE(getVers(lev1Curr) == oldProto); REQUIRE(mc.mPostShadowRemovalProtocolMerges == 3); REQUIRE(mc.mPreShadowRemovalProtocolMerges == 5); break; case 5: REQUIRE(getVers(lev0Curr) == newProto); REQUIRE(getVers(lev0Snap) == oldProto); REQUIRE(mc.mPostShadowRemovalProtocolMerges == 1); REQUIRE(mc.mPreShadowRemovalProtocolMerges == 5); break; default: break; } } } } TEST_CASE("upgrade to version 13", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(0); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); executeUpgrade(*app, makeProtocolVersionUpgrade(12)); auto& lm = app->getLedgerManager(); auto& herder = static_cast<HerderImpl&>(app->getHerder()); auto root = TestAccount::createRoot(*app); auto acc = root.create("A", lm.getLastMinBalance(2)); herder.recvTransaction(root.tx({payment(root, 1)})); herder.recvTransaction(root.tx({payment(root, 2)})); herder.recvTransaction(acc.tx({payment(acc, 1)})); herder.recvTransaction(acc.tx({payment(acc, 2)})); auto txSet = herder.getTransactionQueue().toTxSet({}); for (auto const& tx : txSet->getTxsInHashOrder()) { REQUIRE(tx->getEnvelope().type() == ENVELOPE_TYPE_TX_V0); } { auto const& lcl = lm.getLastClosedLedgerHeader(); auto ledgerSeq = lcl.header.ledgerSeq + 1; auto emptyTxSet = std::make_shared<TxSetFrame const>(lcl.hash); herder.getPendingEnvelopes().putTxSet(emptyTxSet->getContentsHash(), ledgerSeq, emptyTxSet); auto upgrade = toUpgradeType(makeProtocolVersionUpgrade(13)); StellarValue sv = herder.makeStellarValue(emptyTxSet->getContentsHash(), 2, xdr::xvector<UpgradeType, 6>({upgrade}), app->getConfig().NODE_SEED); herder.getHerderSCPDriver().valueExternalized(ledgerSeq, xdr::xdr_to_opaque(sv)); } txSet = herder.getTransactionQueue().toTxSet({}); for (auto const& tx : txSet->getTxsInHashOrder()) { REQUIRE(tx->getEnvelope().type() == ENVELOPE_TYPE_TX); } } TEST_CASE_VERSIONS("upgrade base reserve", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(0); auto app = createTestApplication(clock, cfg); auto& lm = app->getLedgerManager(); auto txFee = lm.getLastTxFee(); auto root = TestAccount::createRoot(*app); auto issuer = root.create("issuer", lm.getLastMinBalance(0) + 100 * txFee); auto native = txtest::makeNativeAsset(); auto cur1 = issuer.asset("CUR1"); auto cur2 = issuer.asset("CUR2"); auto market = TestMarket{*app}; auto executeUpgrade = [&](uint32_t newReserve) { REQUIRE(::executeUpgrade(*app, makeBaseReserveUpgrade(newReserve)) .baseReserve == newReserve); }; auto getLiabilities = [&](TestAccount& acc) { Liabilities res; LedgerTxn ltx(app->getLedgerTxnRoot()); auto account = stellar::loadAccount(ltx, acc.getPublicKey()); res.selling = getSellingLiabilities(ltx.loadHeader(), account); res.buying = getBuyingLiabilities(ltx.loadHeader(), account); return res; }; auto getAssetLiabilities = [&](TestAccount& acc, Asset const& asset) { Liabilities res; if (acc.hasTrustLine(asset)) { LedgerTxn ltx(app->getLedgerTxnRoot()); auto trust = stellar::loadTrustLine(ltx, acc.getPublicKey(), asset); res.selling = trust.getSellingLiabilities(ltx.loadHeader()); res.buying = trust.getBuyingLiabilities(ltx.loadHeader()); } return res; }; auto getNumSponsoringEntries = [&](TestAccount& acc) { LedgerTxn ltx(app->getLedgerTxnRoot()); auto account = stellar::loadAccount(ltx, acc.getPublicKey()); return getNumSponsoring(account.current()); }; auto getNumSponsoredEntries = [&](TestAccount& acc) { LedgerTxn ltx(app->getLedgerTxnRoot()); auto account = stellar::loadAccount(ltx, acc.getPublicKey()); return getNumSponsored(account.current()); }; auto createOffer = [&](TestAccount& acc, Asset const& selling, Asset const& buying, std::vector<TestMarketOffer>& offers, OfferState const& afterUpgrade = OfferState::SAME) { OfferState state = {selling, buying, Price{2, 1}, 1000}; auto offer = market.requireChangesWithOffer( {}, [&] { return market.addOffer(acc, state); }); if (afterUpgrade == OfferState::SAME) { offers.push_back({offer.key, offer.state}); } else { offers.push_back({offer.key, afterUpgrade}); } }; auto createOffers = [&](TestAccount& acc, std::vector<TestMarketOffer>& offers, bool expectToDeleteNativeSells = false) { OfferState nativeSellState = expectToDeleteNativeSells ? OfferState::DELETED : OfferState::SAME; createOffer(acc, native, cur1, offers, nativeSellState); createOffer(acc, native, cur1, offers, nativeSellState); createOffer(acc, cur1, native, offers); createOffer(acc, cur1, native, offers); createOffer(acc, native, cur2, offers, nativeSellState); createOffer(acc, native, cur2, offers, nativeSellState); createOffer(acc, cur2, native, offers); createOffer(acc, cur2, native, offers); createOffer(acc, cur1, cur2, offers); createOffer(acc, cur1, cur2, offers); createOffer(acc, cur2, cur1, offers); createOffer(acc, cur2, cur1, offers); }; auto deleteOffers = [&](TestAccount& acc, std::vector<TestMarketOffer> const& offers) { for (auto const& offer : offers) { auto delOfferState = offer.state; delOfferState.amount = 0; market.requireChangesWithOffer({}, [&] { return market.updateOffer(acc, offer.key.offerID, delOfferState, OfferState::DELETED); }); } }; SECTION("decrease reserve") { auto a1 = root.create("A", lm.getLastMinBalance(14) + 4000 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); for_versions_to(9, *app, [&] { std::vector<TestMarketOffer> offers; createOffers(a1, offers); uint32_t baseReserve = lm.getLastReserve(); market.requireChanges(offers, std::bind(executeUpgrade, baseReserve / 2)); deleteOffers(a1, offers); }); for_versions_from(10, *app, [&] { std::vector<TestMarketOffer> offers; createOffers(a1, offers); uint32_t baseReserve = lm.getLastReserve(); market.requireChanges(offers, std::bind(executeUpgrade, baseReserve / 2)); REQUIRE(getLiabilities(a1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{8000, 4000}); deleteOffers(a1, offers); }); } SECTION("increase reserve") { for_versions_to(9, *app, [&] { auto a1 = root.create("A", 2 * lm.getLastMinBalance(14) + 3999 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); auto a2 = root.create("B", 2 * lm.getLastMinBalance(14) + 4000 + 14 * txFee); a2.changeTrust(cur1, 12000); a2.changeTrust(cur2, 12000); issuer.pay(a2, cur1, 4000); issuer.pay(a2, cur2, 4000); std::vector<TestMarketOffer> offers; createOffers(a1, offers); createOffers(a2, offers); uint32_t baseReserve = lm.getLastReserve(); market.requireChanges(offers, std::bind(executeUpgrade, 2 * baseReserve)); }); auto submitTx = [&](TransactionFrameBasePtr tx) { LedgerTxn ltx(app->getLedgerTxnRoot()); TransactionMeta txm(2); REQUIRE(tx->checkValid(ltx, 0, 0, 0)); REQUIRE(tx->apply(*app, ltx, txm)); ltx.commit(); REQUIRE(tx->getResultCode() == txSUCCESS); }; auto increaseReserveFromV10 = [&](bool allowMaintainLiablities, bool flipSponsorship) { auto a1 = root.create("A", 2 * lm.getLastMinBalance(14) + 3999 + 14 * txFee); a1.changeTrust(cur1, 12000); a1.changeTrust(cur2, 12000); issuer.pay(a1, cur1, 4000); issuer.pay(a1, cur2, 4000); auto a2 = root.create("B", 2 * lm.getLastMinBalance(14) + 4000 + 14 * txFee); a2.changeTrust(cur1, 12000); a2.changeTrust(cur2, 12000); issuer.pay(a2, cur1, 4000); issuer.pay(a2, cur2, 4000); std::vector<TestMarketOffer> offers; createOffers(a1, offers, true); createOffers(a2, offers); if (allowMaintainLiablities) { issuer.setOptions(txtest::setFlags( static_cast<uint32_t>(AUTH_REQUIRED_FLAG) | static_cast<uint32_t>(AUTH_REVOCABLE_FLAG))); issuer.allowMaintainLiabilities(cur1, a1); } if (flipSponsorship) { std::vector<Operation> opsA1 = { a1.op(beginSponsoringFutureReserves(a2))}; std::vector<Operation> opsA2 = { a2.op(beginSponsoringFutureReserves(a1))}; for (auto const& offer : offers) { if (offer.key.sellerID == a2.getPublicKey()) { opsA1.emplace_back(a2.op(revokeSponsorship( offerKey(a2, offer.key.offerID)))); } else { opsA2.emplace_back(a1.op(revokeSponsorship( offerKey(a1, offer.key.offerID)))); } } opsA1.emplace_back(a2.op(endSponsoringFutureReserves())); opsA2.emplace_back(a1.op(endSponsoringFutureReserves())); // submit tx to update sponsorship submitTx(transactionFrameFromOps(app->getNetworkID(), a1, opsA1, {a2})); submitTx(transactionFrameFromOps(app->getNetworkID(), a2, opsA2, {a1})); } uint32_t baseReserve = lm.getLastReserve(); market.requireChanges(offers, std::bind(executeUpgrade, 2 * baseReserve)); REQUIRE(getLiabilities(a1) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(a1, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(a1, cur2) == Liabilities{4000, 4000}); REQUIRE(getLiabilities(a2) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a2, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(a2, cur2) == Liabilities{8000, 4000}); }; SECTION("authorized") { for_versions_from(10, *app, [&] { increaseReserveFromV10(false, false); }); } SECTION("authorized to maintain liabilities") { for_versions_from(13, *app, [&] { increaseReserveFromV10(true, false); }); } SECTION("sponsorships") { auto accSponsorsAllOffersTest = [&](TestAccount& sponsoringAcc, TestAccount& sponsoredAcc, TestAccount& sponsoredAcc2, bool sponsoringAccPullOffers, bool sponsoredAccPullOffers) { sponsoringAcc.changeTrust(cur1, 12000); sponsoringAcc.changeTrust(cur2, 12000); issuer.pay(sponsoringAcc, cur1, 4000); issuer.pay(sponsoringAcc, cur2, 4000); sponsoredAcc.changeTrust(cur1, 12000); sponsoredAcc.changeTrust(cur2, 12000); issuer.pay(sponsoredAcc, cur1, 4000); issuer.pay(sponsoredAcc, cur2, 4000); sponsoredAcc2.changeTrust(cur1, 12000); sponsoredAcc2.changeTrust(cur2, 12000); issuer.pay(sponsoredAcc2, cur1, 4000); issuer.pay(sponsoredAcc2, cur2, 4000); std::vector<TestMarketOffer> offers; createOffers(sponsoringAcc, offers, sponsoringAccPullOffers); createOffers(sponsoredAcc, offers, sponsoredAccPullOffers); createOffers(sponsoredAcc2, offers, true); // prepare ops to transfer sponsorship of all sponsoredAcc // offers and one offer from sponsoredAcc2 to sponsoringAcc std::vector<Operation> ops = { sponsoringAcc.op( beginSponsoringFutureReserves(sponsoredAcc)), sponsoringAcc.op( beginSponsoringFutureReserves(sponsoredAcc2))}; for (auto const& offer : offers) { if (offer.key.sellerID == sponsoredAcc.getPublicKey()) { ops.emplace_back(sponsoredAcc.op(revokeSponsorship( offerKey(sponsoredAcc, offer.key.offerID)))); } } // last offer in offers is for sponsoredAcc2 ops.emplace_back(sponsoredAcc2.op(revokeSponsorship( offerKey(sponsoredAcc2, offers.back().key.offerID)))); ops.emplace_back( sponsoredAcc.op(endSponsoringFutureReserves())); ops.emplace_back( sponsoredAcc2.op(endSponsoringFutureReserves())); // submit tx to update sponsorship submitTx(transactionFrameFromOps( app->getNetworkID(), sponsoringAcc, ops, {sponsoredAcc, sponsoredAcc2})); REQUIRE(getNumSponsoredEntries(sponsoredAcc) == 12); REQUIRE(getNumSponsoredEntries(sponsoredAcc2) == 1); REQUIRE(getNumSponsoringEntries(sponsoringAcc) == 13); uint32_t baseReserve = lm.getLastReserve(); if (sponsoredAccPullOffers) { // SponsoringAcc is now sponsoring all 12 of sponsoredAcc's // offers. SponsoredAcc has 4 subentries. It also has enough // lumens to cover 12 more subentries after the sponsorship // update. After the upgrade to double the baseReserve, this // account will need to cover the 4 subEntries, so we only // need 4 extra baseReserves before the upgrade. Pay out the // rest (8 reserves) so we can get our orders pulled on // upgrade. 16(total reserves) - 4(subEntries) - // 4(base reserve increase) = 8(extra base reserves) sponsoredAcc.pay(root, baseReserve * 8); } else { sponsoredAcc.pay(root, baseReserve * 8 - 1); } if (sponsoringAccPullOffers) { sponsoringAcc.pay(root, 1); } // This account needs to lose a base reserve to get its orders // pulled sponsoredAcc2.pay(root, baseReserve); // execute upgrade market.requireChanges( offers, std::bind(executeUpgrade, 2 * baseReserve)); if (sponsoredAccPullOffers) { REQUIRE(getLiabilities(sponsoredAcc) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(sponsoredAcc, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(sponsoredAcc, cur2) == Liabilities{4000, 4000}); // the 4 native offers were pulled REQUIRE(getNumSponsoredEntries(sponsoredAcc) == 8); REQUIRE(getNumSponsoringEntries(sponsoringAcc) == 9); } else { REQUIRE(getLiabilities(sponsoredAcc) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(sponsoredAcc, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(sponsoredAcc, cur2) == Liabilities{8000, 4000}); REQUIRE(getNumSponsoredEntries(sponsoredAcc) == 12); REQUIRE(getNumSponsoringEntries(sponsoringAcc) == 13); } if (sponsoringAccPullOffers) { REQUIRE(getLiabilities(sponsoringAcc) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(sponsoringAcc, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(sponsoringAcc, cur2) == Liabilities{4000, 4000}); } else { REQUIRE(getLiabilities(sponsoringAcc) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(sponsoringAcc, cur1) == Liabilities{8000, 4000}); REQUIRE(getAssetLiabilities(sponsoringAcc, cur2) == Liabilities{8000, 4000}); } REQUIRE(getLiabilities(sponsoredAcc2) == Liabilities{8000, 0}); REQUIRE(getAssetLiabilities(sponsoredAcc2, cur1) == Liabilities{4000, 4000}); REQUIRE(getAssetLiabilities(sponsoredAcc2, cur2) == Liabilities{4000, 4000}); }; auto sponsorshipTestsBySeed = [&](std::string sponsoringSeed, std::string sponsoredSeed) { auto sponsoring = root.create(sponsoringSeed, 2 * lm.getLastMinBalance(27) + 4000 + 15 * txFee); auto sponsored = root.create(sponsoredSeed, lm.getLastMinBalance(14) + 3999 + 15 * txFee); // This account will have one sponsored offer and will always // have it's offers pulled. auto sponsored2 = root.create( "C", 2 * lm.getLastMinBalance(13) + 3999 + 15 * txFee); SECTION("sponsored and sponsoring accounts get offers " "pulled on upgrade") { accSponsorsAllOffersTest(sponsoring, sponsored, sponsored2, true, true); } SECTION("no offers pulled") { accSponsorsAllOffersTest(sponsoring, sponsored, sponsored2, false, false); } SECTION("offers for sponsored account pulled") { accSponsorsAllOffersTest(sponsoring, sponsored, sponsored2, true, false); } SECTION("offers for sponsoring account pulled") { accSponsorsAllOffersTest(sponsoring, sponsored, sponsored2, false, true); } }; for_versions_from(14, *app, [&] { // Swap the seeds to test that the ordering of accounts doesn't // matter when upgrading SECTION("account A is sponsored") { sponsorshipTestsBySeed("B", "A"); } SECTION("account B is sponsored") { sponsorshipTestsBySeed("A", "B"); } SECTION("swap sponsorship of orders") { increaseReserveFromV10(false, true); } }); } } } TEST_CASE("simulate upgrades", "[herder][upgrades][acceptance]") { // no upgrade is done auto noUpgrade = LedgerUpgradeableData(LedgerManager::GENESIS_LEDGER_VERSION, LedgerManager::GENESIS_LEDGER_BASE_FEE, LedgerManager::GENESIS_LEDGER_MAX_TX_SIZE, LedgerManager::GENESIS_LEDGER_BASE_RESERVE); // all values are upgraded auto upgrade = LedgerUpgradeableData(Config::CURRENT_LEDGER_PROTOCOL_VERSION, LedgerManager::GENESIS_LEDGER_BASE_FEE + 1, LedgerManager::GENESIS_LEDGER_MAX_TX_SIZE + 1, LedgerManager::GENESIS_LEDGER_BASE_RESERVE + 1); SECTION("0 of 3 vote - dont upgrade") { auto nodes = std::vector<LedgerUpgradeNode>{{}, {}, {}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 10), {noUpgrade, noUpgrade, noUpgrade}}}; simulateUpgrade(nodes, checks); } SECTION("1 of 3 vote, dont upgrade") { auto nodes = std::vector<LedgerUpgradeNode>{{upgrade, genesis(0, 0)}, {}, {}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 10), {noUpgrade, noUpgrade, noUpgrade}}}; simulateUpgrade(nodes, checks, true); } SECTION("2 of 3 vote (v-blocking) - 3 upgrade") { auto nodes = std::vector<LedgerUpgradeNode>{ {upgrade, genesis(0, 0)}, {upgrade, genesis(0, 0)}, {}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 10), {upgrade, upgrade, upgrade}}}; simulateUpgrade(nodes, checks); } SECTION("3 of 3 vote - upgrade") { auto nodes = std::vector<LedgerUpgradeNode>{{upgrade, genesis(0, 15)}, {upgrade, genesis(0, 15)}, {upgrade, genesis(0, 15)}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 10), {noUpgrade, noUpgrade, noUpgrade}}, {genesis(0, 28), {upgrade, upgrade, upgrade}}}; simulateUpgrade(nodes, checks); } SECTION("3 votes for bogus fee - all 3 upgrade but ignore bad fee") { auto upgradeBadFee = upgrade; upgradeBadFee.baseFee = 0; auto expectedResult = upgradeBadFee; expectedResult.baseFee = LedgerManager::GENESIS_LEDGER_BASE_FEE; auto nodes = std::vector<LedgerUpgradeNode>{{upgradeBadFee, genesis(0, 0)}, {upgradeBadFee, genesis(0, 0)}, {upgradeBadFee, genesis(0, 0)}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 10), {expectedResult, expectedResult, expectedResult}}}; simulateUpgrade(nodes, checks, true); } SECTION("1 of 3 vote early - 2 upgrade late") { auto nodes = std::vector<LedgerUpgradeNode>{{upgrade, genesis(0, 10)}, {upgrade, genesis(0, 30)}, {upgrade, genesis(0, 30)}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 20), {noUpgrade, noUpgrade, noUpgrade}}, {genesis(0, 37), {upgrade, upgrade, upgrade}}}; simulateUpgrade(nodes, checks); } SECTION("2 of 3 vote early (v-blocking) - 3 upgrade anyways") { auto nodes = std::vector<LedgerUpgradeNode>{{upgrade, genesis(0, 10)}, {upgrade, genesis(0, 10)}, {upgrade, genesis(0, 30)}}; auto checks = std::vector<LedgerUpgradeCheck>{ {genesis(0, 9), {noUpgrade, noUpgrade, noUpgrade}}, {genesis(0, 27), {upgrade, upgrade, upgrade}}}; simulateUpgrade(nodes, checks); } } TEST_CASE_VERSIONS("upgrade invalid during ledger close", "[upgrades]") { VirtualClock clock; auto cfg = getTestConfig(); cfg.USE_CONFIG_FOR_GENESIS = false; auto app = createTestApplication(clock, cfg); SECTION("invalid version changes") { // Version upgrade to unsupported REQUIRE_THROWS(executeUpgrade( *app, makeProtocolVersionUpgrade( Config::CURRENT_LEDGER_PROTOCOL_VERSION + 1))); executeUpgrade(*app, makeProtocolVersionUpgrade( Config::CURRENT_LEDGER_PROTOCOL_VERSION)); // Version downgrade REQUIRE_THROWS(executeUpgrade( *app, makeProtocolVersionUpgrade( Config::CURRENT_LEDGER_PROTOCOL_VERSION - 1))); } SECTION("Invalid flags") { // Base Fee / Base Reserve to 0 REQUIRE_THROWS(executeUpgrade(*app, makeBaseFeeUpgrade(0))); REQUIRE_THROWS(executeUpgrade(*app, makeBaseReserveUpgrade(0))); if (cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION > 0) { executeUpgrade(*app, makeProtocolVersionUpgrade( cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION)); } for_versions_to(17, *app, [&] { REQUIRE_THROWS(executeUpgrade(*app, makeFlagsUpgrade(1))); }); for_versions_from(18, *app, [&] { auto allFlags = DISABLE_LIQUIDITY_POOL_TRADING_FLAG | DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG | DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG; REQUIRE(allFlags == MASK_LEDGER_HEADER_FLAGS); REQUIRE_THROWS(executeUpgrade( *app, makeFlagsUpgrade(MASK_LEDGER_HEADER_FLAGS + 1))); // success executeUpgrade(*app, makeFlagsUpgrade(MASK_LEDGER_HEADER_FLAGS)); }); } } TEST_CASE("validate upgrade expiration logic", "[upgrades]") { auto cfg = getTestConfig(); cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION = 10; cfg.TESTING_UPGRADE_DESIRED_FEE = 100; cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE = 50; cfg.TESTING_UPGRADE_RESERVE = 100000000; cfg.TESTING_UPGRADE_DATETIME = genesis(0, 0); cfg.TESTING_UPGRADE_FLAGS = 1; auto header = LedgerHeader{}; // make sure the network info is different than what's armed header.ledgerVersion = cfg.LEDGER_PROTOCOL_VERSION - 1; header.baseFee = cfg.TESTING_UPGRADE_DESIRED_FEE - 1; header.baseReserve = cfg.TESTING_UPGRADE_RESERVE - 1; header.maxTxSetSize = cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE - 1; setLedgerHeaderFlag(header, cfg.TESTING_UPGRADE_FLAGS - 1); SECTION("remove expired upgrades") { header.scpValue.closeTime = VirtualClock::to_time_t( cfg.TESTING_UPGRADE_DATETIME + Upgrades::UPDGRADE_EXPIRATION_HOURS); bool updated = false; auto upgrades = Upgrades{cfg}.removeUpgrades( header.scpValue.upgrades.begin(), header.scpValue.upgrades.end(), header.scpValue.closeTime, updated); REQUIRE(updated); REQUIRE(!upgrades.mProtocolVersion); REQUIRE(!upgrades.mBaseFee); REQUIRE(!upgrades.mMaxTxSetSize); REQUIRE(!upgrades.mBaseReserve); REQUIRE(!upgrades.mFlags); } SECTION("upgrades not yet expired") { header.scpValue.closeTime = VirtualClock::to_time_t( cfg.TESTING_UPGRADE_DATETIME + Upgrades::UPDGRADE_EXPIRATION_HOURS - std::chrono::seconds(1)); bool updated = false; auto upgrades = Upgrades{cfg}.removeUpgrades( header.scpValue.upgrades.begin(), header.scpValue.upgrades.end(), header.scpValue.closeTime, updated); REQUIRE(!updated); REQUIRE(upgrades.mProtocolVersion); REQUIRE(upgrades.mBaseFee); REQUIRE(upgrades.mMaxTxSetSize); REQUIRE(upgrades.mBaseReserve); REQUIRE(upgrades.mFlags); } } TEST_CASE("upgrade from cpp14 serialized data", "[upgrades]") { std::string in = R"({ "time": 1618016242, "version": { "has": true, "val": 17 }, "fee": { "has": false }, "maxtxsize": { "has": true, "val": 10000 }, "reserve": { "has": false }, "flags": { "has": false } })"; Upgrades::UpgradeParameters up; up.fromJson(in); REQUIRE(VirtualClock::to_time_t(up.mUpgradeTime) == 1618016242); REQUIRE(up.mProtocolVersion.has_value()); REQUIRE(up.mProtocolVersion.value() == 17); REQUIRE(!up.mBaseFee.has_value()); REQUIRE(up.mMaxTxSetSize.has_value()); REQUIRE(up.mMaxTxSetSize.value() == 10000); REQUIRE(!up.mBaseReserve.has_value()); } TEST_CASE_VERSIONS("upgrade flags", "[upgrades][liquiditypool]") { VirtualClock clock; auto cfg = getTestConfig(); auto app = createTestApplication(clock, cfg); auto root = TestAccount::createRoot(*app); auto native = makeNativeAsset(); auto cur1 = makeAsset(root, "CUR1"); auto shareNative1 = makeChangeTrustAssetPoolShare(native, cur1, LIQUIDITY_POOL_FEE_V18); auto poolNative1 = xdrSha256(shareNative1.liquidityPool()); auto executeUpgrade = [&](uint32_t newFlags) { REQUIRE( ::executeUpgrade(*app, makeFlagsUpgrade(newFlags)).ext.v1().flags == newFlags); }; for_versions_from(18, *app, [&] { // deposit REQUIRE_THROWS_AS(root.liquidityPoolDeposit(poolNative1, 1, 1, Price{1, 1}, Price{1, 1}), ex_LIQUIDITY_POOL_DEPOSIT_NO_TRUST); executeUpgrade(DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG); REQUIRE_THROWS_AS(root.liquidityPoolDeposit(poolNative1, 1, 1, Price{1, 1}, Price{1, 1}), ex_opNOT_SUPPORTED); // withdraw REQUIRE_THROWS_AS(root.liquidityPoolWithdraw(poolNative1, 1, 0, 0), ex_LIQUIDITY_POOL_WITHDRAW_NO_TRUST); executeUpgrade(DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG); REQUIRE_THROWS_AS(root.liquidityPoolWithdraw(poolNative1, 1, 0, 0), ex_opNOT_SUPPORTED); // clear flag executeUpgrade(0); // try both after clearing flags REQUIRE_THROWS_AS(root.liquidityPoolDeposit(poolNative1, 1, 1, Price{1, 1}, Price{1, 1}), ex_LIQUIDITY_POOL_DEPOSIT_NO_TRUST); REQUIRE_THROWS_AS(root.liquidityPoolWithdraw(poolNative1, 1, 0, 0), ex_LIQUIDITY_POOL_WITHDRAW_NO_TRUST); // set both flags executeUpgrade(DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG | DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG); REQUIRE_THROWS_AS(root.liquidityPoolDeposit(poolNative1, 1, 1, Price{1, 1}, Price{1, 1}), ex_opNOT_SUPPORTED); REQUIRE_THROWS_AS(root.liquidityPoolWithdraw(poolNative1, 1, 0, 0), ex_opNOT_SUPPORTED); // clear flags executeUpgrade(0); root.changeTrust(shareNative1, INT64_MAX); // deposit so we can test the disable trading flag root.liquidityPoolDeposit(poolNative1, 1000, 1000, Price{1, 1}, Price{1, 1}); auto a1 = root.create("a1", app->getLedgerManager().getLastMinBalance(0)); auto balance = a1.getBalance(); root.pay(a1, cur1, 2, native, 1, {}); REQUIRE(balance + 1 == a1.getBalance()); executeUpgrade(DISABLE_LIQUIDITY_POOL_TRADING_FLAG); REQUIRE_THROWS_AS(root.pay(a1, cur1, 2, native, 1, {}), ex_PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS); executeUpgrade(0); balance = a1.getBalance(); root.pay(a1, cur1, 2, native, 1, {}); REQUIRE(balance + 1 == a1.getBalance()); // block it again after trade (and add on a second flag) executeUpgrade(DISABLE_LIQUIDITY_POOL_TRADING_FLAG | DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG); REQUIRE_THROWS_AS(root.pay(a1, cur1, 2, native, 1, {}), ex_PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS); }); }
// Copyright (c) 2016-2018 The Bitcoin Core developers // Copyright (c) 2017 The Raven Core developers // Copyright (c) 2018 The Rito Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "perf.h" #if defined(__i386__) || defined(__x86_64__) /* These architectures support querying the cycle counter * from user space, no need for any syscall overhead. */ void perf_init(void) { } void perf_fini(void) { } #elif defined(__linux__) #include <unistd.h> #include <sys/syscall.h> #include <linux/perf_event.h> static int fd = -1; static struct perf_event_attr attr; void perf_init(void) { attr.type = PERF_TYPE_HARDWARE; attr.config = PERF_COUNT_HW_CPU_CYCLES; fd = syscall(__NR_perf_event_open, &attr, 0, -1, -1, 0); } void perf_fini(void) { if (fd != -1) { close(fd); } } uint64_t perf_cpucycles(void) { uint64_t result = 0; if (fd == -1 || read(fd, &result, sizeof(result)) < (ssize_t)sizeof(result)) { return 0; } return result; } #else /* Unhandled platform */ void perf_init(void) { } void perf_fini(void) { } uint64_t perf_cpucycles(void) { return 0; } #endif
; A092196: Number of letters in "old style" Roman numeral representation of n (e.g., IIII rather than IV). ; 0,1,2,3,4,1,2,3,4,5,1,2,3,4,5,2,3,4,5,6,2,3,4,5,6,3,4,5,6,7,3,4,5,6,7,4,5,6,7,8,4,5,6,7,8,5,6,7,8,9,1,2,3,4,5,2,3,4,5,6,2,3,4,5,6,3,4,5,6,7,3,4,5,6,7,4,5,6,7,8,4,5,6,7,8,5,6,7,8,9,5,6,7,8,9,6,7,8,9,10 mov $2,$0 mul $2,2 mov $0,$2 lpb $0 lpb $0 dif $0,10 sub $3,$2 lpe trn $3,1 cmp $3,0 add $1,$3 mul $3,$0 sub $0,1 lpe mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r14 push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0x134bf, %r12 nop nop nop inc %r11 mov (%r12), %r14w nop nop sub $36875, %r10 lea addresses_WC_ht+0x447f, %rsi lea addresses_D_ht+0x1e3f, %rdi clflush (%rdi) nop nop nop nop sub $12983, %rbx mov $110, %rcx rep movsw nop nop nop xor $2344, %r12 lea addresses_D_ht+0x963f, %r14 nop and $12149, %rdi vmovups (%r14), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %rbx nop nop cmp %r12, %r12 lea addresses_normal_ht+0xb13f, %rsi lea addresses_D_ht+0x7e3f, %rdi nop sub %r14, %r14 mov $104, %rcx rep movsw nop nop sub %r10, %r10 lea addresses_normal_ht+0x723f, %r11 nop nop nop nop nop and %rcx, %rcx mov $0x6162636465666768, %r10 movq %r10, %xmm1 vmovups %ymm1, (%r11) nop nop nop nop cmp %rdi, %rdi lea addresses_WT_ht+0x1e5d3, %rsi lea addresses_WT_ht+0x8c9f, %rdi nop nop nop nop dec %r10 mov $110, %rcx rep movsl nop nop sub $54138, %r14 lea addresses_UC_ht+0x14497, %rbx nop nop xor %rsi, %rsi mov $0x6162636465666768, %rcx movq %rcx, (%rbx) nop nop xor %rdi, %rdi lea addresses_D_ht+0x1a499, %r10 nop nop nop sub $41694, %r12 mov $0x6162636465666768, %rsi movq %rsi, (%r10) cmp $15889, %rdi lea addresses_A_ht+0x114e7, %r14 clflush (%r14) nop sub %rdi, %rdi and $0xffffffffffffffc0, %r14 movaps (%r14), %xmm5 vpextrq $1, %xmm5, %r10 nop dec %r12 lea addresses_normal_ht+0xf33f, %rdi inc %rcx mov (%rdi), %r12d nop nop and %r12, %r12 pop %rsi pop %rdi pop %rcx pop %rbx pop %r14 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r8 push %rax push %rbp push %rcx push %rdi push %rdx push %rsi // Store lea addresses_WC+0x9f3f, %r11 nop nop nop inc %rcx movb $0x51, (%r11) // Exception!!! nop mov (0), %rbp nop nop xor $60507, %rax // REPMOV lea addresses_normal+0x7e3f, %rsi lea addresses_D+0x1bef, %rdi nop nop inc %r8 mov $24, %rcx rep movsw nop nop nop and $61512, %rsi // Store lea addresses_US+0x363f, %r8 nop nop nop nop inc %rcx mov $0x5152535455565758, %rdx movq %rdx, %xmm2 movups %xmm2, (%r8) nop nop nop nop xor %rdx, %rdx // Store lea addresses_D+0xa619, %r11 cmp $60413, %rdx movb $0x51, (%r11) nop cmp $41648, %rbp // Faulty Load lea addresses_normal+0x7e3f, %rbp add $48544, %r8 mov (%rbp), %esi lea oracles, %rbp and $0xff, %rsi shlq $12, %rsi mov (%rbp,%rsi,1), %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_D', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': True, 'NT': True, 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': True, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'34': 206} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Ints86.asm - Interrupcoes do 8085 ;Prof. Roberto M. Ziller - 04.01.2000 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PILHA SEGMENT STACK DW 128 DUP (?) PILHA ENDS DADOS SEGMENT CONT DB 0 ; CONTAGEM ATRASO DB 0 ; ATRASO DADOS ENDS CODIGO SEGMENT ASSUME CS:CODIGO, DS:DADOS, SS:PILHA INICIO: MOV AX,CS MOV DS,AX ; DS = CS MOV AH,25H ; FUNCAO SET INT VECTOR MOV AL,28H ; VETOR A MODIFICAR MOV DX,OFFSET CONTA ; OFFSET DO TRATADOR INT 21H ; SERVICO DO DOS MOV AL,3 ; RETURN CODE MOV DX,0FFH ; PARAGRAPHS TO KEEP RESIDENT MOV AH,31H ; TSR INT 21H ; SERVICO DO DOS CONTA: PUSH AX PUSH BX PUSH CX PUSH DS MOV AX,DADOS MOV DS,AX ; DS -> DADOS INC ATRASO CMP ATRASO,00H JNE SAIDA MOV AL,CONT INC AL CMP AL,10 JNE OK XOR AL,AL ; ZERA CONTAGEM OK: MOV CONT,AL OR AL,30H ; TRANSFORMA EM ASCII MOV AH,09 ; FUNCAO "WRITE CHAR" DA INT 10H MOV BH,0 ; PAGINA DE VIDEO MOV BL,7 ; ATRIBUTO MOV CX,0001H ; NUMERO DE CARACTERES INT 10H ; SERVICO DO BIOS SAIDA: POP DS POP CX POP BX POP AX IRET CODIGO ENDS END INICIO
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef rtkFFTProjectionsConvolutionImageFilter_hxx #define rtkFFTProjectionsConvolutionImageFilter_hxx #include "rtkFFTProjectionsConvolutionImageFilter.h" // Use local RTK FFTW files taken from Gaëtan Lehmann's code for // thread safety: http://hdl.handle.net/10380/3154 #include <itkRealToHalfHermitianForwardFFTImageFilter.h> #include <itkHalfHermitianToRealInverseFFTImageFilter.h> #include <itkImageRegionIterator.h> #include <itkImageRegionIteratorWithIndex.h> namespace rtk { template <class TInputImage, class TOutputImage, class TFFTPrecision> FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::FFTProjectionsConvolutionImageFilter() : m_KernelDimension(1), m_TruncationCorrection(0.), m_GreatestPrimeFactor(2), m_BackupNumberOfThreads(1) { #if defined(USE_FFTWD) if(typeid(TFFTPrecision).name() == typeid(double).name() ) m_GreatestPrimeFactor = 13; #endif #if defined(USE_FFTWF) if(typeid(TFFTPrecision).name() == typeid(float).name() ) m_GreatestPrimeFactor = 13; #endif m_ZeroPadFactors.Fill(2); } template <class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); InputImageType * input = const_cast<InputImageType *>(this->GetInput() ); if ( !input ) return; // Compute input region (==requested region fully enlarged for dim 0) RegionType inputRegion; this->CallCopyOutputRegionToInputRegion(inputRegion, this->GetOutput()->GetRequestedRegion() ); inputRegion.SetIndex(0, this->GetOutput()->GetLargestPossibleRegion().GetIndex(0) ); inputRegion.SetSize(0, this->GetOutput()->GetLargestPossibleRegion().GetSize(0) ); // Also enlarge along dim 1 if 2D kernel is used if(m_KernelDimension == 2) { inputRegion.SetIndex(1, this->GetOutput()->GetLargestPossibleRegion().GetIndex(1) ); inputRegion.SetSize(1, this->GetOutput()->GetLargestPossibleRegion().GetSize(1) ); } input->SetRequestedRegion( inputRegion ); } template<class TInputImage, class TOutputImage, class TFFTPrecision> int FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::GetTruncationCorrectionExtent() { return itk::Math::floor(m_TruncationCorrection * this->GetInput()->GetRequestedRegion().GetSize(0)); } template<class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::BeforeThreadedGenerateData() { UpdateTruncationMirrorWeights(); // If the following condition is met, multi-threading is left to the (i)fft // filter. Otherwise, one splits the image and a separate fft is performed // per thread. if(this->GetOutput()->GetRequestedRegion().GetSize()[2] == 1 && m_KernelDimension == 2) { #if ITK_VERSION_MAJOR<5 m_BackupNumberOfThreads = this->GetNumberOfThreads(); this->SetNumberOfThreads(1); #else m_BackupNumberOfThreads = this->GetNumberOfWorkUnits(); this->SetNumberOfWorkUnits(1); #endif } else m_BackupNumberOfThreads = 1; // Update FFT ramp kernel (if required) RegionType paddedRegion = GetPaddedImageRegion( this->GetInput()->GetRequestedRegion() ); UpdateFFTProjectionsConvolutionKernel( paddedRegion.GetSize() ); } template<class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::AfterThreadedGenerateData() { if(this->GetOutput()->GetRequestedRegion().GetSize()[2] == 1 && m_KernelDimension == 2) #if ITK_VERSION_MAJOR<5 this->SetNumberOfThreads(m_BackupNumberOfThreads); #else this->SetNumberOfWorkUnits(m_BackupNumberOfThreads); #endif } template<class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> #if ITK_VERSION_MAJOR<5 ::ThreadedGenerateData( const RegionType& outputRegionForThread, ThreadIdType itkNotUsed(threadId) ) #else ::DynamicThreadedGenerateData( const RegionType& outputRegionForThread) #endif { // Pad image region enlarged along X RegionType enlargedRegionX = outputRegionForThread; enlargedRegionX.SetIndex(0, this->GetInput()->GetRequestedRegion().GetIndex(0) ); enlargedRegionX.SetSize(0, this->GetInput()->GetRequestedRegion().GetSize(0) ); enlargedRegionX.SetIndex(1, this->GetInput()->GetRequestedRegion().GetIndex(1) ); enlargedRegionX.SetSize(1, this->GetInput()->GetRequestedRegion().GetSize(1) ); FFTInputImagePointer paddedImage; paddedImage = PadInputImageRegion(enlargedRegionX); // FFT padded image typedef itk::RealToHalfHermitianForwardFFTImageFilter< FFTInputImageType > FFTType; typename FFTType::Pointer fftI = FFTType::New(); fftI->SetInput( paddedImage ); #if ITK_VERSION_MAJOR<5 fftI->SetNumberOfThreads( m_BackupNumberOfThreads ); #else fftI->SetNumberOfWorkUnits( m_BackupNumberOfThreads ); #endif fftI->Update(); //Multiply line-by-line or projection-by-projection (depends on kernel size) itk::ImageRegionIterator<typename FFTType::OutputImageType> itI(fftI->GetOutput(), fftI->GetOutput()->GetLargestPossibleRegion() ); itk::ImageRegionConstIterator<FFTOutputImageType> itK(m_KernelFFT, m_KernelFFT->GetLargestPossibleRegion() ); itI.GoToBegin(); while(!itI.IsAtEnd() ) { itK.GoToBegin(); while(!itK.IsAtEnd() ) { itI.Set(itI.Get() * itK.Get() ); ++itI; ++itK; } } //Inverse FFT image typedef itk::HalfHermitianToRealInverseFFTImageFilter< typename FFTType::OutputImageType > IFFTType; typename IFFTType::Pointer ifft = IFFTType::New(); ifft->SetInput( fftI->GetOutput() ); #if ITK_VERSION_MAJOR<5 ifft->SetNumberOfThreads( m_BackupNumberOfThreads ); #else ifft->SetNumberOfWorkUnits( m_BackupNumberOfThreads ); #endif ifft->SetReleaseDataFlag( true ); ifft->SetActualXDimensionIsOdd( paddedImage->GetLargestPossibleRegion().GetSize(0) % 2 ); ifft->Update(); // Crop and paste result itk::ImageRegionConstIterator<FFTInputImageType> itS(ifft->GetOutput(), outputRegionForThread); itk::ImageRegionIterator<OutputImageType> itD(this->GetOutput(), outputRegionForThread); itS.GoToBegin(); itD.GoToBegin(); while(!itS.IsAtEnd() ) { itD.Set( itS.Get() ); ++itS; ++itD; } } template<class TInputImage, class TOutputImage, class TFFTPrecision> typename FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision>::FFTInputImagePointer FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::PadInputImageRegion(const RegionType &inputRegion) { UpdateTruncationMirrorWeights(); RegionType paddedRegion = GetPaddedImageRegion(inputRegion); // Create padded image (spacing and origin do not matter) FFTInputImagePointer paddedImage = FFTInputImageType::New(); paddedImage->SetRegions(paddedRegion); paddedImage->Allocate(); paddedImage->FillBuffer(0); const long next = std::min(inputRegion.GetIndex(0) - paddedRegion.GetIndex(0), (typename FFTInputImageType::IndexValueType)this->GetTruncationCorrectionExtent() ); if(next) { typename FFTInputImageType::IndexType idx; typename FFTInputImageType::IndexType iidx; // Reference point (SA / SE) typename FFTInputImageType::IndexType::IndexValueType borderDist=0, rightIdx=0; // Mirror left (equation 3a in [Ohnesorge et al, Med Phys, 2000]) RegionType leftRegion = inputRegion; leftRegion.SetIndex(0, inputRegion.GetIndex(0)-next); leftRegion.SetSize(0, next); itk::ImageRegionIteratorWithIndex<FFTInputImageType> itLeft(paddedImage, leftRegion); while(!itLeft.IsAtEnd() ) { iidx = itLeft.GetIndex(); iidx[0] = leftRegion.GetIndex(0)+leftRegion.GetSize(0)+1; TFFTPrecision SA = this->GetInput()->GetPixel(iidx); for(unsigned int i=0; i<leftRegion.GetSize(0); i++, ++itLeft) { idx = itLeft.GetIndex(); borderDist = inputRegion.GetIndex(0)-idx[0]; idx[0] = inputRegion.GetIndex(0) + borderDist; itLeft.Set(m_TruncationMirrorWeights[ borderDist ] * (2.0*SA-this->GetInput()->GetPixel(idx)) ); } } // Mirror right (equation 3b in [Ohnesorge et al, Med Phys, 2000]) RegionType rightRegion = inputRegion; rightRegion.SetIndex(0, inputRegion.GetIndex(0)+inputRegion.GetSize(0) ); rightRegion.SetSize(0, next); itk::ImageRegionIteratorWithIndex<FFTInputImageType> itRight(paddedImage, rightRegion); while(!itRight.IsAtEnd() ) { iidx = itRight.GetIndex(); iidx[0] = rightRegion.GetIndex(0)-1; TFFTPrecision SE = this->GetInput()->GetPixel(iidx); for(unsigned int i=0; i<rightRegion.GetSize(0); i++, ++itRight) { idx = itRight.GetIndex(); rightIdx = inputRegion.GetIndex(0)+inputRegion.GetSize(0)-1; borderDist = idx[0]-rightIdx; idx[0] = rightIdx - borderDist; itRight.Set(m_TruncationMirrorWeights[ borderDist ] * (2.0*SE-this->GetInput()->GetPixel(idx)) ); } } } // Copy central part itk::ImageRegionConstIterator<InputImageType> itS(this->GetInput(), inputRegion); itk::ImageRegionIterator<FFTInputImageType> itD(paddedImage, inputRegion); itS.GoToBegin(); itD.GoToBegin(); while(!itS.IsAtEnd() ) { itD.Set(itS.Get() ); ++itS; ++itD; } return paddedImage; } template<class TInputImage, class TOutputImage, class TFFTPrecision> typename FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision>::RegionType FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::GetPaddedImageRegion(const RegionType &inputRegion) { RegionType paddedRegion = inputRegion; // Set x padding typename SizeType::SizeValueType xPaddedSize = m_ZeroPadFactors[0]*inputRegion.GetSize(0); while( GreatestPrimeFactor( xPaddedSize ) > m_GreatestPrimeFactor ) xPaddedSize++; paddedRegion.SetSize(0, xPaddedSize); long zeroext = ( (long)xPaddedSize - (long)inputRegion.GetSize(0) ) / 2; paddedRegion.SetIndex(0, inputRegion.GetIndex(0) - zeroext); // Set y padding. Padding along Y is only required if // - there is some windowing in the Y direction // - the DFT requires the size to be the product of given prime factors typename SizeType::SizeValueType yPaddedSize = inputRegion.GetSize(1); if(m_KernelDimension == 2) yPaddedSize *= m_ZeroPadFactors[1]; while( GreatestPrimeFactor( yPaddedSize ) > m_GreatestPrimeFactor ) yPaddedSize++; paddedRegion.SetSize(1, yPaddedSize); // TODO what's that in ScatterGlare long zeroexty = ((long)yPaddedSize - (long)inputRegion.GetSize(1)) / 2; paddedRegion.SetIndex(1, inputRegion.GetIndex(1) ); return paddedRegion; } template<class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::PrintSelf(std::ostream &os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "GreatestPrimeFactor: " << m_GreatestPrimeFactor << std::endl; } template<class TInputImage, class TOutputImage, class TFFTPrecision> bool FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::IsPrime( int n ) const { int last = (int)std::sqrt( double(n) ); for( int x=2; x<=last; x++ ) if( n%x == 0 ) return false; return true; } template<class TInputImage, class TOutputImage, class TFFTPrecision> int FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::GreatestPrimeFactor( int n ) const { int v = 2; while( v <= n ) if( n%v == 0 && IsPrime( v ) ) n /= v; else v += 1; return v; } template<class TInputImage, class TOutputImage, class TFFTPrecision> void FFTProjectionsConvolutionImageFilter<TInputImage, TOutputImage, TFFTPrecision> ::UpdateTruncationMirrorWeights() { const unsigned int next = this->GetTruncationCorrectionExtent(); if ( (unsigned int) m_TruncationMirrorWeights.size() != next) { m_TruncationMirrorWeights.resize(next+1); for(unsigned int i=0; i<next+1; i++) m_TruncationMirrorWeights[i] = pow( sin( (next-i)*itk::Math::pi/(2*next-2) ), 0.75); } } } // end namespace rtk #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "stdafx.h" #include "PluginJsonConstants.h" #include "..\..\AzureDeviceManagementCommon\DMConstants.h" #include "..\..\AzureDeviceManagementCommon\Plugins\PluginConstants.h" #include "WindowsUpdateHandler.h" #define CSPWritePath "./Device/Vendor/MSFT/Policy/Config/Update/" #define CSPReadPath "./Device/Vendor/MSFT/Policy/Result/Update/" #define CSPActiveHoursStart "ActiveHoursStart" #define CSPActiveHoursEnd "ActiveHoursEnd" #define CSPAllowAutoUpdate "AllowAutoUpdate" #define CSPAllowUpdateService "AllowUpdateService" #define CSPBranchReadinessLevel "BranchReadinessLevel" #define CSPDeferFeatureUpdatesPeriodInDays "DeferFeatureUpdatesPeriodInDays" #define CSPDeferQualityUpdatesPeriodInDays "DeferQualityUpdatesPeriodInDays" #define CSPPauseFeatureUpdates "PauseFeatureUpdates" #define CSPPauseQualityUpdates "PauseQualityUpdates" #define CSPScheduledInstallDay "ScheduledInstallDay" #define CSPScheduledInstallTime "ScheduledInstallTime" #define JsonActiveHoursStart "activeHoursStart" #define JsonActiveHoursEnd "activeHoursEnd" #define JsonAllowAutoUpdate "allowAutoUpdate" #define JsonAllowUpdateService "allowUpdateService" #define JsonBranchReadinessLevel "branchReadinessLevel" #define JsonDeferFeatureUpdatesPeriodInDays "deferFeatureUpdatesPeriodInDays" #define JsonDeferQualityUpdatesPeriodInDays "deferQualityUpdatesPeriodInDays" #define JsonPauseFeatureUpdates "pauseFeatureUpdates" #define JsonPauseQualityUpdates "pauseQualityUpdates" #define JsonScheduledInstallDay "scheduledInstallDay" #define JsonScheduledInstallTime "scheduledInstallTime" using namespace DMCommon; using namespace DMUtils; using namespace std; namespace Microsoft { namespace Azure { namespace DeviceManagement { namespace WindowsUpdatePlugin { WindowsUpdateHandler::WindowsUpdateHandler() : BaseHandler(WindowsUpdateHandlerId, ReportedSchema(JsonDeviceSchemasTypeRaw, JsonDeviceSchemasTagDM, 1, 1)) { } void WindowsUpdateHandler::Start( const Json::Value& handlerConfig, bool& active) { TRACELINE(LoggingLevel::Verbose, __FUNCTION__); SetConfig(handlerConfig); Json::Value logFilesPath = handlerConfig[JsonTextLogFilesPath]; if (!logFilesPath.isNull() && logFilesPath.isString()) { wstring wideLogFileName = MultibyteToWide(logFilesPath.asString().c_str()); wstring wideLogFileNamePrefix = MultibyteToWide(GetId().c_str()); gLogger.SetLogFilePath(wideLogFileName.c_str(), wideLogFileNamePrefix.c_str()); gLogger.EnableConsole(true); TRACELINE(LoggingLevel::Verbose, "Logging configured."); } active = true; } void WindowsUpdateHandler::OnConnectionStatusChanged( ConnectionStatus status) { TRACELINE(LoggingLevel::Verbose, __FUNCTION__); if (status == ConnectionStatus::eOffline) { TRACELINE(LoggingLevel::Verbose, "Connection Status: Offline."); } else { TRACELINE(LoggingLevel::Verbose, "Connection Status: Online."); } } void WindowsUpdateHandler::SetSubGroup( const Json::Value& groupDesiredConfigJson, const std::string& cspNodeId, const std::string& operationId, std::shared_ptr<DMCommon::ReportedErrorList> errorList) { RunOperation(operationId, errorList, [&]() { OperationModelT<int> operationDataModel = TryGetOptionalSinglePropertyOpIntParameter(groupDesiredConfigJson, operationId); if (operationDataModel.present) { string writePath = string(CSPWritePath) + cspNodeId; _mdmProxy.RunSet(writePath, operationDataModel.value); // Is configured? _isConfigured = true; } }); } void WindowsUpdateHandler::GetSubGroup( const std::string& cspNodeId, const std::string& operationId, Json::Value& reportedObject, std::shared_ptr<DMCommon::ReportedErrorList> errorList) { RunOperation(operationId, errorList, [&]() { string readPath = string(CSPReadPath) + cspNodeId; int readValue; _mdmProxy.TryGetNumber<int>(readPath, readValue); reportedObject[operationId] = Json::Value(readValue); }); } void WindowsUpdateHandler::BuildReported( Json::Value& reportedObject, std::shared_ptr<DMCommon::ReportedErrorList> errorList) { GetSubGroup(CSPActiveHoursStart, JsonActiveHoursStart, reportedObject, errorList); GetSubGroup(CSPActiveHoursEnd, JsonActiveHoursEnd, reportedObject, errorList); GetSubGroup(CSPAllowAutoUpdate, JsonAllowAutoUpdate, reportedObject, errorList); GetSubGroup(CSPAllowUpdateService, JsonAllowUpdateService, reportedObject, errorList); GetSubGroup(CSPBranchReadinessLevel, JsonBranchReadinessLevel, reportedObject, errorList); GetSubGroup(CSPDeferFeatureUpdatesPeriodInDays, JsonDeferFeatureUpdatesPeriodInDays, reportedObject, errorList); GetSubGroup(CSPDeferQualityUpdatesPeriodInDays, JsonDeferQualityUpdatesPeriodInDays, reportedObject, errorList); GetSubGroup(CSPPauseFeatureUpdates, JsonPauseFeatureUpdates, reportedObject, errorList); GetSubGroup(CSPPauseQualityUpdates, JsonPauseQualityUpdates, reportedObject, errorList); GetSubGroup(CSPScheduledInstallDay, JsonScheduledInstallDay, reportedObject, errorList); GetSubGroup(CSPScheduledInstallTime, JsonScheduledInstallTime, reportedObject, errorList); } void WindowsUpdateHandler::EmptyReported( Json::Value& reportedObject) { Json::Value nullValue; reportedObject[JsonActiveHoursStart] = nullValue; reportedObject[JsonActiveHoursEnd] = nullValue; reportedObject[JsonAllowAutoUpdate] = nullValue; reportedObject[JsonAllowUpdateService] = nullValue; reportedObject[JsonBranchReadinessLevel] = nullValue; reportedObject[JsonDeferFeatureUpdatesPeriodInDays] = nullValue; reportedObject[JsonDeferQualityUpdatesPeriodInDays] = nullValue; reportedObject[JsonPauseFeatureUpdates] = nullValue; reportedObject[JsonPauseQualityUpdates] = nullValue; reportedObject[JsonScheduledInstallDay] = nullValue; reportedObject[JsonScheduledInstallTime] = nullValue; } InvokeResult WindowsUpdateHandler::Invoke( const Json::Value& groupDesiredConfigJson) noexcept { TRACELINE(LoggingLevel::Verbose, __FUNCTION__); // Returned objects (if InvokeContext::eDirectMethod, it is returned to the cloud direct method caller). InvokeResult invokeResult(InvokeContext::eDesiredState); // Twin reported objects Json::Value reportedObject(Json::objectValue); std::shared_ptr<ReportedErrorList> errorList = make_shared<ReportedErrorList>(); RunOperation(GetId(), errorList, [&]() { // Make sure this is not a transient state if (IsRefreshing(groupDesiredConfigJson)) { return; } // Process Meta Data _metaData->FromJsonParentObject(groupDesiredConfigJson); // Apply new state SetSubGroup(groupDesiredConfigJson, CSPActiveHoursStart, JsonActiveHoursStart, errorList); SetSubGroup(groupDesiredConfigJson, CSPActiveHoursEnd, JsonActiveHoursEnd, errorList); SetSubGroup(groupDesiredConfigJson, CSPAllowAutoUpdate, JsonAllowAutoUpdate, errorList); SetSubGroup(groupDesiredConfigJson, CSPAllowUpdateService, JsonAllowUpdateService, errorList); SetSubGroup(groupDesiredConfigJson, CSPBranchReadinessLevel, JsonBranchReadinessLevel, errorList); SetSubGroup(groupDesiredConfigJson, CSPDeferFeatureUpdatesPeriodInDays, JsonDeferFeatureUpdatesPeriodInDays, errorList); SetSubGroup(groupDesiredConfigJson, CSPDeferQualityUpdatesPeriodInDays, JsonDeferQualityUpdatesPeriodInDays, errorList); SetSubGroup(groupDesiredConfigJson, CSPPauseFeatureUpdates, JsonPauseFeatureUpdates, errorList); SetSubGroup(groupDesiredConfigJson, CSPPauseQualityUpdates, JsonPauseQualityUpdates, errorList); SetSubGroup(groupDesiredConfigJson, CSPScheduledInstallDay, JsonScheduledInstallDay, errorList); SetSubGroup(groupDesiredConfigJson, CSPScheduledInstallTime, JsonScheduledInstallTime, errorList); // Report current state if (_metaData->GetReportingMode() == JsonReportingModeAlways) { BuildReported(reportedObject, errorList); } else { EmptyReported(reportedObject); } }); FinalizeAndReport(reportedObject, errorList); return invokeResult; } }}}}
;****************************************************************************** ;* ;* Adjustris - Block dropping puzzle game for Gameboy ;* ;* Written in 2017 by Dave VanEe (tbsp) dave.vanee@gmail.com ;* ;* To the extent possible under law, the author(s) have dedicated all copyright ;* and related and neighboring rights to this software to the public domain ;* worldwide. This software is distributed without any warranty. ;* ;* You should have received a copy of the CC0 Public Domain Dedication along with ;* this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. ;* ;****************************************************************************** INCLUDE "engine.inc" INCLUDE "gbhw.inc" INCLUDE "joypad.inc" INCLUDE "room_game.inc" INCLUDE "debug.inc" ;****************************************************************************** ;** Variables ** ;****************************************************************************** SECTION "Room Game Variables",WRAM0 game_exit: ds 1 ;****************************************************************************** ;** Data ** ;***************************************************************************** SECTION "Room Game Code/Data", ROM0 BACKGROUND_TILES: INCBIN "background.bin" SPRITE_TILES: INCBIN "sprites.bin" ;****************************************************************************** ;** Code ** ;***************************************************************************** ; ===== Game Loop ===== RoomGame:: call AlterPiece ; Input and Movement call DropPiece ; Automatic Movement call GameLogic ; Score Additions, GameMode Completion Checks call UpdateSprite ; Sprite Updates call RandomNumber ldh a,[FrameCounter] inc a cp 60 jr nz,.NoReset xor a .NoReset ldh [FrameCounter],a halt ; Wait for VBlank Interrupt nop jr RoomGame GameInit: xor a ; Clear VRAM ld hl,$8000 ld bc,$2000 call mem_Set ld hl,$C000 ld bc,$00A0 call mem_Set ld hl,$C0A3 ld bc,$0F5D call mem_Set ld hl,PieceEditorUI ld de,$9010 ld bc,16*21 call mem_Copy ld hl,Global_Blocks ld de,$8800 ld bc,16*16 call mem_Copy ld hl,Global_Blocks ld de,$8000 ld bc,16*16 call mem_Copy ld hl,Tiles_Numbers ; Load Numerical Tiles (Move to masterInit?) ld de,$9300 ld bc,$00A0 call mem_Copy ld hl,Tiles_Letters ld de,$9410 ; Load Alphabet Tiles ld bc,$01A0 call mem_Copy ld hl,Global_TextSymbols ld bc,16*8 call mem_Copy ; Additional Symbols ldh a,[SelectedSet] call CopyPieceSet ld hl,LinesCleared ; Initialize HiScores call ResetHiScore ld hl,BlocksUsed call ResetHiScore ld hl,TargetLines call ResetHiScore ld hl,CurrentScore call ResetHiScore ld hl,LinesToLvl call ResetHiScore ld hl,Level call ResetHiScore ld hl,TargetLines ld bc,LineLimitGoal call AddBCHiScore ld hl,LinesToLvl ; 10 Lines per level ld bc,LevelIncrement call AddBCHiScore ld hl,Level ld bc,$0001 call AddBCHiScore ld a,StartDropSpeed ldh [DropSet],a ldh [DropCounter],a ld a,40 ldh [ClearDelay],a xor a ldh [NextPiece],a ; Make random later...or something xor a ldh [UpdateHalf],a ldh [LineCount],a ldh [BlockCount],a ldh [TileUpdate],a ldh [BlocksInLastPiece],a call RandomNumber call RandomNumber ; Draw Basic Screen Layout ld hl,$9801 ; side walls ld de,$0020 ld a,$0F ld b,$12 .bglp0 ld [hl],a add hl,de dec b jr nz,.bglp0 ld hl,$980C ld de,$0020 ld a,$10 ld b,$12 .bglp1 ld [hl],a add hl,de dec b jr nz,.bglp1 ld hl,$980D ; next piece box ld de,$001A ld [hl],1 inc hl ld a,5 ld b,5 .bglp2 ld [hli],a dec b jr nz,.bglp2 ld [hl],2 add hl,de ld b,5 .bglp3 ld [hl],7 inc hl inc hl inc hl inc hl inc hl inc hl ld [hl],8 add hl,de dec b jr nz,.bglp3 ld [hl],3 inc hl ld a,6 ld b,5 .bglp4 ld [hli],a dec b jr nz,.bglp4 ld [hl],4 ; score/lines/level boxes ld hl,$98ED ld de,$0020 ld a,1 ld [hl],a add hl,de ld a,7 ld [hl],a add hl,de ld [hl],a add hl,de ld a,$13 ld [hl],a add hl,de ld a,7 ld [hl],a add hl,de ld [hl],a add hl,de ld a,$13 ld [hl],a add hl,de ld a,7 ld [hl],a add hl,de ld [hl],a add hl,de ld a,3 ld [hl],a ld hl,$98F3 ld a,2 ld [hl],a add hl,de ld a,8 ld [hl],a add hl,de ld [hl],a add hl,de ld a,$14 ld [hl],a add hl,de ld a,8 ld [hl],a add hl,de ld [hl],a add hl,de ld a,$14 ld [hl],a add hl,de ld a,8 ld [hl],a add hl,de ld [hl],a add hl,de ld a,4 ld [hl],a ld hl,$98EE ld a,5 ld bc,5 call mem_Set ld hl,$994E ld a,$15 ld bc,5 call mem_Set ld hl,$99AE ld bc,5 call mem_Set ld hl,$9A0E ld a,6 ld bc,5 call mem_Set ; Score/Lines/Level ld hl,Gameplay_Text ld de,$990E ld bc,5 call mem_Copy ld de,$996E ld bc,5 call mem_Copy ld de,$99CE ld bc,5 call mem_Copy ; Draw Window Map ld a,1 ld hl,$9C42 ld [hli],a ld a,5 ld bc,15 call mem_Set ld a,2 ld [hl],a ld a,3 ld hl,$9DA2 ld [hli],a ld a,6 ld bc,15 call mem_Set ld a,4 ld [hl],a ld a,7 ld hl,$9C62 ld de,$20 ld b,10 .win0lp ld [hl],a add hl,de dec b jr nz,.win0lp inc a ld hl,$9C72 ld b,10 .win1lp ld [hl],a add hl,de dec b jr nz,.win1lp ld hl,PauseText ld de,$9C87 ld bc,6 call mem_Copy ld de,$9CE5 ld bc,11 call mem_Copy ld de,$9D05 ld bc,11 call mem_Copy ld de,$9D44 ld bc,13 call mem_Copy ld de,$9D67 ld bc,7 call mem_Copy call GenerateBlock call GenerateBlock call GenerateNextBlockMap ld a,%00000001 ldh [$FF],a ; Enable VBlank Interrupt ld a,%11100011 ldh [rLCDC],a ; Turn on LCD ret AlterPiece: call ReadJoyPad call RandomNumber ldh a,[hPadPressed] and BUTTON_DOWN call nz,.DownPressed ldh a,[hPadHeld] and BUTTON_DOWN call nz,.DownHeld ldh a,[hPadPressed] and BUTTON_LEFT call nz,.LeftPressed ldh a,[hPadHeld] and BUTTON_LEFT call nz,.LeftHeld ldh a,[hPadPressed] and BUTTON_RIGHT call nz,.RightPressed ldh a,[hPadHeld] and BUTTON_RIGHT call nz,.RightHeld ldh a,[hPadPressed] and BUTTON_A jp nz,.APressed ldh a,[hPadPressed] and BUTTON_B jp nz,.BPressed ldh a,[hPadPressed] and BUTTON_START jr nz,.StartPressed ret .StartPressed ld a,%11100001 ; kill sprites ldh [rLCDC],a ld a,GUIDelay ldh [MenuDelay],a ld a,7 ldh [rWX],a .StartWait ldh a,[MenuDelay] cp 0 jr z,.Startok dec a ldh [MenuDelay],a jr .skip .Startok call ReadJoyPad ldh a,[hPadPressed] and BUTTON_START jr nz,.StartOut ldh a,[hPadPressed] and BUTTON_SELECT jr nz,.GiveUp .skip halt nop jr .StartWait .StartOut ld a,%00000001 ldh [$FF],a ld a,%11100011 ldh [rLCDC],a ld a,$A7 ldh [rWX],a ret .GiveUp ;pop hl pop hl ret .DownPressed push af ld a,1 .DownMove ldh [DHCount],a ld b,1 ld c,0 call GenerateBlockPhantom call TestBlockPhantom cp 0 jr nz,.dnmv call ConfirmBlockPhantom ld hl,FX_gameMove call MS_sfxM2 pop af ret .DownHeld push af ldh a,[DHCount] dec a ldh [DHCount],a jr nz,.dnmv ld a,1 ldh [DHCount],a .RushDrop ldh a,[DropCounter] cp 3 jr c,.dnmv ld a,3 ldh [DropCounter],a jr .dnmv .RightPressed push af ld a,HoldPause .RightMove ldh [RHCount],a ld b,0 ld c,1 call GenerateBlockPhantom call TestBlockPhantom cp 0 jr nz,.dnmv call ConfirmBlockPhantom ld hl,FX_gameMove call MS_sfxM2 .dnmv pop af ret .RightHeld push af ldh a,[RHCount] dec a ldh [RHCount],a jr nz,.dnmv ld a,HoldDelay jr .RightMove .LeftPressed push af ld a,HoldPause .LeftMove ldh [LHCount],a ld b,0 ld c,255 call GenerateBlockPhantom call TestBlockPhantom cp 0 jr nz,.dnmv call ConfirmBlockPhantom ld hl,FX_gameMove call MS_sfxM2 pop af ret .LeftHeld push af ldh a,[LHCount] dec a ldh [LHCount],a jr nz,.dnmv ld a,HoldDelay jr .LeftMove .BPressed push af ld bc,$0000 call GenerateBlockPhantom ld c,0 ; normal call RotateBlockPhantom call TestBlockPhantom cp 0 jr nz,.dnmv .cbrok call ConfirmBlockPhantom ld hl,FX_gameRotate call MS_sfxM1 pop af ret .APressed push af ld bc,$0000 call GenerateBlockPhantom ld c,1 ; opposite call RotateBlockPhantom call TestBlockPhantom cp 0 jp nz,.dnmv .cblok call ConfirmBlockPhantom ld hl,FX_gameRotate call MS_sfxM1 pop af ret UpdateSprite: ld hl,$C000 ld de,YX+1 ld a,[de] ; get tile # ld c,a inc de ld a,[de] ; get block count inc de inc de ; skip rot pair inc de ld b,a .lp ld a,[de] inc de add a,a add a,a add a,a add a,$10 ld [hli],a ld a,[de] inc de add a,a add a,a add a,a add a,$18 ld [hli],a ld a,c ld [hli],a ld a,$85 ld [hli],a dec b jr nz,.lp ret UpdateTiles: ldh a,[UpdateHalf] inc a ldh [UpdateHalf],a bit 0,a jr nz,.Bottom ; Top ld hl,$9802 ld de,Grid ; 3 jr .past .Bottom ld hl,$9922 ld de,Grid+9*10 ; 3 xor a ldh [TileUpdate],a .past ; 9 loops ld bc,$0016 ; x ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 add hl,bc ld a,[de] ; 2 inc e ; 2 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ld a,[de] ; 2 inc e ; 1 ld [hli],a ; 2 ret UpdateScoreTiles: ldh a,[GameMode] cp $F0 ret nc ; modes over $F0 have no score displayed ld hl,$998E ; 3 ld de,LinesCleared+1 ; 3 ld b,5 ; 2 .lpS0 ld a,[de] ; 2 (*6) add a,$30 ; 2 (*6) inc de ; 2 (*6) ld [hli],a ; 2 (*6) dec b ; 1 (*6) jr nz,.lpS0 ; 3 (3*5+2) ; = XX clocks ld de,CurrentScore+1 ; 3 ld hl,$992E ; 3 ld b,5 ; 2 .lpS1 ld a,[de] ; 2 add a,$30 ; 2 inc de ; 2 ld [hli],a ; 2 dec b ; 1 jr nz,.lpS1 ; 3 ; = 79 clocks ld hl,$99F1 ld de,Level+4 ld a,[de] add a,$30 ld [hli],a inc de ld a,[de] add a,$30 ld [hl],a ret GameLogic: ldh a,[GameMode] cp 0 jr z,.Infinite ret .Infinite ldh a,[LineCount] ; new math (just cases) cp 0 jr z,.Inf0 cp 1 jr z,.Inf1 cp 2 jr z,.Inf2 cp 3 jr z,.Inf3 cp 4 jr z,.Inf4 ;5 ld hl,2000 jr .InfGS .Inf4 ld hl,1200 jr .InfGS .Inf3 ld hl,600 jr .InfGS .Inf2 ld hl,200 jr .InfGS .Inf1 ld hl,80 jr .InfGS .Inf0 ld hl,0 .InfGS ldh a,[BlocksInLastPiece] add a,l ld b,h ld c,a ld hl,CurrentScore call AddBCHiScore ldh a,[LineCount] cp 0 jr z,.InfiniteBlocks ld hl,LinesCleared ld b,0 ld c,a call AddBCHiScore ld a,b ldh [LineCount],a .InfiniteBlocks ldh a,[BlockCount] cp 0 jr z,.InfiniteDone ld hl,BlocksUsed ld b,0 ld c,a call AddBCHiScore ld hl,LinesCleared ld de,LinesToLvl call CpHiScore jr c,.InfNoLevelUp ld hl,LinesToLvl ld bc,LevelIncrement call AddBCHiScore ld hl,FX_gamelaser call MS_sfxM1 ld hl,Level ld bc,$0001 call AddBCHiScore ldh a,[DropSet] cp MinDropSpeed jr z,.InfNoLevelUp dec a dec a dec a ldh [DropSet],a .InfNoLevelUp ld a,b ldh [BlockCount],a ldh [BlocksInLastPiece],a .InfiniteDone ret .LineLimit ldh a,[LineCount] cp 0 jr z,.LineLimitBlocks ld hl,LinesCleared ld b,0 ld c,a call AddBCHiScore ld a,b ldh [LineCount],a ld hl,LinesCleared ld de,TargetLines call CpHiScore jr c,.LineLimitBlocks ld a,1 ldh [BeatMode],a pop hl ret .LineLimitBlocks ldh a,[BlockCount] cp 0 jr z,.LineLimitDone ld hl,BlocksUsed ld b,0 ld c,a call AddBCHiScore ld hl,LinesCleared ld de,LinesToLvl call CpHiScore jr c,.LineLimitNoLevelUp ld hl,LinesToLvl ld bc,LevelIncrement call AddBCHiScore ld hl,Level ld bc,$0001 call AddBCHiScore ldh a,[DropSet] cp MinDropSpeed jr z,.LineLimitNoLevelUp dec a dec a dec a ldh [DropSet],a .LineLimitNoLevelUp ld a,b ldh [BlockCount],a .LineLimitDone ret CalcSetChecksum: cp ROM_Set_Count push af jr nc,.SRAM_Set ; ROM Set ld hl,ROM_Piece_Sets jr .copy_set .SRAM_Set sub ROM_Set_Count ld hl,SavedSets push af di ld a,$0A ld [$00],a ; activate SRAM pop af .copy_set inc hl ; skip first header byte ld c,a cp 0 jr z,.Set0 ; loop through pieces/blocks of every set to reach target set .lpSetsF ld a,[hli] cp $FE jr nz,.lpSetsF dec c jr nz,.lpSetsF .Set0 ; at the start of the set ld d,0 ; clear checksum ld a,[hli] ld b,a add a,d ld d,a ; include block count .lpPieces push bc ld a,[hli] ; include flags add a,d ld d,a inc hl ; skip tile type ld a,[hli] ; include block count ld b,a add a,d ld d,a ld a,[hli] ; include RotY add a,d ld d,a ld a,[hli] ; include RotX add a,d ld d,a .lpBlocks ld a,[hli] ; include Y add a,d ld d,a ld a,[hli] ; include X add a,d ld d,a dec b jr nz,.lpBlocks pop bc dec b jr nz,.lpPieces pop af cp ROM_Set_Count ; needed again? jr nc,.SRAM_Stop ret .SRAM_Stop xor a ld [$00],a ei ; d = checksum on return ret HiScoreHandler: ; Infinite ; offset to hiscore set of interest ld hl,SavedScores-19 ld de,19 ldh a,[SelectedSet] inc a .lpOffset add hl,de dec a jr nz,.lpOffset ; calculate set checksum push hl ldh a,[SelectedSet] Call CalcSetChecksum pop hl di ld a,$0A ld [$00],a ; enable sram ld a,[hl] cp d jr z,.SetUnchanged ; set has been modified, clear old scores ld [hl],d push hl inc hl ld a,$80 ld bc,18 call mem_Set ; initialize highscores for set pop hl .SetUnchanged inc hl xor a ld [$00],a ; disable sram ei ld a,2 ld de,TempScore push hl call ReadHiScore ld hl,TempScore ld de,CurrentScore call CpHiScore jr nc,.InfEx1Higher ld a,1 ld de,TempScore pop hl push hl call ReadHiScore ld hl,TempScore ld de,CurrentScore call CpHiScore jr nc,.NotThatHigh2 .k xor a ld de,TempScore pop hl push hl call ReadHiScore ld hl,TempScore ld de,CurrentScore call CpHiScore jr nc,.NotThatHigh1 .l ; 1st ld a,1 ld de,TempScore pop hl push hl push de call ReadHiScore ; read score 1 pop de ld a,2 pop hl push hl push de call SaveHiScore ; save as score 2 pop de xor a pop hl push hl push de call ReadHiScore ; read score 0 pop de ld a,1 pop hl push hl call SaveHiScore ; save as score 1 xor a pop hl push hl jr .ji .NotThatHigh1 ; 2nd ld a,1 ld de,TempScore pop hl push hl push de call ReadHiScore ; read score 1 pop de ld a,2 pop hl push hl call SaveHiScore ; save as score 2 ld a,1 pop hl push hl jr .ji .NotThatHigh2 ; 3rd ld a,2 .ji ld de,CurrentScore pop hl call SaveHiScore push hl .InfEx1Higher pop hl ret FillGrid: xor a ld hl,$C000 ld bc,$0020 call mem_Set ld hl,Grid ld d,$12 .lpWipe push de ld a,$12 ld bc,$000A call mem_Set ld a,1 ldh [TileUpdate],a halt nop halt nop pop de dec d jr nz,.lpWipe ret ClearLines: ld hl,Grid+10*17 ld c,$12 .Blp0 push hl ld b,$0A .Blp1 ld a,[hli] cp 0 jr z,.BNextLine dec b jr nz,.Blp1 dec hl ld d,h ld e,l ld hl,FX_gameID call MS_sfxM1 pop hl push hl push bc ld a,$11 ld b,$0A .BFillLine ld [hli],a dec b jr nz,.BFillLine ldh a,[GameMode] ldh [temp],a ld a,$FE ldh [GameMode],a ld a,1 ldh [TileUpdate],a ldh a,[ClearDelay] ld b,a .BVBL halt nop dec b jr nz,.BVBL ldh a,[temp] ldh [GameMode],a ld a,1 ldh [TileUpdate],a pop bc pop hl push hl dec hl push bc dec c .BDropBlock ld b,$0A .BDropLine ld a,[hld] ld [de],a dec de dec b jr nz,.BDropLine dec c jr nz,.BDropBlock xor a inc hl ld b,$0A .BClearLine ld [hli],a dec b jr nz,.BClearLine push hl ldh a,[LineCount] inc a ldh [LineCount],a ld hl,$C010 ; clear OAM... alter to be block count dynamic ld bc,$10 xor a call mem_Set pop hl pop bc pop hl inc c jr .BNoPop .BNextLine pop hl ld de,$FFF6 ; -10 add hl,de .BNoPop dec c jr nz,.Blp0 ret DropPiece: ldh a,[DropCounter] dec a ldh [DropCounter],a cp 0 ret nz ldh a,[DropSet] DBGMSG "Read DropSet as: %a%" ldh [DropCounter],a ld hl,MoveArray+2 ld a,[hli] ld b,a ld a,[hl] ld c,a call GenerateBlockPhantom call TestBlockPhantom cp 0 jr z,.drop ld hl,FX_gameBomb call MS_sfxM4 call UpdateSprite ; Ensure proper cover sprite location ld a,[BlockCount] inc a ldh [BlockCount],a ld a,1 ldh [TileUpdate],a ld a,[YX+2] ; skip flags and tile ldh [BlocksInLastPiece],a ; store # of blocks for scoring call FreezeBlock ld a,$FF ; block (greatly delay) dropping after a piece is frozen ldh [DHCount],a halt nop halt nop xor a ld hl,$C000 ld bc,25*4 call mem_Set call ClearLines call GenerateBlock ; Next Block call GenerateNextBlockMap ld bc,$00 call GenerateBlockPhantom call TestBlockPhantom jr z,.NoEndGame ; Start space is blocked pop hl ; Clear Stack .NoEndGame ret .drop call ConfirmBlockPhantom ret UpdateNextPiece: ldh a,[GameMode] cp $FF ret z ld hl,NextBlockMap ld de,$982E ld bc,5 call mem_Copy ld de,$984E ld bc,5 call mem_Copy ld de,$986E ld bc,5 call mem_Copy ld de,$988E ld bc,5 call mem_Copy ld de,$98AE ld bc,5 call mem_Copy ret ; 4 GenerateNextBlockMap: ; clear current map xor a ld hl,NextBlockMap ld bc,25 call mem_Set ld hl,Active_Piece_Set+1 ; skip piece count ldh a,[NextPiece] cp 0 jr z,.block0 ld b,a .lpPiece inc hl ; skip flag byte inc hl ; skip tile byte ld a,[hli] ; get block count inc hl inc hl ; skip rotation pair .lpBlocks inc hl inc hl dec a jr nz,.lpBlocks dec b jr nz,.lpPiece .block0 inc hl ; skip flag byte ld a,[hli] add a,$80 ld c,a ; store tile byte ld a,[hli] ld b,a ; store block count inc hl ; skip rotation pair inc hl ld de,NextBlockMap .BlockLoop push de ld a,[hli] cp 0 jr z,.Yzero push hl ld h,d ld l,e ld de,5 .Y add hl,de dec a jr nz,.Y ld d,h ld e,l pop hl .Yzero ld a,[hli] push hl ld h,0 ld l,a add hl,de ld d,h ld e,l pop hl ld a,c ld [de],a ; set block to tile pop de dec b jr nz,.BlockLoop ret GenerateBlock: ldh a,[NextPiece] ldh [BlockType],a .TryAgain ; get next piece call RandomNumber ld c,a ld a,[Active_Piece_Set] ; get # of pieces in set cp 1 jr z,.single_piece_set ld e,a call Unsigned_Multiply ld a,h ; only use high byte jr .GotShape .single_piece_set xor a .GotShape ldh [NextPiece],a ld hl,Active_Piece_Set inc hl ; skip piece count ldh a,[BlockType] cp 0 jr z,.block0 ld b,a .lpPiece inc hl ; skip flag byte inc hl ; skip tile byte ld a,[hli] ; get block count inc hl inc hl ; skip rotation pair .lpBlocks inc hl inc hl dec a jr nz,.lpBlocks dec b jr nz,.lpPiece .block0 ld a,[hli] ; get flag byte ld de,YX ld [de],a ; include flag byte inc de ld a,[hli] ld [de],a ; include tile byte inc de ld a,[hli] ld [de],a ; include block count inc de inc a ; increment to include rotation pair ld b,a .lp ld a,[hli] ld [de],a inc de ld a,[hli] add 3 ; calc X offset? ld [de],a inc de dec b jr nz,.lp xor a ldh [BlockRotate],a .noLoop ret ; Input: B=dY, C=dX GenerateBlockPhantom: ld hl,YX+2 ; skip flags and tile type ld de,YXt ld a,b ldh [temp],a ld a,[hli] ; get block count inc a ; include rotation pair ld b,a .lp push bc ldh a,[temp] ld b,a ld a,[hli] add a,b ld [de],a inc de ld a,[hli] add a,c ld [de],a inc de pop bc dec b jr nz,.lp ret TestBlockPhantom: ld a,[YX+2] ; get block count ld d,a ld hl,YXt+2 ; skip testing of rotation pair .lp ld a,[hli] cp 18 ret z ld b,a ld a,[hli] cp Width ret z cp 255 ret z ld c,a push hl push de call TestYX pop de pop hl cp 0 ret nz dec d jr nz,.lp ret ConfirmBlockPhantom: ld hl,YX+2 ; skip flags and tile type ld de,YXt ld a,[hli] inc a ; include block phantom sla a ; a*2 ld b,a .lp ld a,[de] inc de ld [hli],a dec b jr nz,.lp ret FreezeBlock: ld hl,YX+2 ld a,[hli] inc hl inc hl ; skip rot pair ld d,a .lp ld a,[hli] ld b,a ld a,[hli] ld c,a push hl push de call SetYX pop de pop hl dec d jr nz,.lp ret RotateBlockPhantom: ; for CW rotations: ; y2=(x1-x0)+y0 ; x2=-(y1-y0)+x0 ; setup x0,y0 pivot in de ld hl,YXt ld a,[hli] ld d,a ; get y0 ld a,[hli] ld e,a ; get x0 ; adjust for bits ld a,[YX] ; get flags byte bit 7,a ret z ; return if flagged not to rotate bit 5,a jr nz,.spin bit 4,a jr z,.not_done_yet res 4,a ld [YX],a ; store spin flag bit 6,a jr z,.cw jr .ccw .not_done_yet set 4,a ld [YX],a ; store spin flag bit 6,a jr z,.ccw jr .cw .spin bit 6,a jr z,.ccw .cw ld a,c cp 0 jr nz,.ccw1 .cw1 ld a,[YX+2] ; get block count ld b,a .lpcw ld a,[hli] ; get y1 sub d ; -y0 sub e ; -x0 cpl ; invert inc a ldh [temp],a ; store x2 for a bit ld a,[hl] ; get x1 ld c,a ; store x1 for a bit ldh a,[temp] ld [hld],a ; save x2 ld a,c ; get x1 back sub e ; -x0 add d ; +y0 ld [hli],a ; save y2 inc hl ; skip x dec b jr nz,.lpcw ret .ccw ld a,c cp 0 jr nz,.cw1 .ccw1 ld a,[YX+2] ; get block count ld b,a .lpccw ld a,[hli] ; get y1 sub d ; -y0 add e ; +x0 ldh [temp],a ; store x2 for a bit ld a,[hl] ; get x1 ld c,a ; store x1 for a bit ldh a,[temp] ld [hld],a ; save x2 ld a,c ; get x1 back cpl ; invert inc a add e ; +x0 add d ; +y0 ld [hli],a ; save y2 inc hl ; skip x dec b jr nz,.lpccw ret ; Input: B=Y, C=X ; Output: A=0 or 1 TestYX: ld hl,Grid ld de,Width inc b .lp0 dec b jr z,.X add hl,de jr .lp0 .X ld e,c add hl,de ld a,[hl] ret SetYX: ld hl,Grid ld de,Width inc b .lp0 dec b jr z,.X add hl,de jr .lp0 .X ld e,c add hl,de ld a,[YX+1] set 7,a ; use $80 base tiles ld [hl],a ret MoveArray: db 0,1,1,0,0,$FF,$FF,0,0,1,1,0 Gameplay_Text: db "SCORE" db "LINES" db "LEVEL" PauseText: db "PAUSED" db "PRESS START" db "TO CONTINUE" db "PRESS SELECT" db "TO QUIT"
#pragma once #include "Arduino.h" class GeodeticConverter { public: GeodeticConverter(float home_latitude = 0, float home_longitude = 0, float home_altitude = 0) { setHome(home_latitude, home_longitude, home_altitude); } void setHome(float home_latitude, float home_longitude, float home_altitude) { home_latitude_ = home_latitude; home_longitude_ = home_longitude; home_altitude_ = home_altitude; // Save NED origin home_latitude_rad_ = deg2Rad(home_latitude); home_longitude_rad_ = deg2Rad(home_longitude); // Compute ECEF of NED origin geodetic2Ecef(home_latitude_, home_longitude_, home_altitude_, &home_ecef_x_, &home_ecef_y_, &home_ecef_z_); } void getHome(float* latitude, float* longitude, float* altitude) { *latitude = home_latitude_; *longitude = home_longitude_; *altitude = home_altitude_; } void geodetic2Ecef(const float latitude, const float longitude, const float altitude, float* x, float* y, float* z) { // Convert geodetic coordinates to ECEF. // http://code.google.com/p/pysatel/source/browse/trunk/coord.py?r=22 float lat_rad = deg2Rad(latitude); float lon_rad = deg2Rad(longitude); float xi = sqrt(1 - kFirstEccentricitySquared * sin(lat_rad) * sin(lat_rad)); *x = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * cos(lon_rad); *y = (kSemimajorAxis / xi + altitude) * cos(lat_rad) * sin(lon_rad); *z = (kSemimajorAxis / xi * (1 - kFirstEccentricitySquared) + altitude) * sin(lat_rad); } void ecef2Geodetic(const float x, const float y, const float z, float* latitude, float* longitude, float* altitude) { // Convert ECEF coordinates to geodetic coordinates. // J. Zhu, "Conversion of Earth-centered Earth-fixed coordinates // to geodetic coordinates," IEEE Transactions on Aerospace and // Electronic Systems, vol. 30, pp. 957-961, 1994. float r = sqrt(x * x + y * y); float Esq = kSemimajorAxis * kSemimajorAxis - kSemiminorAxis * kSemiminorAxis; float F = 54 * kSemiminorAxis * kSemiminorAxis * z * z; float G = r * r + (1 - kFirstEccentricitySquared) * z * z - kFirstEccentricitySquared * Esq; float C = (kFirstEccentricitySquared * kFirstEccentricitySquared * F * r * r) / pow(G, 3); float S = cbrt(1 + C + sqrt(C * C + 2 * C)); float P = F / (3 * pow((S + 1 / S + 1), 2) * G * G); float Q = sqrt(1 + 2 * kFirstEccentricitySquared * kFirstEccentricitySquared * P); float r_0 = -(P * kFirstEccentricitySquared * r) / (1 + Q) + sqrt( 0.5 * kSemimajorAxis * kSemimajorAxis * (1 + 1.0 / Q) - P * (1 - kFirstEccentricitySquared) * z * z / (Q * (1 + Q)) - 0.5 * P * r * r); float U = sqrt(pow((r - kFirstEccentricitySquared * r_0), 2) + z * z); float V = sqrt( pow((r - kFirstEccentricitySquared * r_0), 2) + (1 - kFirstEccentricitySquared) * z * z); float Z_0 = kSemiminorAxis * kSemiminorAxis * z / (kSemimajorAxis * V); *altitude = static_cast<float>(U * (1 - kSemiminorAxis * kSemiminorAxis / (kSemimajorAxis * V))); *latitude = rad2Deg(atan((z + kSecondEccentricitySquared * Z_0) / r)); *longitude = rad2Deg(atan2(y, x)); } private: // Geodetic system parameters static constexpr float kSemimajorAxis = 6378137; static constexpr float kSemiminorAxis = 6356752.3142; static constexpr float kFirstEccentricitySquared = 6.69437999014 * 0.001; static constexpr float kSecondEccentricitySquared = 6.73949674228 * 0.001; static constexpr float kFlattening = 1 / 298.257223563; inline float rad2Deg(const float radians) { return (radians / M_PI) * 180.0; } inline float deg2Rad(const float degrees) { return (degrees / 180.0) * M_PI; } float home_latitude_rad_, home_latitude_; float home_longitude_rad_, home_longitude_; float home_altitude_; float home_ecef_x_; float home_ecef_y_; float home_ecef_z_; }; // class GeodeticConverter
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2016 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreHardwareIndexBuffer.h" #include "OgreHardwareBufferManager.h" #include "OgreDefaultHardwareBufferManager.h" namespace Ogre { //----------------------------------------------------------------------------- HardwareIndexBuffer::HardwareIndexBuffer(HardwareBufferManagerBase* mgr, IndexType idxType, size_t numIndexes, HardwareBuffer::Usage usage, bool useSystemMemory, bool useShadowBuffer) : HardwareBuffer(usage, useSystemMemory, useShadowBuffer) , mMgr(mgr) , mIndexType(idxType) , mNumIndexes(numIndexes) { // Calculate the size of the indexes switch (mIndexType) { case IT_16BIT: mIndexSize = sizeof(unsigned short); break; case IT_32BIT: mIndexSize = sizeof(unsigned int); break; } mSizeInBytes = mIndexSize * mNumIndexes; // Create a shadow buffer if required if (mUseShadowBuffer) { mShadowBuffer = OGRE_NEW DefaultHardwareIndexBuffer(mIndexType, mNumIndexes, HardwareBuffer::HBU_DYNAMIC); } } //----------------------------------------------------------------------------- HardwareIndexBuffer::~HardwareIndexBuffer() { if (mMgr) { mMgr->_notifyIndexBufferDestroyed(this); } OGRE_DELETE mShadowBuffer; } //----------------------------------------------------------------------------- HardwareIndexBufferSharedPtr::HardwareIndexBufferSharedPtr(HardwareIndexBuffer* buf) : SharedPtr<HardwareIndexBuffer>(buf) { } }