text stringlengths 1 1.05M |
|---|
; A236227: Sum of the nineteenth powers of the first n primes.
; Submitted by Christian Krause
; 524288,1162785755,19074649113880,11417969834487023,61170508418249033314,1523090798793695143991,240595526483945019991144,2219015182144258609115123,76834486109734969171023610,6180095732699726458749873279,27850757952670122653464150750,652782748943512250401741280123,5047118918612315409012225330484,15908890262272732023920520016391,74774182006152217331383243661974,651861489380646649723682281195491,5079663786068591098594312077725030,13421600009342019458210645925405771
mov $3,$0
mov $5,$0
add $5,1
lpb $5
mov $0,$3
sub $5,1
sub $0,$5
seq $0,40 ; The prime numbers.
mov $2,$0
pow $2,19
add $4,$2
lpe
mov $0,$4
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0xc942, %rsi
lea addresses_UC_ht+0x11142, %rdi
clflush (%rdi)
nop
nop
nop
nop
sub %r14, %r14
mov $4, %rcx
rep movsw
nop
nop
nop
nop
nop
cmp %r10, %r10
lea addresses_normal_ht+0x46d6, %rdx
nop
nop
add $35928, %r11
mov $0x6162636465666768, %r14
movq %r14, %xmm3
and $0xffffffffffffffc0, %rdx
movntdq %xmm3, (%rdx)
nop
nop
nop
and $47426, %r11
lea addresses_D_ht+0x1a142, %rsi
lea addresses_A_ht+0x2142, %rdi
nop
nop
cmp $24238, %rbx
mov $104, %rcx
rep movsq
nop
add %r11, %r11
lea addresses_WC_ht+0xa542, %rcx
nop
nop
nop
nop
nop
xor $56379, %r14
mov $0x6162636465666768, %rdx
movq %rdx, (%rcx)
and $36260, %rbx
lea addresses_WC_ht+0x7b42, %rbx
nop
nop
add $61300, %r11
movw $0x6162, (%rbx)
nop
sub $31829, %rdx
lea addresses_D_ht+0xd142, %rsi
lea addresses_WT_ht+0xd942, %rdi
nop
nop
dec %r11
mov $33, %rcx
rep movsb
nop
nop
nop
cmp %rcx, %rcx
lea addresses_D_ht+0x17942, %rsi
lea addresses_UC_ht+0x1c412, %rdi
nop
nop
add $53555, %r11
mov $33, %rcx
rep movsq
nop
nop
nop
nop
nop
dec %r10
lea addresses_UC_ht+0x9912, %rdx
nop
nop
nop
nop
nop
add %rdi, %rdi
vmovups (%rdx), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %r10
sub $53699, %rdx
lea addresses_D_ht+0x14d42, %r14
nop
cmp %rsi, %rsi
mov (%r14), %edx
nop
nop
nop
nop
nop
and $58938, %rbx
lea addresses_D_ht+0x7ac2, %rsi
lea addresses_UC_ht+0xd2da, %rdi
nop
nop
nop
sub %rdx, %rdx
mov $121, %rcx
rep movsb
nop
nop
xor $43543, %rcx
lea addresses_UC_ht+0x8198, %rsi
lea addresses_WC_ht+0x10272, %rdi
nop
nop
nop
and %r14, %r14
mov $79, %rcx
rep movsb
nop
nop
nop
nop
inc %rdi
lea addresses_WC_ht+0x1c3c2, %rbx
nop
nop
nop
nop
and %rcx, %rcx
mov $0x6162636465666768, %rdx
movq %rdx, %xmm4
movups %xmm4, (%rbx)
cmp $11738, %r14
lea addresses_D_ht+0x164e2, %r14
nop
nop
add $55059, %rbx
movb (%r14), %cl
nop
nop
nop
and $40530, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %r9
push %rbp
push %rcx
push %rdi
// Store
lea addresses_A+0x3142, %r9
nop
nop
nop
nop
sub %rdi, %rdi
mov $0x5152535455565758, %rcx
movq %rcx, %xmm7
movups %xmm7, (%r9)
nop
nop
nop
and $27181, %r9
// Store
mov $0xd42, %r8
dec %rbp
movl $0x51525354, (%r8)
// Exception!!!
nop
nop
nop
nop
nop
mov (0), %rbp
and $8927, %r12
// Store
mov $0x687a050000000842, %rcx
nop
nop
nop
and %r12, %r12
movl $0x51525354, (%rcx)
nop
add %r9, %r9
// Faulty Load
lea addresses_A+0x3142, %r12
nop
nop
nop
nop
add $43178, %r8
vmovups (%r12), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $1, %xmm2, %rbp
lea oracles, %r12
and $0xff, %rbp
shlq $12, %rbp
mov (%r12,%rbp,1), %rbp
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 6}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}, 'dst': {'same': True, 'congruent': 4, 'type': 'addresses_UC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 3}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 6}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2}}
{'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
*/
|
processor 6502
include "vcs.h"
include "macro.h"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Váriaveis
seg.u Variables
org $80
JetXPos byte
JetYPos byte
BomberXPos byte
BomberYPos byte
MissileXPos byte
MissileYPos byte
Score byte ;2 digit score
Timer byte ;2 digit timer
Temp byte ; variavel auxiliar para calcular o score e timer
OnesDigitOffset word
TensDigitOffset word
JetSpritePtr word
JetColorPtr word
BomberSpritePtr word
BomberColorPtr word
JetAnimOffset byte
Random byte
ScoreSprite byte
TimerSprite byte
TerrainColor byte
RiverColor byte
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Constantes
JET_HEIGHT = 9
JET_TOP_LIMIT = 77
JET_BOT_LIMIT = 1
JET_LEF_LIMIT = 101
JET_RIG_LIMIT = 31
BOMBER_HEIGHT = 9
DIGITS_HEIGHT = 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Code segment
seg Code
org $f000
Reset:
CLEAN_START
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Inicializar variáveis
lda #10
sta JetYPos
lda #63
sta JetXPos
lda #83
sta BomberYPos
lda #54
sta BomberXPos
lda #%11010100
sta Random
lda #0
sta Score
sta Timer
lda #%00010000 ;seta o missile0 no tamanho 2x
sta NUSIZ0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Inicializar ponteiros
lda #<JetSprite
sta JetSpritePtr
lda #>JetSprite
sta JetSpritePtr+1
lda #<JetColor
sta JetColorPtr
lda #>JetColor
sta JetColorPtr+1
lda #<BomberSprite
sta BomberSpritePtr
lda #>BomberSprite
sta BomberSpritePtr+1
lda #<BomberColor
sta BomberColorPtr
lda #>BomberColor
sta BomberColorPtr+1
StartFrame:
; 1 + 3 lines of VSYNC
lda #2
sta VBLANK ; liga o VBLANK
sta VSYNC ; liga o VSYNC
REPEAT 3
sta WSYNC ; aguarda as 3 linhas do VSYNC
REPEND
lda #0
sta VSYNC ; desliga o VSYNC
; 37 lines of underscan
REPEAT 34
sta WSYNC ; mostra 34 linhas do VBLANK o resto são os ciclos do processamento abaixo até completar 37
REPEND
; VBLANK processing
lda JetXPos
ldy #0
jsr SetObjectXPos
lda BomberXPos
ldy #1
jsr SetObjectXPos
lda MissileXPos
ldy #2
jsr SetObjectXPos
jsr CalculateDigitOffset ; calcula o offset do digito
jsr JetSound
sta WSYNC
sta HMOVE
lda #0
sta VBLANK ; turn off VBLANK
; Scoreboard
lda #0
sta COLUBK
sta PF0
sta PF1
sta PF2
sta GRP0
sta GRP1
sta CTRLPF
sta COLUBK
lda #$1E
sta COLUPF
ldx #DIGITS_HEIGHT
.ScoreDigitLoop:
; Score
ldy TensDigitOffset
lda Digits,Y
and #$F0
sta ScoreSprite
ldy OnesDigitOffset
lda Digits,Y
and #$0F
ora ScoreSprite
sta ScoreSprite
sta WSYNC
sta PF1
;Timer
ldy TensDigitOffset+1
lda Digits,Y
and #$F0
sta TimerSprite
ldy OnesDigitOffset+1
lda Digits,Y
and #$0F
ora TimerSprite
sta TimerSprite
jsr Sleep12Cycles
sta PF1
ldy ScoreSprite
sta WSYNC
sty PF1
inc TensDigitOffset
inc TensDigitOffset+1
inc OnesDigitOffset
inc OnesDigitOffset+1
jsr Sleep12Cycles
dex
sta PF1
bne .ScoreDigitLoop
sta WSYNC
lda #0
sta PF0
sta PF1
sta PF2
sta WSYNC
sta WSYNC
sta WSYNC
sta WSYNC
GameVisibleLine:
lda TerrainColor
sta COLUPF
lda RiverColor
sta COLUBK
lda #%00000001
sta CTRLPF ; refletir o playfield
; Desenha o playfield
lda #$F0
sta PF0
lda #$FC
sta PF1
lda #0
sta PF2
ldx #88 ; conta as scanlines remanecentes usando kernel * 2 ou seja 89 * 2 scanlines = 178
; as 21 faltantes são desenhadas ao longo do processamento
.GameLineLoop:
lda #%00000000
cpx MissileYPos
bne .SkipMissileDraw
.MissileDraw:
lda #%00000010
inc MissileYPos
.SkipMissileDraw:
sta ENAM0
.AreWeInsideJetSprite:
txa
sec
sbc JetYPos
cmp #JET_HEIGHT
bcc .DrawSpriteP0
lda #0
.DrawSpriteP0:
clc
adc JetAnimOffset ;pular para o frame correto para gerar a animação de curva
tay
lda (JetSpritePtr),Y
sta WSYNC
sta GRP0
lda (JetColorPtr),Y
sta COLUP0
.AreWeInsideBomberSprite:
txa
sec
sbc BomberYPos
cmp #BOMBER_HEIGHT
bcc .DrawSpriteP1
lda #0
.DrawSpriteP1:
tay
lda #%00000101
sta NUSIZ1
lda (BomberSpritePtr),Y
sta WSYNC
sta GRP1
lda (BomberColorPtr),Y
sta COLUP1
dex
bne .GameLineLoop
lda #0
sta JetAnimOffset
sta WSYNC
; 30 linhas do overscan
lda #2
sta VBLANK ; liga o VBLANK de novo para o overscan
REPEAT 26
sta WSYNC ; desenha as 26 linhas do overscan as 4 faltantes é o processamento de colisão abaixo
REPEND
lda #0
sta VBLANK ; desliga o VBLANK
; Joystick
CheckP0up:
lda #%00010000
bit SWCHA
bne CheckP0Down
lda #JET_TOP_LIMIT
cmp JetYPos
bmi CheckP0Down
.P0UpPressed:
inc JetYPos
lda #0
sta JetAnimOffset
CheckP0Down:
lda #%00100000
bit SWCHA
bne CheckP0Left
lda #JET_BOT_LIMIT
cmp JetYPos
bpl CheckP0Left
.P0DownPressed:
dec JetYPos
lda #0
sta JetAnimOffset
CheckP0Left:
lda #%01000000
bit SWCHA
bne CheckP0Right
lda #JET_RIG_LIMIT
cmp JetXPos
bpl CheckP0Right
.P0LeftPressed:
dec JetXPos
lda #JET_HEIGHT
sta JetAnimOffset
CheckP0Right:
lda #%10000000
bit SWCHA
bne CheckButtonPressed
lda #JET_LEF_LIMIT
cmp JetXPos
bmi CheckButtonPressed
.P0RightPressed:
inc JetXPos
lda #JET_HEIGHT
sta JetAnimOffset
CheckButtonPressed:
lda #%10000000
bit INPT4
bne EndInputCheck
.ButtonPressed:
lda JetXPos
clc
adc #5
sta MissileXPos
clc
adc #8
lda JetYPos
clc
adc #2
sta MissileYPos
EndInputCheck:
; Atualizar posições para o próximo frame
UpdateBomberPosition:
lda BomberYPos
clc
cmp #0
bmi .ResetBomberPosition
dec BomberYPos
jmp EndPositionUpdate
.ResetBomberPosition
jsr GetRandomBomberPos ; pegar uma posicao aleatória para o bomber
.SetTimerValues
sed
lda Timer
clc
adc #1
sta Timer
cld
EndPositionUpdate:
; Check Colisões
CheckCollisionP0P1:
lda #%10000000 ;CXPPMM bit 7 detecta colisao do P0 com P1
bit CXPPMM ;Checa o registrador CXPPMM teve a colisão acima
bne .P0P1Collided ;Se colidir vai para o tratamento da colisão
jsr SetTerrainRiverColor
jmp CheckCollisionM0P1
.P0P1Collided:
jsr GameOver
CheckCollisionM0P1: ;Checa a colisão do missil com o avião inimigo Bomber
lda #%10000000
bit CXM0P
bne .M0P1Collided
jmp EndCollisionCheck
.M0P1Collided:
sed
lda Score
clc
adc #1
sta Score
cld
lda #0
sta MissileYPos ; Some o missil
jsr GetRandomBomberPos ; Gera um novo bomber
EndCollisionCheck:
sta CXCLR
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Loopback to new frame
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
jmp StartFrame
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Audio do aviao e vai mudar o PITCH de acordo com a posição Y
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
JetSound:
lda #3
sta AUDV0
lda JetYPos
lsr
lsr
lsr
sta Temp
lda #31
sec
sbc Temp
sta AUDF0
lda #8
sta AUDC0
rts
SetTerrainRiverColor subroutine
lda #$C2
sta TerrainColor
lda #$84
sta RiverColor
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Subroutine to handle object horizontal position with fine offset
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A is the target x-coordinate position in pixels of our object
;; Y is the object type (0:player0, 1:player1, 2:missile0, 3:missile1, 4:ball)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
SetObjectXPos subroutine
sta WSYNC ; start a fresh new scanline
sec ; make sure carry-flag is set before subtracion
.Div15Loop
sbc #15 ; subtract 15 from accumulator
bcs .Div15Loop ; loop until carry-flag is clear
eor #7 ; handle offset range from -8 to 7
asl
asl
asl
asl ; four shift lefts to get only the top 4 bits
sta HMP0,Y ; store the fine offset to the correct HMxx
sta RESP0,Y ; fix object position in 15-step increment
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; GameOver
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GameOver subroutine
lda #$30
sta TerrainColor
sta RiverColor
lda #$0
sta Score
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Subrotina para gerar um numero aleatorio
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; dividir por 4 e adicionar 30 para caber dentro do Rio no mapa
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
GetRandomBomberPos subroutine
lda Random
asl
eor Random
asl
eor Random
asl
asl
eor Random
asl
rol Random
lsr ; Divide por 2
lsr ; Divide por 2 totalizando divisão por 4
sta BomberXPos
lda #30
adc BomberXPos
sta BomberXPos
lda #96
sta BomberYPos
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Calcula o endereco de memoria para escolher o offset certo do digito
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; cada sprite do score tem o tamanho de 5, então você tem que multiplicar
;; por 5 para encontrar o sprite correto
;; Para multiplicar vc shifita 2 vezes para multiplicar por 4 e soma
;; mais uma vez o próprio valor. (N*2*2)+N
;;
;; PAra a outra parte precisa dividir por 16 e multiplicar por 5
;; Para isso precisa fazer N/16*5 = ((N/2/2)+(N/2/2/2/2)) * 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
CalculateDigitOffset subroutine
ldx #1
.PrepareScoreLoop: ; Loopa 2 vezes 1 para o timer outra para o score
lda Score,X ; Load acumulator com o timer X=1 Timer X=0 Score
and #%00001111
sta Temp ; salva o valor do A no temp
asl
asl
adc Temp
sta OnesDigitOffset,X
lda Score,X
and #%11110000
lsr
lsr
sta Temp
lsr
lsr
adc Temp
sta TensDigitOffset,X
dex
bpl .PrepareScoreLoop
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Desperdica ciclos para sincronizar com o TIA (Race the Beam)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Sleep12Cycles subroutine
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Declare ROM lookup tables
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Digits:
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %00110011 ; ## ##
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %00010001 ; # #
.byte %01110111 ; ### ###
.byte %00100010 ; # #
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01010101 ; # # # #
.byte %01100110 ; ## ##
.byte %01010101 ; # # # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01000100 ; # #
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %01100110 ; ## ##
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01010101 ; # # # #
.byte %01100110 ; ## ##
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01110111 ; ### ###
.byte %01110111 ; ### ###
.byte %01000100 ; # #
.byte %01100110 ; ## ##
.byte %01000100 ; # #
.byte %01000100 ; # #
JetSprite:
.byte #%00000000 ;
.byte #%00010100 ; # #
.byte #%01111111 ; #######
.byte #%00111110 ; #####
.byte #%00011100 ; ###
.byte #%00011100 ; ###
.byte #%00001000 ; #
.byte #%00001000 ; #
.byte #%00001000 ; #
JetSpriteTurn:
.byte #%00000000 ;
.byte #%00001000 ; #
.byte #%00111110 ; #####
.byte #%00011100 ; ###
.byte #%00011100 ; ###
.byte #%00011100 ; ###
.byte #%00001000 ; #
.byte #%00001000 ; #
.byte #%00001000 ; #
BomberSprite:
.byte #%00000000 ;
.byte #%00001000 ; #
.byte #%00001000 ; #
.byte #%00101010 ; # # #
.byte #%00111110 ; #####
.byte #%01111111 ; #######
.byte #%00101010 ; # # #
.byte #%00001000 ; #
.byte #%00011100 ; ###
JetColor:
.byte #$34;
.byte #$34;
.byte #$02;
.byte #$02;
.byte #$C8;
.byte #$1C;
.byte #$04;
.byte #$06;
.byte #$0A;
JetColorTurn:
.byte #$34;
.byte #$34;
.byte #$02;
.byte #$02;
.byte #$C8;
.byte #$1C;
.byte #$04;
.byte #$06;
.byte #$0A;
BomberColor:
.byte #$00
.byte #$32
.byte #$32
.byte #$0E
.byte #$40
.byte #$40
.byte #$40
.byte #$40
.byte #$40
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Epilogue
org $fffc
.word Reset ; reset vector
.word Reset ; BRK vector |
var1: defl 0
var1: equ 99
|
// Copyright (c) 2015-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
// Copyright (c) 2017-2019 The PIVX developers
// Copyright (c) 2019 The JACK developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "torcontrol.h"
#include "utilstrencodings.h"
#include "netbase.h"
#include "net.h"
#include "util.h"
#include "crypto/hmac_sha256.h"
#include <vector>
#include <deque>
#include <set>
#include <stdlib.h>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/signals2/signal.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/thread.h>
/** Default control port */
const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:9051";
/** Tor cookie size (from control-spec.txt) */
static const int TOR_COOKIE_SIZE = 32;
/** Size of client/server nonce for SAFECOOKIE */
static const int TOR_NONCE_SIZE = 32;
/** For computing serverHash in SAFECOOKIE */
static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
/** For computing clientHash in SAFECOOKIE */
static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
/** Exponential backoff configuration - initial timeout in seconds */
static const float RECONNECT_TIMEOUT_START = 1.0;
/** Exponential backoff configuration - growth factor */
static const float RECONNECT_TIMEOUT_EXP = 1.5;
/** Maximum length for lines received on TorControlConnection.
* tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
* this is belt-and-suspenders sanity limit to prevent memory exhaustion.
*/
static const int MAX_LINE_LENGTH = 100000;
/****** Low-level TorControlConnection ********/
/** Reply from Tor, can be single or multi-line */
class TorControlReply
{
public:
TorControlReply() { Clear(); }
int code;
std::vector<std::string> lines;
void Clear()
{
code = 0;
lines.clear();
}
};
/** Low-level handling for Tor control connection.
* Speaks the SMTP-like protocol as defined in torspec/control-spec.txt
*/
class TorControlConnection
{
public:
typedef boost::function<void(TorControlConnection&)> ConnectionCB;
typedef boost::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
/** Create a new TorControlConnection.
*/
TorControlConnection(struct event_base *base);
~TorControlConnection();
/**
* Connect to a Tor control port.
* target is address of the form host:port.
* connected is the handler that is called when connection is successfully established.
* disconnected is a handler that is called when the connection is broken.
* Return true on success.
*/
bool Connect(const std::string &target, const ConnectionCB& connected, const ConnectionCB& disconnected);
/**
* Disconnect from Tor control port.
*/
bool Disconnect();
/** Send a command, register a handler for the reply.
* A trailing CRLF is automatically added.
* Return true on success.
*/
bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
/** Response handlers for async replies */
boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
private:
/** Callback when ready for use */
boost::function<void(TorControlConnection&)> connected;
/** Callback when connection lost */
boost::function<void(TorControlConnection&)> disconnected;
/** Libevent event base */
struct event_base *base;
/** Connection to control socket */
struct bufferevent *b_conn;
/** Message being received */
TorControlReply message;
/** Response handlers */
std::deque<ReplyHandlerCB> reply_handlers;
/** Libevent handlers: internal */
static void readcb(struct bufferevent *bev, void *ctx);
static void eventcb(struct bufferevent *bev, short what, void *ctx);
};
TorControlConnection::TorControlConnection(struct event_base *_base):
base(_base), b_conn(0)
{
}
TorControlConnection::~TorControlConnection()
{
if (b_conn)
bufferevent_free(b_conn);
}
void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
struct evbuffer *input = bufferevent_get_input(bev);
size_t n_read_out = 0;
char *line;
assert(input);
// If there is not a whole line to read, evbuffer_readln returns NULL
while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != NULL)
{
std::string s(line, n_read_out);
free(line);
if (s.size() < 4) // Short line
continue;
// <status>(-|+| )<data><CRLF>
self->message.code = atoi(s.substr(0,3));
self->message.lines.push_back(s.substr(4));
char ch = s[3]; // '-','+' or ' '
if (ch == ' ') {
// Final line, dispatch reply and clean up
if (self->message.code >= 600) {
// Dispatch async notifications to async handler
// Synchronous and asynchronous messages are never interleaved
self->async_handler(*self, self->message);
} else {
if (!self->reply_handlers.empty()) {
// Invoke reply handler with message
self->reply_handlers.front()(*self, self->message);
self->reply_handlers.pop_front();
} else {
LogPrint("tor", "tor: Received unexpected sync reply %i\n", self->message.code);
}
}
self->message.Clear();
}
}
// Check for size of buffer - protect against memory exhaustion with very long lines
// Do this after evbuffer_readln to make sure all full lines have been
// removed from the buffer. Everything left is an incomplete line.
if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
self->Disconnect();
}
}
void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
{
TorControlConnection *self = (TorControlConnection*)ctx;
if (what & BEV_EVENT_CONNECTED) {
LogPrint("tor", "tor: Successfully connected!\n");
self->connected(*self);
} else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
if (what & BEV_EVENT_ERROR) {
LogPrint("tor", "tor: Error connecting to Tor control socket\n");
} else {
LogPrint("tor", "tor: End of stream\n");
}
self->Disconnect();
self->disconnected(*self);
}
}
bool TorControlConnection::Connect(const std::string &target, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
{
if (b_conn)
Disconnect();
// Parse target address:port
struct sockaddr_storage connect_to_addr;
int connect_to_addrlen = sizeof(connect_to_addr);
if (evutil_parse_sockaddr_port(target.c_str(),
(struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
LogPrintf("tor: Error parsing socket address %s\n", target);
return false;
}
// Create a new socket, set up callbacks and enable notification bits
b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
if (!b_conn)
return false;
bufferevent_setcb(b_conn, TorControlConnection::readcb, NULL, TorControlConnection::eventcb, this);
bufferevent_enable(b_conn, EV_READ|EV_WRITE);
this->connected = _connected;
this->disconnected = _disconnected;
// Finally, connect to target
if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
LogPrintf("tor: Error connecting to address %s\n", target);
return false;
}
return true;
}
bool TorControlConnection::Disconnect()
{
if (b_conn)
bufferevent_free(b_conn);
b_conn = 0;
return true;
}
bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
{
if (!b_conn)
return false;
struct evbuffer *buf = bufferevent_get_output(b_conn);
if (!buf)
return false;
evbuffer_add(buf, cmd.data(), cmd.size());
evbuffer_add(buf, "\r\n", 2);
reply_handlers.push_back(reply_handler);
return true;
}
/****** General parsing utilities ********/
/* Split reply line in the form 'AUTH METHODS=...' into a type
* 'AUTH' and arguments 'METHODS=...'.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
*/
static std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
{
size_t ptr=0;
std::string type;
while (ptr < s.size() && s[ptr] != ' ') {
type.push_back(s[ptr]);
++ptr;
}
if (ptr < s.size())
++ptr; // skip ' '
return make_pair(type, s.substr(ptr));
}
/** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
* Returns a map of keys to values, or an empty map if there was an error.
* Grammar is implicitly defined in https://spec.torproject.org/control-spec by
* the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
* and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
*/
static std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
{
std::map<std::string,std::string> mapping;
size_t ptr=0;
while (ptr < s.size()) {
std::string key, value;
while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
key.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
if (s[ptr] == ' ') // The remaining string is an OptArguments
break;
++ptr; // skip '='
if (ptr < s.size() && s[ptr] == '"') { // Quoted string
++ptr; // skip opening '"'
bool escape_next = false;
while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
// Repeated backslashes must be interpreted as pairs
escape_next = (s[ptr] == '\\' && !escape_next);
value.push_back(s[ptr]);
++ptr;
}
if (ptr == s.size()) // unexpected end of line
return std::map<std::string,std::string>();
++ptr; // skip closing '"'
/**
* Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
*
* For future-proofing, controller implementors MAY use the following
* rules to be compatible with buggy Tor implementations and with
* future ones that implement the spec as intended:
*
* Read \n \t \r and \0 ... \377 as C escapes.
* Treat a backslash followed by any other character as that character.
*/
std::string escaped_value;
for (size_t i = 0; i < value.size(); ++i) {
if (value[i] == '\\') {
// This will always be valid, because if the QuotedString
// ended in an odd number of backslashes, then the parser
// would already have returned above, due to a missing
// terminating double-quote.
++i;
if (value[i] == 'n') {
escaped_value.push_back('\n');
} else if (value[i] == 't') {
escaped_value.push_back('\t');
} else if (value[i] == 'r') {
escaped_value.push_back('\r');
} else if ('0' <= value[i] && value[i] <= '7') {
size_t j;
// Octal escape sequences have a limit of three octal digits,
// but terminate at the first character that is not a valid
// octal digit if encountered sooner.
for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
// Tor restricts first digit to 0-3 for three-digit octals.
// A leading digit of 4-7 would therefore be interpreted as
// a two-digit octal.
if (j == 3 && value[i] > '3') {
j--;
}
escaped_value.push_back(strtol(value.substr(i, j).c_str(), NULL, 8));
// Account for automatic incrementing at loop end
i += j - 1;
} else {
escaped_value.push_back(value[i]);
}
} else {
escaped_value.push_back(value[i]);
}
}
value = escaped_value;
} else { // Unquoted value. Note that values can contain '=' at will, just no spaces
while (ptr < s.size() && s[ptr] != ' ') {
value.push_back(s[ptr]);
++ptr;
}
}
if (ptr < s.size() && s[ptr] == ' ')
++ptr; // skip ' ' after key=value
mapping[key] = value;
}
return mapping;
}
/** Read full contents of a file and return them in a std::string.
* Returns a pair <status, string>.
* If an error occurred, status will be false, otherwise status will be true and the data will be returned in string.
*
* @param maxsize Puts a maximum size limit on the file that is read. If the file is larger than this, truncated data
* (with len > maxsize) will be returned.
*/
static std::pair<bool,std::string> ReadBinaryFile(const std::string &filename, size_t maxsize=std::numeric_limits<size_t>::max())
{
FILE *f = fopen(filename.c_str(), "rb");
if (f == NULL)
return std::make_pair(false,"");
std::string retval;
char buffer[128];
size_t n;
while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
// Check for reading errors so we don't return any data if we couldn't
// read the entire file (or up to maxsize)
if (ferror(f))
return std::make_pair(false,"");
retval.append(buffer, buffer+n);
if (retval.size() > maxsize)
break;
}
fclose(f);
return std::make_pair(true,retval);
}
/** Write contents of std::string to a file.
* @return true on success.
*/
static bool WriteBinaryFile(const std::string &filename, const std::string &data)
{
FILE *f = fopen(filename.c_str(), "wb");
if (f == NULL)
return false;
if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
fclose(f);
return false;
}
fclose(f);
return true;
}
/****** Bitcoin specific TorController implementation ********/
/** Controller that connects to Tor control socket, authenticate, then create
* and maintain a ephemeral hidden service.
*/
class TorController
{
public:
TorController(struct event_base* base, const std::string& target);
~TorController();
/** Get name fo file to store private key in */
std::string GetPrivateKeyFile();
/** Reconnect, after getting disconnected */
void Reconnect();
private:
struct event_base* base;
std::string target;
TorControlConnection conn;
std::string private_key;
std::string service_id;
bool reconnect;
struct event *reconnect_ev;
float reconnect_timeout;
CService service;
/** Cookie for SAFECOOKIE auth */
std::vector<uint8_t> cookie;
/** ClientNonce for SAFECOOKIE auth */
std::vector<uint8_t> clientNonce;
/** Callback for ADD_ONION result */
void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHENTICATE result */
void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for AUTHCHALLENGE result */
void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback for PROTOCOLINFO result */
void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
/** Callback after successful connection */
void connected_cb(TorControlConnection& conn);
/** Callback after connection lost or failed connection attempt */
void disconnected_cb(TorControlConnection& conn);
/** Callback for reconnect timer */
static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
};
TorController::TorController(struct event_base* _base, const std::string& _target):
base(_base),
target(_target), conn(base), reconnect(true), reconnect_ev(0),
reconnect_timeout(RECONNECT_TIMEOUT_START)
{
reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
if (!reconnect_ev)
LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
// Start connection attempts immediately
if (!conn.Connect(_target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Initiating connection to Tor control port %s failed\n", _target);
}
// Read service private key if cached
std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
if (pkf.first) {
LogPrint("tor", "tor: Reading cached private key from %s\n", GetPrivateKeyFile());
private_key = pkf.second;
}
}
TorController::~TorController()
{
if (reconnect_ev) {
event_free(reconnect_ev);
reconnect_ev = 0;
}
if (service.IsValid()) {
RemoveLocal(service);
}
}
void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: ADD_ONION successful\n");
for (const std::string &s : reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
service_id = i->second;
if ((i = m.find("PrivateKey")) != m.end())
private_key = i->second;
}
if (service_id.empty()) {
LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
for (const std::string &s : reply.lines) {
LogPrintf(" %s\n", SanitizeString(s));
}
return;
}
LookupNumeric(std::string(service_id+".onion").c_str(), service, GetListenPort());
LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
LogPrint("tor", "tor: Cached service private key to %s\n", GetPrivateKeyFile());
} else {
LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile());
}
AddLocal(service, LOCAL_MANUAL);
// ... onion requested - keep connection open
} else if (reply.code == 510) { // 510 Unrecognized command
LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
} else {
LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
}
}
void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: Authentication successful\n");
// Now that we know Tor is running setup the proxy for onion addresses
// if -onion isn't set to something else.
if (GetArg("-onion", "") == "") {
CService resolved;
assert(LookupNumeric("127.0.0.1", resolved, 9050));
CService addrOnion = CService(resolved, 9050);
SetProxy(NET_TOR, addrOnion);
SetLimited(NET_TOR, false);
}
// Finally - now create the service
if (private_key.empty()) // No private key, generate one
private_key = "NEW:RSA1024"; // Explicitly request RSA1024 - see issue #9214
// Request hidden service, redirect port.
// Note that the 'virtual' port doesn't have to be the same as our internal port, but this is just a convenient
// choice. TODO; refactor the shutdown sequence some day.
_conn.Command(strprintf("ADD_ONION %s Port=%i,127.0.0.1:%i", private_key, GetListenPort(), GetListenPort()),
boost::bind(&TorController::add_onion_cb, this, _1, _2));
} else {
LogPrintf("tor: Authentication failed\n");
}
}
/** Compute Tor SAFECOOKIE response.
*
* ServerHash is computed as:
* HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
* CookieString | ClientNonce | ServerNonce)
* (with the HMAC key as its first argument)
*
* After a controller sends a successful AUTHCHALLENGE command, the
* next command sent on the connection must be an AUTHENTICATE command,
* and the only authentication string which that AUTHENTICATE command
* will accept is:
*
* HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
* CookieString | ClientNonce | ServerNonce)
*
*/
static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
{
CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
computeHash.Write(cookie.data(), cookie.size());
computeHash.Write(clientNonce.data(), clientNonce.size());
computeHash.Write(serverNonce.data(), serverNonce.size());
computeHash.Finalize(computedHash.data());
return computedHash;
}
void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
LogPrint("tor", "tor: SAFECOOKIE authentication challenge successful\n");
std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
if (l.first == "AUTHCHALLENGE") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
if (m.empty()) {
LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
return;
}
std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
LogPrint("tor", "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
if (serverNonce.size() != 32) {
LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
return;
}
std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
if (computedServerHash != serverHash) {
LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
return;
}
std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
_conn.Command("AUTHENTICATE " + HexStr(computedClientHash), boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
}
} else {
LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
}
}
void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
if (reply.code == 250) {
std::set<std::string> methods;
std::string cookiefile;
/*
* 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
* 250-AUTH METHODS=NULL
* 250-AUTH METHODS=HASHEDPASSWORD
*/
for (const std::string &s : reply.lines) {
std::pair<std::string,std::string> l = SplitTorReplyLine(s);
if (l.first == "AUTH") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("METHODS")) != m.end())
boost::split(methods, i->second, boost::is_any_of(","));
if ((i = m.find("COOKIEFILE")) != m.end())
cookiefile = i->second;
} else if (l.first == "VERSION") {
std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("Tor")) != m.end()) {
LogPrint("tor", "tor: Connected to Tor version %s\n", i->second);
}
}
}
for (const std::string &s : methods) {
LogPrint("tor", "tor: Supported authentication method: %s\n", s);
}
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
/* Authentication:
* cookie: hex-encoded ~/.tor/control_auth_cookie
* password: "password"
*/
std::string torpassword = GetArg("-torpassword", "");
if (!torpassword.empty()) {
if (methods.count("HASHEDPASSWORD")) {
LogPrint("tor", "tor: Using HASHEDPASSWORD authentication\n");
boost::replace_all(torpassword, "\"", "\\\"");
_conn.Command("AUTHENTICATE \"" + torpassword + "\"", boost::bind(&TorController::auth_cb, this, _1, _2));
} else {
LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
}
} else if (methods.count("NULL")) {
LogPrint("tor", "tor: Using NULL authentication\n");
_conn.Command("AUTHENTICATE", boost::bind(&TorController::auth_cb, this, _1, _2));
} else if (methods.count("SAFECOOKIE")) {
// Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
LogPrint("tor", "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
// _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), boost::bind(&TorController::auth_cb, this, _1, _2));
cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
GetRandBytes(&clientNonce[0], TOR_NONCE_SIZE);
_conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), boost::bind(&TorController::authchallenge_cb, this, _1, _2));
} else {
if (status_cookie.first) {
LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
} else {
LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
}
}
} else if (methods.count("HASHEDPASSWORD")) {
LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
} else {
LogPrintf("tor: No supported authentication method\n");
}
} else {
LogPrintf("tor: Requesting protocol info failed\n");
}
}
void TorController::connected_cb(TorControlConnection& _conn)
{
reconnect_timeout = RECONNECT_TIMEOUT_START;
// First send a PROTOCOLINFO command to figure out what authentication is expected
if (!_conn.Command("PROTOCOLINFO 1", boost::bind(&TorController::protocolinfo_cb, this, _1, _2)))
LogPrintf("tor: Error sending initial protocolinfo command\n");
}
void TorController::disconnected_cb(TorControlConnection& _conn)
{
// Stop advertising service when disconnected
if (service.IsValid())
RemoveLocal(service);
service = CService();
if (!reconnect)
return;
LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);
// Single-shot timer for reconnect. Use exponential backoff.
struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
if (reconnect_ev)
event_add(reconnect_ev, &time);
reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
}
void TorController::Reconnect()
{
/* Try to reconnect and reestablish if we get booted - for example, Tor
* may be restarting.
*/
if (!conn.Connect(target, boost::bind(&TorController::connected_cb, this, _1),
boost::bind(&TorController::disconnected_cb, this, _1) )) {
LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", target);
}
}
std::string TorController::GetPrivateKeyFile()
{
return (GetDataDir() / "onion_private_key").string();
}
void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
{
TorController *self = (TorController*)arg;
self->Reconnect();
}
/****** Thread ********/
static struct event_base *gBase;
static boost::thread torControlThread;
static void TorControlThread()
{
TorController ctrl(gBase, GetArg("-torcontrol", DEFAULT_TOR_CONTROL));
event_base_dispatch(gBase);
}
void StartTorControl(boost::thread_group& threadGroup/*, CScheduler& scheduler*/)
{
assert(!gBase);
#ifdef WIN32
evthread_use_windows_threads();
#else
evthread_use_pthreads();
#endif
gBase = event_base_new();
if (!gBase) {
LogPrintf("tor: Unable to create event_base\n");
return;
}
torControlThread = boost::thread(boost::bind(&TraceThread<void (*)()>, "torcontrol", &TorControlThread));
}
void InterruptTorControl()
{
if (gBase) {
LogPrintf("tor: Thread interrupt\n");
event_base_loopbreak(gBase);
}
}
void StopTorControl()
{
// timed_join() avoids the wallet not closing during a repair-restart. For a 'normal' wallet exit
// it behaves for our cases exactly like the normal join()
if (gBase) {
#if BOOST_VERSION >= 105000
torControlThread.try_join_for(boost::chrono::seconds(1));
#else
torControlThread.timed_join(boost::posix_time::seconds(1));
#endif
event_base_free(gBase);
gBase = 0;
}
} |
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %r8
push %r9
push %rdi
push %rdx
lea addresses_A_ht+0x16d75, %r12
nop
nop
xor %r14, %r14
movb $0x61, (%r12)
nop
nop
sub $34653, %rdi
lea addresses_WC_ht+0xef1d, %r8
nop
nop
nop
nop
add $50269, %rdx
mov (%r8), %r9d
xor $44514, %r14
lea addresses_A_ht+0x6de3, %r9
cmp $19008, %r8
movups (%r9), %xmm0
vpextrq $0, %xmm0, %rdi
nop
nop
nop
nop
nop
sub $39462, %r14
lea addresses_WC_ht+0x22dd, %r14
xor $46493, %rdi
movups (%r14), %xmm3
vpextrq $0, %xmm3, %r8
nop
cmp $36692, %rdx
pop %rdx
pop %rdi
pop %r9
pop %r8
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
// Load
lea addresses_US+0x104fd, %r11
clflush (%r11)
nop
nop
cmp $64172, %rdx
vmovups (%r11), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $1, %xmm6, %rdi
nop
nop
nop
nop
nop
xor %r11, %r11
// Store
lea addresses_WT+0x38fd, %r8
nop
nop
sub $38853, %rsi
movw $0x5152, (%r8)
nop
nop
nop
dec %rdi
// Store
lea addresses_WT+0x7355, %rcx
nop
nop
sub %r13, %r13
movw $0x5152, (%rcx)
nop
nop
nop
cmp %rdi, %rdi
// Faulty Load
lea addresses_WC+0xcfd, %r13
nop
nop
sub $51637, %r11
movb (%r13), %dl
lea oracles, %rcx
and $0xff, %rdx
shlq $12, %rdx
mov (%rcx,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 2}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'00': 13}
00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
#ifndef HOG_READER_HPP_GUARD
#define HOG_READER_HPP_GUARD
//===----------------------------------------------------------------------===//
//
// The Descent map loader
//
// NAME : HogReader
// PURPOSE : Providing a decoder and wrapper for the Descent .HOG format.
// COPYRIGHT : (c) 2011 Sean Donnellan. All Rights Reserved.
// AUTHORS : Sean Donnellan (darkdonno@gmail.com)
// DESCRIPTION : A decoder for the HOG file format that is used by Parallax
// Software in the computer game, Descent.
//
// The file format is as follows:
//
// - Magic number which is 3 bytes and corresponding to the
// string "DHF"
// - A series of files which are preceded by a short header,
// which describes the name of the file and the numer of bytes.
//
// | "DHF" - 3 bytes
// |---------------- Start of the first file
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
// |---------------- The next header/file comes straight after.
// | filename - 13 bytes
// | size - 4 bytes
// | data - the size of this part is by the size before it.
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <vector>
#include <stdint.h>
class HogReaderIterator;
struct HogFileHeader
{
char name[13]; // Padded to 13 bytes with \0.
uint32_t size; // The filesize as N bytes.
};
// Warning: The above structure is padded on x86 so you can not just read in the
// whole thing.
class HogReader
{
public:
typedef HogReaderIterator iterator;
HogReader(const char* filename);
~HogReader();
bool IsValid() const;
// Returns true if the file was succesfully opened and the magic header is
// correct.
bool NextFile();
std::vector<uint8_t> CurrentFile();
// Returns a copy of the data for the current file after reading it.
const char* CurrentFileName() const;
unsigned int CurrentFileSize() const;
iterator begin();
iterator end();
private:
FILE* myFile;
uint8_t myHeader[3];
bool hasReadFile;
HogFileHeader myChildFile;
};
#endif |
JUC r6 start_menu ///calls start_game.
start_Game:
JAL r6 initlevel
JAL r6 INIT_GreenGhost
mainGameLoop:
JAL r6 GreenGhost_UPDATE_STATE
JAL r6 GreenGhost_Draw_GLYPH
JUC r6 mainGameLoop
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
//register usage: r14 used to save return address of this function.
//registers r0, r1 destroyed as general purpose, r4 used to store state address
// STATES:
// For the '0' states, the state feild will evaluate to 0 if masked with 0x0F (15).
// the ZERO ('0') states are where GreenGhost is centered on a tile.
// In the 0 state GreenGhost will continue MOVIng forward unless the player inputs a direction
// if GreenGhost reaches any state0 and a ghost position is this tile, nextstate is dead1.
//
// 0x10: GreenGhostUP0 (16) --centered on tile, facing up. nextstate will be up1, unless player input
// 0x20: GreenGhostDOWN0 (32) --centered on tile, facing down. nextstate is player input direction, else down1
// 0x30: GreenGhostLEFT0 (48) --centered on tile, facing left. nextstate is player input direction, else left1
// 0x40: GreenGhostRIGHT0 (64) --centered on tile, facing right. nextstate is player input direction, else right1
// The rest of the states are defined with the following pattern
// the number in parenthesis is the decimal value.
//
// 0x11 UP1 (17) //nextstate up2, if player inputs down then nextstate down0
// 0x12 UP2 (18) //nextstate up3, if player pushes down then nextstate down3
// 0x13 UP3 (19) //nextstate up0, if player pushes down then nextstate down2
//
// 0x21 DOWN1 (33) //nextstate down2, if player inputs up then nextstate up0
// 0x22 DOWN2 (34) //nextstate down3, if player inputs up then nextstate up3
// 0x23 DOWN3 (35) //nextstate down0, if player inputs up then nextstate up2
//
// 0x31 LEFT1 (49) //nextstate left2, if player inputs right then nextstate right0
// 0x32 LEFT2 (50) //nextstate left3, if player inputs right then nextstate right3
// 0x33 LEFT3 (51) //nextstate left0, if player inputs right then nextstate right2
//
// 0x41 RIGHT1 (65) //nextstate right2, if player inputs right then nextstate left0
// 0x42 RIGHT2 (66) //nextstate right3, if player inputs right then nextstate left3
// 0x43 RIGHT3 (67) //nextstate right0, if player inputs right then nextstate left2
//
/////THIS FUNCTION UPDATES STATEMACHINE BY ONE STEP.
//
// The first thing it does is check the timer. If the timer is not active, it immediately leaves.
// Otherwise:
// check what state GreenGhost is in
// check controller input accordingly,
// update state & position variables
// reset timer
//
GreenGhost_UPDATE_STATE:
MOV r15 r14 //store old return adress
LUI 255 r0 //check timer by making address
ORI 240 r0
LOAD r0 r0 //then loading its value and cmp to 1
CMPI 1 r0
JNE r6 endGreenGhostStateUpdate //if timer was not active, do not update state.
// //else, continue on to update GreenGhost state:
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::GET CURRENT STATE ADDRESS::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CURRENT STATE state address 12801, store address in r4
LUI 50 r4
ORI 1 r4 //store address in r4
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::ZERO STATES::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// If in a ZERO state:
// check if on a ghost, if so die.
// otherwise, check player input in all directions and start MOVIng.
// if player has made no input selections, keep going in current direction.
// CHECK IF GreenGhost HIT GHOST: (Any ghost position is on GreenGhosts square)
// if hit, set nextstate to dead,
// jump to reset timer to progress to next state.
//
// if position = AnyGhostPosition
// nextstate = GreenGhostDEAD1
// JUC endGreenGhostState_SetTimer
//Check if in a '0' state:
LOAD r1 r4 //read current state, address in r4
MOV r1 r0 //copy STATE into temp register.
ANDI 15 r0 //mask it by ANDing it with 0xF (15)
CMPI 0 r0 //if masked value is not zero, check if it is in another state
JNE r6 GGUpStates //by branching to the next comparison, to check if it is an upstate
//check if up/down controls are pushed:
state0_updown:
JAL r6 CheckUP //CheckUP is a function that checks if controller up button is pushed
MOV r0 r1 //store the result of checkup in r1
JAL r6 CheckDOWN //CheckDOWN is a function that checks if controller down button is pushed
CMP r0 r1 //compare the results of both checkup and checkdown, by comparing r1 and r0
BEQ state0_leftright //if controller UP/DOWN are pushed together, input could be left or right
CMPI 1 r0 //Else, check if down was pushed. r0 will be 1 if down was pushed
BEQ GreenGhostTryMoveDOWN
BUC GreenGhostTryMoveUP
//check if left/right controls are pushed:
state0_leftright:
JAL r6 CheckRIGHT //CheckLEFT is a function that checks if controller up button is pushed
MOV r0 r1 //store the result of checkLEFT in r1
JAL r6 CheckLEFT //CheckRIGHT is a function that checks if controller right button is pushed
CMP r0 r1 //compare the results of both checkup and checkdown, by comparing r1 and r0
BEQ GGstate0_NoInput //if controller LEFT/RIGHT are pushed together and up/down was not processed exclusively, entire dpad pushed
CMPI 1 r0 //Else, check if RIGHT was pushed. r0 will be 1 if right was pushed
BEQ GreenGhostTryMoveLEFT
BUC GreenGhostTryMoveRIGHT
GGstate0_NoInput:
LOAD r1 r4 //load state
CMPI 16 r1 //check if in up0 state.
BEQ GreenGhostMoveUP //if not in up0 state, check if in down0 state
CMPI 32 r1 //check if in down0 state.
BEQ GreenGhostMoveDOWN //if not in down0 state, check if in left0 state, else:
CMPI 48 r1 //check if in left0 state.
BEQ GreenGhostMoveLEFT
CMPI 64 r1 //check if in right0 state.
BEQ GreenGhostMoveRIGHT //if not in right0 state, do not update state.
JUC r6 endGreenGhostState_SetTimer
GreenGhostMoveUP:
JAL r6 GreenGhost_isWallUP
CMPI 1 r0 //check if wall is above
JEQ r6 endGreenGhostState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setStateUP call
JAL r6 setStateUP1 // set GreenGhost state to up1
JUC r6 endGreenGhostState_SetTimer
GreenGhostMoveDOWN:
JAL r6 GreenGhost_isWallDOWN
CMPI 1 r0 //check if wall is below
JEQ r6 endGreenGhostState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN1 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GreenGhostMoveLEFT:
JAL r6 GreenGhost_isWallLEFT
CMPI 1 r0 //check if wall is left
JEQ r6 endGreenGhostState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT1 // set GreenGhost state to left1
JUC r6 endGreenGhostState_SetTimer
GreenGhostMoveRIGHT:
JAL r6 GreenGhost_isWallRIGHT
CMPI 1 r0 //check if wall is right
JEQ r6 endGreenGhostState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT1 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GreenGhostTryMoveUP:
JAL r6 GreenGhost_isWallUP
CMPI 1 r0 //check if wall is above
JEQ r6 GGstate0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setStateUP call
JAL r6 setStateUP1 // set GreenGhost state to up1
JUC r6 endGreenGhostState_SetTimer
GreenGhostTryMoveDOWN:
JAL r6 GreenGhost_isWallDOWN
CMPI 1 r0 //check if wall is below
JEQ r6 GGstate0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN1 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GreenGhostTryMoveLEFT:
JAL r6 GreenGhost_isWallLEFT
CMPI 1 r0 //check if wall is left
JEQ r6 GGstate0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT1 // set GreenGhost state to left1
JUC r6 endGreenGhostState_SetTimer
GreenGhostTryMoveRIGHT:
JAL r6 GreenGhost_isWallRIGHT
CMPI 1 r0 //check if wall is right
JEQ r6 GGstate0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT1 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
////:::::::::::::::::::::::End Zero States::::::::::::::::::::::::::
GGUpStates:
//if we are traveling up and not centered on a tile, we will
//continue to travel up, thus only the down button must be checked.
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP1:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP1:
LOAD r1 r4 //read current state, address in r4
CMPI 17 r1 //if state is GreenGhostUP1
BNE GreenGhostUP2
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE GGUP1Cont
UP1Rev:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGUP1Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP2:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP2:
LOAD r1 r4 //read current state, address in r4
CMPI 18 r1 //if state is GreenGhostUP2
BNE GreenGhostUP3
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE GGUP2Cont
//if button isnt pushed, skip to up2cont otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGUP2Cont:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI 53 r1 //adding one
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP3:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP3:
LOAD r1 r4 //read current state, address in r4
CMPI 19 r1 //if state is GreenGhostUP3
BNE GreenGhostDOWN1
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE GGUP3Cont
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGUP3Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGDownStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN1:::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN1:
LOAD r1 r4 //read current state, address in r4
CMPI 33 r1 //if state is GreenGhostDOWN1
BNE GreenGhostDOWN2
JAL r6 CheckUP //check if control is pushed
CMPI 1 r0
BNE GGD1C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGD1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN2:
LOAD r1 r4 //read current state, address in r4
CMPI 34 r1 //if state is GreenGhostDOWN2
BNE GreenGhostDOWN3
JAL r6 CheckUP //check if control is pushed
CMPI 1 r0
BNE GGD2C
//if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP3 // set GreenGhost state //and storing back to position address in r0
JUC r6 endGreenGhostState_SetTimer
GGD2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI -53 r1 //adding one
STOR r1 r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN3:
LOAD r1 r4 //read current state, address in r4
CMPI 35 r1 //check state
BNE GreenGhostLEFT1 //
JAL r6 CheckUP //check if down control is pushed
CMPI 1 r0
BNE GGD3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGD3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGLeftStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT1:
LOAD r1 r4 //read current state, address in r4
CMPI 49 r1 //check state
BNE GreenGhostLEFT2
JAL r6 CheckRIGHT //check if control is pushed
CMPI 1 r0
BNE GGL1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGL1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT2:
LOAD r1 r4 //read current state, address in r4
CMPI 50 r1 //check state
BNE GreenGhostLEFT3
JAL r6 CheckRIGHT //check if control is pushed
CMPI 1 r0
BNE GGL2C
//if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGL2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI 1 r1 //adding one
JAL r6 SetPosition_WarpLeftSide //setting it to either its position or the 'warp' position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT3:
LOAD r1 r4 //read current state, address in r4
CMPI 51 r1 //check state
BNE GreenGhostRIGHT1 //
JAL r6 CheckRIGHT //check if down control is pushed
CMPI 1 r0
BNE GGL3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGL3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGRightStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT1:
LOAD r1 r4 //read current state, address in r4
CMPI 65 r1 //check state
BNE GreenGhostRIGHT2
JAL r6 CheckLEFT //check if control is pushed
CMPI 1 r0
BNE GGR1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGR1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT2::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT2:
LOAD r1 r4 //read current state, address in r4
CMPI 66 r1 //check state
BNE GreenGhostRIGHT3
JAL r6 CheckLEFT //check if control is pushed
CMPI 1 r0
BNE GGR2C //if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGR2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI -1 r1 //adding one
JAL r6 SetPosition_WarpRightSide //set position to warped side or current position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT3:
LOAD r1 r4 //read current state, address in r4
CMPI 67 r1 //check state
BNE endGreenGhostState_SetTimer //
JAL r6 CheckLEFT //check if LEFT control is pushed
CMPI 1 r0
BNE GGR3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
GGR3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
endGreenGhostState_SetTimer:
LUI 255 r0 //make timer reset address
ORI 241 r0
MOVI 55 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
endGreenGhostStateUpdate:
MOV r14 r15 //restore old return adress
RETX //return
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::GreenGhostDraw GLYPH:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhost_Draw_GLYPH:
//GreenGhost's GreenGhostDraw glyph
//check if not edible
// if not edible GreenGhostDraw normal
// if edible check flash state:
// if blue: GreenGhostDraw blue ghost
// if lblue: GreenGhostDraw lblue ghost
//MAKE GreenGhost LOCATION ADDRESS IN r2
LUI 50 r2
//MAKE GreenGhost STATE ADDRESS IN r3
LUI 50 r3
ORI 1 r3
//load location of GreenGhost INTO r0
LOAD r0 r2
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 0:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP0
GreenGhostDrawUP0:
load r5 r3
CMPI 16 r5
BNE GreenGhostDrawUP1 //else check if in state UP1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP0
BUC GG_Eat1_UP0
GG_Normal_UP0:
MOV r0 r1
MOVI 107 r0 //GGHOST_UP_0
STOR r0 r1
ADDI -53 r1 //get location below GreenGhost
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_UP0:
MOV r0 r1
MOVI 51 r0 //E1GHOST_UP_0
STOR r0 r1
ADDI -53 r1 //get location below
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_UP0:
MOV r0 r1
MOVI 79 r0 //E2GHOST_UP0
STOR r0 r1
ADDI -53 r1 //get location below
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 1:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP1
GreenGhostDrawUP1:
LOAD R5 R3
CMPI 17 r5
BNE GreenGhostDrawUP2 //else check if in state UP2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP1
BUC GG_Eat1_UP1
GG_Normal_UP1:
MOV r0 r1
MOVI 113 r0 //GHOST_UP_6
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 112 r0 //GHOST_UP_5
STOR r0 r1
RETX
GG_Eat0_Up1:
MOVI 57 R1 //E1GHOST_UP_6
STOR R1 R0
ADDI 53 R0
MOVI 56 R1 //E1GHOST_UP_5
STOR R1 R0
RETX
GG_Eat1_Up1:
MOVI 85 R1 //E2GHOST_UP6
STOR R1 R0
ADDI 53 R0
MOVI 84 R1 //E2GHOST_UP5
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 2:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP2
GreenGhostDrawUP2:
LOAD R5 R3
CMPI 18 r5
BNE GreenGhostDrawUP3 //else check if in state UP3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP2
BUC GG_Eat1_UP2
GG_Normal_UP2:
MOV r0 r1
MOVI 111 r0 //GHOST_UP_4
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 110 r0 //GHOST_UP_3
STOR r0 r1
RETX
GG_Eat0_Up2:
MOVI 55 R1 //E1GHOST_UP_4
STOR R1 R0
ADDI 53 R0
MOVI 54 R1 //E1GHOST_UP_3
STOR R1 R0
RETX
GG_Eat1_Up2:
MOVI 83 R1 //E2GHOST_UP_4
STOR R1 R0
ADDI 53 R0
MOVI 82 R1 //E2GHOST_UP_3
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 3:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP3
GreenGhostDrawUP3:
LOAD R5 R3
CMPI 19 r5
BNE GreenGhostDrawDOWN0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP3
BUC GG_Eat1_UP3
GG_Normal_UP3:
MOV r0 r1
MOVI 108 r0 //GHOST_UP_1
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 109 r0 //GHOST_UP_2
STOR r0 r1
RETX
GG_Eat0_Up3:
MOVI 52 R1 //E1GHOST_UP_1
STOR R1 R0
ADDI -53 R0
MOVI 53 R1 //E1GHOST_UP_2
STOR R1 R0
RETX
GG_Eat1_Up3:
MOVI 80 R1 //E2GHOST_UP_1
STOR R1 R0
ADDI -53 R0
MOVI 81 R1 //E2GHOST_UP_2
STOR R1 R0 //LOAD INTO POSITION
RETX
//COPY AND PASTE FROM UP STATES!!
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN0
GreenGhostDrawDOWN0:
load r5 r3
CMPI 32 r5
BNE GreenGhostDrawDOWN1 //else check if in state DOWN1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN0
BUC GG_Eat1_DOWN0
GG_Normal_DOWN0:
MOV r0 r1
MOVI 86 r0 //GGHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above GreenGhost
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_DOWN0:
MOV r0 r1
MOVI 30 r0 //E1GHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_DOWN0:
MOV r0 r1
MOVI 58 r0 //E2GHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 1:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN1
GreenGhostDrawDOWN1:
LOAD R5 R3
CMPI 33 r5
BNE GreenGhostDrawDOWN2 //else check if in state DOWN2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN1
BUC GG_Eat1_DOWN1
GG_Normal_DOWN1:
MOV r0 r1
MOVI 87 r0 //GHOST_DOWN_1
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 88 r0 //GHOST_DOWN_2
STOR r0 r1
RETX
GG_Eat0_DOWN1:
MOVI 31 R1 //E1GHOST_DOWN_1
STOR R1 R0
ADDI -53 R0
MOVI 32 R1 //E1GHOST_DOWN_2
STOR R1 R0
RETX
GG_Eat1_DOWN1:
MOVI 59 R1 //E2GHOST_DOWN_1
STOR R1 R0
ADDI -53 R0
MOVI 60 R1 //E2GHOST_DOWN_2
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN2
GreenGhostDrawDOWN2:
LOAD R5 R3
CMPI 34 r5
BNE GreenGhostDrawDOWN3 //else check if in state DOWN3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN2
BUC GG_Eat1_DOWN2
GG_Normal_DOWN2:
MOV r0 r1
MOVI 89 r0 //GHOST_DOWN_3
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 90 r0 //GHOST_DOWN_4
STOR r0 r1
RETX
GG_Eat0_DOWN2:
MOVI 33 R1 //E1GHOST_DOWN_3
STOR R1 R0
ADDI -53 R0
MOVI 34 R1 //E1GHOST_DOWN_4
STOR R1 R0
RETX
GG_Eat1_DOWN2:
MOVI 61 R1 //E2GHOST_DOWN_3
STOR R1 R0
ADDI -53 R0
MOVI 62 R1 //E2GHOST_DOWN_4
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN3
GreenGhostDrawDOWN3:
LOAD R5 R3
CMPI 35 r5
BNE GreenGhostDrawLEFT0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN3
BUC GG_Eat1_DOWN3
GG_Normal_DOWN3:
MOV r0 r1
MOVI 92 r0 //GHOST_DOWN_6
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 91 r0 //GHOST_DOWN_5
STOR r0 r1
RETX
GG_Eat0_DOWN3:
MOVI 64 R1 //E1GHOST_DOWN_6
STOR R1 R0
ADDI 53 R0
MOVI 63 R1 //E1GHOST_DOWN_5
STOR R1 R0
RETX
GG_Eat1_DOWN3:
MOVI 81 R1 //E2GHOST_DOWN_6
STOR R1 R0
ADDI 53 R0
MOVI 80 R1 //E2GHOST_DOWN_5
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT0
GreenGhostDrawLEFT0:
load r5 r3
CMPI 48 r5
BNE GreenGhostDrawLEFT1 //else check if in state LEFT1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT0
BUC GG_Eat1_LEFT0
GG_Normal_LEFT0:
MOV r0 r1
MOVI 93 r0 //GGHOST_LEFT_0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_LEFT0:
MOV r0 r1
MOVI 37 r0 //E1GHOST_LEFT_0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_LEFT0:
MOV r0 r1
MOVI 65 r0 //E2GHOST_LEFT0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 1:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT1
GreenGhostDrawLEFT1:
LOAD R5 R3
CMPI 49 r5
BNE GreenGhostDrawLEFT2 //else check if in state LEFT2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT1
BUC GG_Eat1_LEFT1
GG_Normal_LEFT1:
MOV r0 r1
MOVI 99 r0 //GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 98 r0 //GHOST_LEFT_5
STOR r0 r1
RETX
GG_Eat0_LEFT1:
MOV r0 r1
MOVI 43 R0 //E1GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 42 R0 //E1GHOST_LEFT_5
STOR R0 R1
RETX
GG_Eat1_LEFT1:
MOV r0 r1
MOVI 71 R0 //E2GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 70 R0 //E2GHOST_LEFT_5
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT2
GreenGhostDrawLEFT2:
LOAD R5 R3
CMPI 50 r5
BNE GreenGhostDrawLEFT3 //else check if in state LEFT3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT2
BUC GG_Eat1_LEFT2
GG_Normal_LEFT2:
MOV r0 r1
MOVI 97 r0 //GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 96 r0 //GHOST_LEFT_3
STOR r0 r1
RETX
GG_Eat0_LEFT2:
MOV r0 r1
MOVI 41 R0 //E1GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 40 R0 //E1GHOST_LEFT_3
STOR R0 R1
RETX
GG_Eat1_LEFT2:
MOV r0 r1
MOVI 69 R0 //E2GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 68 R0 //E2GHOST_LEFT_3
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT3
GreenGhostDrawLEFT3:
LOAD R5 R3
CMPI 51 r5
BNE GreenGhostDrawRIGHT0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT3
BUC GG_Eat1_LEFT3
GG_Normal_LEFT3:
MOV r0 r1
MOVI 94 r0 //GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 95 r0 //GHOST_LEFT_2
STOR r0 r1
RETX
GG_Eat0_LEFT3:
MOV r0 r1
MOVI 38 R0 //E1GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 39 R0 //E1GHOST_LEFT_2
STOR R0 R1
RETX
GG_Eat1_LEFT3:
MOV r0 r1
MOVI 66 R0 //E2GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 67 R0 //E2GHOST_LEFT_2
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT0
GreenGhostDrawRIGHT0:
load r5 r3
CMPI 64 r5
BNE GreenGhostDrawRIGHT1 //else check if in state RIGHT1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT0
BUC GG_Eat1_RIGHT0
GG_Normal_RIGHT0:
MOV r0 r1
MOVI 100 r0 //GGHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_RIGHT0:
MOV r0 r1
MOVI 44 r0 //E1GHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_RIGHT0:
MOV r0 r1
MOVI 72 r0 //E2GHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 1:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT1
GreenGhostDrawRIGHT1:
LOAD R5 R3
CMPI 65 r5
BNE GreenGhostDrawRIGHT2 //else check if in state RIGHT2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT1
BUC GG_Eat1_RIGHT1
GG_Normal_RIGHT1:
MOV r0 r1
MOVI 101 r0 //GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 102 r0 //GHOST_RIGHT_2
STOR r0 r1
RETX
GG_Eat0_RIGHT1:
MOV r0 r1
MOVI 45 R0 //E1GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 46 R0 //E1GHOST_RIGHT_2
STOR R0 R1
RETX
GG_Eat1_RIGHT1:
MOV r0 r1
MOVI 73 R0 //E2GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 74 R0 //E2GHOST_RIGHT_2
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT2
GreenGhostDrawRIGHT2:
LOAD R5 R3
CMPI 66 r5
BNE GreenGhostDrawRIGHT3 //else check if in state RIGHT3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT2
BUC GG_Eat1_RIGHT2
GG_Normal_RIGHT2:
MOV r0 r1
MOVI 103 r0 //GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 104 r0 //GHOST_RIGHT_4
STOR r0 r1
RETX
GG_Eat0_RIGHT2:
MOV r0 r1
MOVI 47 R0 //E1GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 48 R0 //E1GHOST_RIGHT_4
STOR R0 R1
RETX
GG_Eat1_RIGHT2:
MOV r0 r1
MOVI 75 R0 //E2GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 76 R0 //E2GHOST_RIGHT_4
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT3
GreenGhostDrawRIGHT3:
LOAD R5 R3
CMPI 67 r5
BEQ GG_Right3 //else return if not in a state...
RETX
GG_Right3:
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT3
BUC GG_Eat1_RIGHT3
GG_Normal_RIGHT3:
MOV r0 r1
MOVI 106 r0 //GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 105 r0 //GHOST_RIGHT_5
STOR r0 r1
RETX
GG_Eat0_RIGHT3:
MOV r0 r1
MOVI 50 R0 //E1GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 49 R0 //E1GHOST_RIGHT_5
STOR R0 R1
RETX
GG_Eat1_RIGHT3:
MOV r0 r1
MOVI 78 R0 //E2GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 77 R0 //E2GHOST_RIGHT_5
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::END GreenGhostDraw GLYPH:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
INIT_GreenGhost:
LUI 255 r0 //make timer reset address
ORI 241 r0
LUI 4 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
//set GreenGhost state to left0
LUI 50 r4
ORI 1 r4
MOVI 48 r1
STOR r1 r4
//put GreenGhost on initial spot in map
LUI 50 r4
LUI 63 r1 # make address for top corner in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -28 r8
ADD r8 r1 # Offset by rows
ADDI -26 r1 # Offset by columns
STOR R1 r4
RETX
//CHECK_DIRECTION functions. Use only register r0 and ra for safety. This way when calling these functions,
//only the r0 and ra registers must be preserved first if they are important.
CheckRIGHT:
LUI 255 r0 //make right address in r0
ORI 248 r0
LOAD r0 r0 //save result back into r0
RETX
CheckLEFT:
LUI 255 r0 //make address in r0
ORI 249 r0
LOAD r0 r0 //save result back into r0
RETX //return
CheckUP:
LUI 255 r0
ORI 251 r0
LOAD r0 r0
RETX
CheckDOWN:
LUI 255 r0
ORI 250 r0
LOAD r0 r0
RETX
GreenGhost_isWallUP:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI 53 r0 //increment r0 to get location of square above GreenGhost (53 adress spaces higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallDOWN:
LUI 50 r0 //green ghost location
LOAD r0 r0 //save result back into r0
ADDI -53 r0 //increment r0 to get location of square below GreenGhost (53 adress spaces lower in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallLEFT:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI 1 r0 //increment r0 to get location of square left of GreenGhost (1 space higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallRIGHT:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI -1 r0 //increment r0 to get location of square right of GreenGhost (1 space lower in memory)
LOAD r0 r0
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
///check the position passed in r1, sets r1 to equal r1 if not on warp,
///otherwise sets r1 to warped position.
SetPosition_WarpLeftSide:
LUI 63 r7 # make address for checking location
ORI 255 r7
MOVI 53 r9
MULI -19 r9
ADD r9 r7 # Offset by rows
ADDI -12 r7 # Offset by columns
CMP r1 r7
BNE endWarpLeftSide
ADDI -28 r7
MOV r7 r1
endWarpLeftSide:
RETX
SetPosition_WarpRightSide:
LUI 63 r7 # make address for checking location
ORI 255 r7
MOVI 53 r9
MULI -19 r9
ADD r9 r7 # Offset by rows
ADDI -12 r7
ADDI -29 r7 # Offset by columns
CMP r1 r7
BNE endWarpRightSide
ADDI 28 r7
MOV r7 r1
endWarpRightSide:
RETX
FBpos_2_CPpos:
LUI 14 r7
MULI -1 r7
ADD r7 r1
RETX
CPpos_2_FBpos:
LUI 14 r7
ADD r7 r1
RETX
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::STATE MACHINE HELPERS FOR ALL MACHINES::::::::::::::::
// The following functions assume 'state address' has been moved to r0
//**actorUP**
setStateUP0:
MOVI 16 r1
STOR r1 r0
RETX
setStateUP1:
MOVI 17 r1
STOR r1 r0
RETX
setStateUP2:
MOVI 18 r1
STOR r1 r0
RETX
setStateUP3:
MOVI 19 r1
STOR r1 r0
RETX
//**actorDOWN**
setStateDOWN0:
MOVI 32 r1
STOR r1 r0
RETX
setStateDOWN1:
MOVI 33 r1
STOR r1 r0
RETX
setStateDOWN2:
MOVI 34 r1
STOR r1 r0
RETX
setStateDOWN3:
MOVI 35 r1
STOR r1 r0
RETX
//**actorLEFT**
setStateLEFT0:
MOVI 48 r1
STOR r1 r0
RETX
setStateLEFT1:
MOVI 49 r1
STOR r1 r0
RETX
setStateLEFT2:
MOVI 50 r1
STOR r1 r0
RETX
setStateLEFT3:
MOVI 51 r1
STOR r1 r0
RETX
//**actorRIGHT**
setStateRIGHT0:
MOVI 64 r1
STOR r1 r0
RETX
setStateRIGHT1:
MOVI 65 r1
STOR r1 r0
RETX
setStateRIGHT2:
MOVI 66 r1
STOR r1 r0
RETX
setStateRIGHT3:
MOVI 67 r1
STOR r1 r0
RETX
//**GreenGhostDEAD**
setStateDEAD1:
MOVI 1 r1
STOR r1 r0
RETX
setStateDEAD2:
MOVI 2 r1
STOR r1 r0
RETX
setStateDEAD3:
MOVI 3 r1
STOR r1 r0
RETX
setStateDEAD4:
MOVI 4 r1
STOR r1 r0
RETX
/////:::::::::::END ALL STATE MACHINE LOGIC:::::::::::::::::://////
/////HELPER FUNCTIONS FOR MAIN GAME LOGIC ////
DrawLivesLeft:
LUI 63 r1 # make address for writting location in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -37 r8
ADD r8 r1 # Offset by rows
ADDI -14 r1 # Offset by columns
//zero out space where lives drawn
MOVI 0 r0 // number of lives drawn
MOVI 0 r2 // blank glyph
livesClearLoop:
CMPI 5 r0
BEQ endlivesClearLoop
STOR r2 r1
ADDI -1 r1
ADDI 1 r0
BUC livesClearLoop
endlivesClearLoop:
ADDI 5 r1 //reset address
LUI 51 r8 //lives left addr
ORI 244 r8 //lives left addr
LOAD r8 r8
MOVI 0 r0
MOVI 226 r2 //pman glyph
livesLoop:
CMP r0 r8
BEQ endlivesLoop
STOR r2 r1
ADDI -1 r1
ADDI 1 r0
BUC livesLoop
endlivesLoop:
RETX
initlevel:
//Initialize pill remaining counter in gamestate by MOVIng 244 Pills left on board to addr 13301
LUI 51 r4
ORI 245 r4
MOVI 244 r0
STOR r0 r4
//initialize map in fb only.
LUI 55 r0 // Make the address for where init function starts
ORI 182 r0 //
MOV r0 r3 // r3 current address of where we are reading from memory
LUI 63 r1 # make address for writting location in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -5 r8
ADD r8 r1 # Offset by rows
ADDI -13 r1 # Offset by columns
MOVI 0 r6
loopi:
CMPI 31 r6
BEQ endloopi #this should support labels, jump endloopi
MOVI 0 r7
loopj:
CMPI 28 r7
BEQ endloopj #jump to endloopj
MOV r6 r4
MULI 53 r4
ADD r7 r4
MULI -1 r4
ADD r1 r4
LOAD r5 r3
STOR r5 r4
SUBI 1 r3
ADDI 1 r7
BUC loopj
endloopj:
ADDI 1 r6
BUC loopi
endloopi:
//make the copy of the map in memory in fbcp
LUI 55 r0 // Make the address for where init function starts
ORI 182 r0 //
MOV r0 r3 // r3 current address of where we are reading from memory
LUI 49 r1 # make address for writting location in frame buffer copy
ORI 255 r1
MOVI 53 r8
MULI -5 r8
ADD r8 r1 # Offset by rows
ADDI -13 r1 # Offset by columns
MOVI 0 r6
loopi2:
CMPI 31 r6
BEQ endloopi2 #this should support labels, jump endloopi
MOVI 0 r7
loopj2:
CMPI 28 r7
BEQ endloopj2 #jump to endloopj
MOV r6 r4
MULI 53 r4
ADD r7 r4
MULI -1 r4
ADD r1 r4
LOAD r5 r3
STOR r5 r4
SUBI 1 r3
ADDI 1 r7
BUC loopj2
endloopj2:
ADDI 1 r6
BUC loopi2
endloopi2:
RETX
//***************************************
//************Start Menu*****************
//***************************************
// A(114) - Z(139)
// !(140)
// 0(169) - 9(178)
start_menu:
// zero out map
MOV r15 r14
JAL r9 clear_screen
MOV r14 r15
MOVI 0 r8 // zero out r8 for toggle return address
LUI 63 r0 // top left most glyph address
ORI 255 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
ADDI -22 r0 // and 22 columns
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 245 r1 // Store 'pacman0'
STOR r1 r0
ADDI -1 r0
MOVI 126 r1 // Store 'M'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 171 r1 // Store '2'
STOR r1 r0
ADDI -1 r0
LUI 1 r1 // Store 'pill'
ORI 15 r1
STOR r1 r0
ADDI -1 r0
MOVI 169 r1 // Store '0'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
MOVI 133 r1 // Store 'T'
STOR r1 r0
ADDI -1 r0
MOVI 128 r1 // Store 'O'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 115 r1 // Store 'B'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 122 r1 // Store 'I'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI 5 r0
ADDI 106 r0
ADDI 106 r0
LUI 255 r4 // start timer
ORI 231 r4
MOVI 250 r5 // .5 seconds (500 milliseconds)
ADDI 125 r5
ADDI 125 r5
STOR r5 r4
BUC flash_start
dead_menu:
// zero out map
MOV r15 r14
JAL r9 clear_screen
MOV r14 r15
MOVI 0 r8 // zero out r8 for toggle return address
LUI 63 r0 // top left most glyph address
ORI 255 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
ADDI -22 r0 // and 22 columns
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 126 r1 // Store 'M'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 245 r1 // Store 'pacman0'
STOR r1 r0
ADDI -1 r0
MOVI 135 r1 // Store 'V'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 140 r1 // Store '!'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
MOVI 133 r1 // Store 'T'
STOR r1 r0
ADDI -1 r0
MOVI 128 r1 // Store 'O'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 115 r1 // Store 'B'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 122 r1 // Store 'I'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI 5 r0
ADDI 106 r0
ADDI 106 r0
LUI 255 r4 // start timer
ORI 231 r4
MOVI 250 r5 // .5 seconds (500 milliseconds)
ADDI 125 r5
ADDI 125 r5
STOR r5 r4
BUC flash_start
flash_start:
MOV r0 r7
//check if start button has been pressed on NES controller
MOV r15 r14
JAL r9 Homescreencheckstart
MOV r14 r15
LUI 255 r3 // calculate timer return value address
ORI 230 r3
LOAD r3 r3 // load timer rv into r3
CMPI 1 r3
BNE choose_draw
MOV r15 r14
JAL r9 toggle
MOV r14 r15
choose_draw: // choose whether to GreenGhostDraw 'start' or 'blank'
CMPI 1 r8
BNE draw_blank
draw_start:
MOVI 205 r1 // GreenGhostDraw closed pacmanRIGHT0
STOR r1 r10
MOVI 132 r1 // Store 'S'
STOR r1 r7
ADDI -1 r7
MOVI 133 r1 // Store 'T'
STOR r1 r7
ADDI -1 r7
MOVI 114 r1 // Store 'A'
STOR r1 r7
ADDI -1 r7
MOVI 131 r1 // Store 'R'
STOR r1 r7
ADDI -1 r7
MOVI 133 r1 // Store 'T'
STOR r1 r7
JUC r9 flash_start
draw_blank:
MOVI 245 r1
STOR r1 r10
MOVI 0 r1 // otherwise draw nothing
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
JUC r9 flash_start
toggle:
XORI 1 r8 // toggle rv
LUI 255 r4 // reset timer
ORI 231 r4
LUI 2 r5 // really close to 500, maybe 512
STOR r5 r4
RETX
Homescreencheckstart:
MOVI 0 r2 // Check 'START'
LUI 255 r2
ORI 252 r2
LOAD r2 r2
CMPI 1 r2
JEQ r9 start_Game // if start asserted, start game
RETX
clear_screen:
MOV r2 r10 //save this register
MOV r3 r11 // save this register
MOVI 0 r0 // zero-out temp
LUI 63 r2 // create glyph address
ORI 255 r2
LUI 8 r3 // create counter constraint of 2120 (# of glyphs)
ORI 72 r3
MOVI 0 r1 // glyph 0 to be drawn
clearscreenloop:
STOR r1 r2 // draw glyph
ADDI -1 r2 // decrement address pointer
ADDI 1 r0 // increment counter
CMP r0 r3 // check counter <= 2120
BLT clearscreenloop
MOV r10 r2 // else restore the reg's
MOV r11 r3
RETX
//*** end start menu**///
|
/*********************************************************
* Copyright (C) 2010-2016 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*********************************************************/
/**
* @file copyPasteDnDX11.cpp
*
* Implementation class for DnD and copy paste on X11 platform.
*/
#define G_LOG_DOMAIN "dndcp"
#include "copyPasteDnDWrapper.h"
#include "copyPasteDnDX11.h"
#include "dndPluginIntX11.h"
#include "tracer.hh"
Window gXRoot;
Display *gXDisplay;
GtkWidget *gUserMainWidget;
extern "C" {
#include "copyPasteCompat.h"
#include "vmware/tools/plugin.h"
void CopyPaste_Register(GtkWidget *mainWnd, ToolsAppCtx *ctx);
void CopyPaste_Unregister(GtkWidget *mainWnd);
}
#include "pointer.h"
/**
*
* BlockingService - a singleton class responsible for initializing and
* cleaning up blocking state (vmblock).
*/
class BlockService {
public:
static BlockService *GetInstance();
void Init(ToolsAppCtx *);
DnDBlockControl *GetBlockCtrl() { return &m_blockCtrl; }
private:
BlockService();
~BlockService();
void Shutdown();
static gboolean ShutdownSignalHandler(const siginfo_t *, gpointer);
GSource *m_shutdownSrc;
DnDBlockControl m_blockCtrl;
bool m_initialized;
static BlockService *m_instance;
};
BlockService *BlockService::m_instance = 0;
/**
*
* Constructor.
*/
BlockService::BlockService() :
m_shutdownSrc(0),
m_initialized(false)
{
memset(&m_blockCtrl, 0, sizeof m_blockCtrl);
m_blockCtrl.fd = -1;
}
/**
*
* Get an instance of BlockService, which is an application singleton.
*
* @return a pointer to the singleton BlockService object, or NULL if
* for some reason it could not be allocated.
*/
BlockService *
BlockService::GetInstance()
{
TRACE_CALL();
if (!m_instance) {
m_instance = new BlockService();
}
ASSERT(m_instance);
return m_instance;
}
/**
*
* Initialize blocking subsystem so that GTK+ DnD operations won't
* time out. Also install SIGUSR1 handler so we can disconnect from
* blcoing subsystem upon request.
*
* @param[in] ctx tools app context.
*/
void
BlockService::Init(ToolsAppCtx *ctx)
{
TRACE_CALL();
if (!m_initialized && ctx) {
m_blockCtrl.fd = ctx->blockFD;
m_blockCtrl.fd >= 0 ?
DnD_CompleteBlockInitialization(m_blockCtrl.fd, &m_blockCtrl) :
DnD_InitializeBlocking(&m_blockCtrl);
m_shutdownSrc = VMTools_NewSignalSource(SIGUSR1);
VMTOOLSAPP_ATTACH_SOURCE(ctx, m_shutdownSrc, ShutdownSignalHandler,
ctx, NULL);
m_initialized = true;
}
}
/**
*
* Signal handler called when we receive SIGUSR1 which is a hint for us
* to disconnect from blocking subsystem so that it can be upgraded.
*
* @param[in] siginfo unused.
* @param[in] data unused.
*
* @return always TRUE.
*/
gboolean
BlockService::ShutdownSignalHandler(const siginfo_t *siginfo,
gpointer data)
{
TRACE_CALL();
g_debug("Shutting down block service on SIGUSR1 ...\n");
GetInstance()->Shutdown();
return FALSE;
}
/**
*
* Shut down blocking susbsystem so that we can perform upgrade.
*/
void
BlockService::Shutdown()
{
TRACE_CALL();
if (m_initialized) {
g_source_destroy(m_shutdownSrc);
g_source_unref(m_shutdownSrc);
m_shutdownSrc = 0;
if (DnD_BlockIsReady(&m_blockCtrl)) {
DnD_UninitializeBlocking(&m_blockCtrl);
}
m_initialized = false;
}
}
/**
*
* Constructor.
*/
CopyPasteDnDX11::CopyPasteDnDX11() :
m_copyPasteUI(NULL),
m_dndUI(NULL)
{
}
/**
*
* Initialize Win32 platform DnD/CP. Initialize Gtk+, and create detection
* windows.
*
* @param[in] ctx tools app context.
*/
gboolean
CopyPasteDnDX11::Init(ToolsAppCtx *ctx)
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
ASSERT(ctx);
int argc = 1;
const char *argv[] = {"", NULL};
m_main = new Gtk::Main(&argc, (char ***) &argv, false);
if (wrapper) {
BlockService::GetInstance()->Init(ctx);
}
gUserMainWidget = gtk_invisible_new();
#ifndef GTK3
gXDisplay = GDK_WINDOW_XDISPLAY(gUserMainWidget->window);
#else
gXDisplay = GDK_WINDOW_XDISPLAY(gtk_widget_get_window(gUserMainWidget));
#endif
gXRoot = RootWindow(gXDisplay, DefaultScreen(gXDisplay));
/*
* Register legacy (backdoor) version of copy paste.
*/
CopyPaste_SetVersion(1);
CopyPaste_Register(gUserMainWidget, ctx);
return TRUE;
}
/**
*
* Destructor.
*/
CopyPasteDnDX11::~CopyPasteDnDX11()
{
if (m_copyPasteUI) {
delete m_copyPasteUI;
}
if (m_dndUI) {
delete m_dndUI;
}
if (m_main) {
delete m_main;
}
/*
* Legacy CP.
*/
CopyPaste_Unregister(gUserMainWidget);
if (gUserMainWidget) {
gtk_widget_destroy(gUserMainWidget);
}
}
/**
*
* Register copy and paste capabilities with the VMX.
*
* @return TRUE on success, FALSE on failure
*/
gboolean
CopyPasteDnDX11::RegisterCP()
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
if (wrapper->IsCPRegistered()) {
return TRUE;
}
if (!wrapper->IsCPEnabled()) {
return FALSE;
}
m_copyPasteUI = new CopyPasteUIX11();
if (m_copyPasteUI) {
if (m_copyPasteUI->Init()) {
BlockService *bs = BlockService::GetInstance();
m_copyPasteUI->SetBlockControl(bs->GetBlockCtrl());
wrapper->SetCPIsRegistered(TRUE);
int version = wrapper->GetCPVersion();
g_debug("%s: version is %d\n", __FUNCTION__, version);
if (version >= 3) {
CopyPasteVersionChanged(version);
m_copyPasteUI->SetCopyPasteAllowed(TRUE);
}
/*
* Set legacy copy/paste version.
*/
CopyPaste_SetVersion(version);
} else {
delete m_copyPasteUI;
m_copyPasteUI = NULL;
}
}
return wrapper->IsCPRegistered();
}
/**
*
* Register DnD capabilities with the VMX.
*
* @return TRUE on success, FALSE on failure
*/
gboolean
CopyPasteDnDX11::RegisterDnD()
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
if (!wrapper->IsDnDEnabled()) {
return FALSE;
}
if (!wrapper->IsDnDRegistered()) {
m_dndUI = new DnDUIX11(wrapper->GetToolsAppCtx());
if (m_dndUI) {
BlockService *bs = BlockService::GetInstance();
m_dndUI->SetBlockControl(bs->GetBlockCtrl());
if (m_dndUI->Init()) {
wrapper->SetDnDIsRegistered(TRUE);
m_dndUI->SetDnDAllowed(TRUE);
int version = wrapper->GetDnDVersion();
g_debug("%s: dnd version is %d\n", __FUNCTION__, version);
if (version >= 3) {
DnDVersionChanged(version);
}
} else {
delete m_dndUI;
m_dndUI = NULL;
}
}
}
g_debug("%s: dnd is registered? %d\n", __FUNCTION__, (int) wrapper->IsDnDRegistered());
return wrapper->IsDnDRegistered();
}
/**
*
* Unregister copy paste capabilities and do general cleanup.
*/
void
CopyPasteDnDX11::UnregisterCP()
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
if (wrapper->IsCPRegistered()) {
if (m_copyPasteUI) {
delete m_copyPasteUI;
m_copyPasteUI = NULL;
}
wrapper->SetCPIsRegistered(FALSE);
wrapper->SetCPVersion(-1);
}
}
/**
*
* Unregister DnD capabilities and do general cleanup.
*/
void
CopyPasteDnDX11::UnregisterDnD()
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
if (wrapper->IsDnDRegistered()) {
if (m_dndUI) {
delete m_dndUI;
m_dndUI = NULL;
}
wrapper->SetDnDIsRegistered(false);
wrapper->SetDnDVersion(-1);
return;
}
}
/**
*
* Communicate dnd allowed to platform implementation.
*
* @param[allowed] if TRUE, dnd allowed.
*/
void
CopyPasteDnDX11::SetDnDAllowed(bool allowed)
{
ASSERT(m_dndUI);
TRACE_CALL();
m_dndUI->SetDnDAllowed(allowed);
}
/**
*
* Communicate copypaste allowed to platform implementation.
*
* @param[allowed] if TRUE, copy paste allowed.
*/
void
CopyPasteDnDX11::SetCopyPasteAllowed(bool allowed)
{
ASSERT(m_copyPasteUI);
TRACE_CALL();
m_copyPasteUI->SetCopyPasteAllowed(allowed);
}
/**
* Communicate copy paste version change to the platform implementation.
*
* @param[in] version the new version
*/
void
CopyPasteDnDX11::CopyPasteVersionChanged(int version)
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
ToolsAppCtx *ctx = wrapper->GetToolsAppCtx();
g_debug("%s: calling VmxCopyPasteVersionChanged (version %d)\n",
__FUNCTION__, version);
if (ctx) {
m_copyPasteUI->VmxCopyPasteVersionChanged(ctx->rpc, version);
}
}
/**
* Communicate DnD version change by calling the platform implementation.
*
* @param[in] version the new version.
*/
void
CopyPasteDnDX11::DnDVersionChanged(int version)
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
ToolsAppCtx *ctx = wrapper->GetToolsAppCtx();
g_debug("%s: calling VmxDnDVersionChanged (version %d)\n",
__FUNCTION__, version);
ASSERT(ctx);
ASSERT(m_dndUI);
m_dndUI->VmxDnDVersionChanged(ctx->rpc, version);
}
/**
*
* Initialize pointer code.
*/
void
CopyPasteDnDX11::PointerInit()
{
TRACE_CALL();
CopyPasteDnDWrapper *wrapper = CopyPasteDnDWrapper::GetInstance();
ASSERT(wrapper);
ToolsAppCtx *ctx = wrapper->GetToolsAppCtx();
ASSERT(ctx);
Pointer_Init(ctx);
}
/**
* Return platform DnD/CP caps.
*
* @return 32-bit caps vector.
*/
uint32
CopyPasteDnDX11::GetCaps()
{
return DND_CP_CAP_VALID |
DND_CP_CAP_DND |
DND_CP_CAP_CP |
DND_CP_CAP_FORMATS_ALL |
DND_CP_CAP_ACTIVE_CP |
DND_CP_CAP_BIG_BUFFER;
}
|
; A135683: a(n)=1 if n is a prime number; otherwise, a(n)=n.
; 1,1,1,4,1,6,1,8,9,10,1,12,1,14,15,16,1,18,1,20,21,22,1,24,25,26,27,28,1,30,1,32,33,34,35,36,1,38,39,40,1,42,1,44,45,46,1,48,49,50,51,52,1,54,55,56,57,58,1,60,1,62,63,64,65,66,1,68,69,70,1,72,1,74,75,76,77,78,1,80,81,82,1,84,85,86,87,88,1,90,91,92,93,94,95,96,1,98,99,100
mov $1,$0
seq $1,14684 ; In the sequence of positive integers subtract 1 from each prime number.
mod $0,$1
add $0,1
|
; A299289: Coordination sequence for "tsi" 3D uniform tiling.
; 1,8,28,60,106,164,236,320,418,528,652,788,938,1100,1276,1464,1666,1880,2108,2348,2602,2868,3148,3440,3746,4064,4396,4740,5098,5468,5852,6248,6658,7080,7516,7964,8426,8900,9388,9888,10402,10928
add $0,1
mov $1,$0
sub $0,2
mul $1,$0
mov $2,$1
add $1,2
mul $1,7
div $2,2
sub $1,$2
sub $1,6
|
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef RESAMPLING_HPP
#define RESAMPLING_HPP
#include <assert.h>
#include <limits.h>
#include <stdint.h>
#include <iostream>
#include "common.hpp"
#include "dnn_types.hpp"
#include "dnnl_common.hpp"
#include "dnnl_memory.hpp"
#include "perf_report.hpp"
namespace resampling {
enum alg_t { nearest, linear };
alg_t str2alg(const char *str);
const char *alg2str(alg_t alg);
dnnl_alg_kind_t alg2alg_kind(alg_t alg);
struct desc_t {
int64_t mb, ic;
int64_t id, ih, iw;
int64_t od, oh, ow;
const char *name;
int ndims;
};
int str2desc(desc_t *desc, const char *str);
std::ostream &operator<<(std::ostream &s, const desc_t &d);
struct prb_t : public desc_t {
prb_t(const desc_t &desc, dir_t dir, dnnl_data_type_t dt,
dnnl_format_tag_t tag, alg_t alg, int64_t mb = 0)
: desc_t(desc), dir(dir), dt(dt), tag(tag), alg(alg) {
if (mb) this->mb = mb;
}
~prb_t() {}
dir_t dir;
dnnl_data_type_t dt;
dnnl_format_tag_t tag;
alg_t alg;
BENCHDNN_DISALLOW_COPY_AND_ASSIGN(prb_t);
};
std::ostream &operator<<(std::ostream &s, const prb_t &p);
struct perf_report_t : public base_perf_report_t {
using base_perf_report_t::base_perf_report_t;
void report(const prb_t *p, const res_t *r, const char *prb_str) {
p_ = p;
base_report(r, prb_str);
}
virtual void dump_alg(std::ostream &s) const override {
s << alg2str(p_->alg);
}
virtual void dump_desc(std::ostream &s) const override {
s << static_cast<const desc_t &>(*p_);
}
virtual void dump_desc_csv(std::ostream &s) const override {
s << p_->mb << ','
<< p_->ic << ',' << p_->id << ',' << p_->ih << ',' << p_->iw << ','
<< p_->od << ',' << p_->oh << ',' << p_->ow;
}
virtual const char *name() const override { return p_->name; }
virtual const dir_t *dir() const override { return &p_->dir; }
virtual const dnnl_data_type_t *dt() const override { return &p_->dt; }
virtual const dnnl_format_tag_t *tag() const override { return &p_->tag; }
private:
const prb_t *p_ = NULL;
};
/* some extra control parameters which shouldn't be placed in prb_t */
extern const char *skip_impl; /* NULL or "" means do not skip anything */
extern bool allow_unimpl; /* true means do not treat unimplemented as error */
inline int64_t src_off_f(const prb_t *p, int64_t mb, int64_t ic, int64_t id,
int64_t ih, int64_t iw) {
return (((mb * p->ic + ic) * p->id + id) * p->ih + ih) * p->iw + iw;
}
inline void inv_src_off_f(const prb_t *p, int64_t off, int64_t &mb, int64_t &ic,
int64_t &id, int64_t &ih, int64_t &iw) {
iw = off % p->iw;
off /= p->iw;
ih = off % p->ih;
off /= p->ih;
id = off % p->id;
off /= p->id;
ic = off % p->ic;
off /= p->ic;
mb = off % p->mb;
off /= p->mb;
assert(off == 0);
}
inline int64_t dst_off_f(const prb_t *p, int64_t mb, int64_t ic, int64_t od,
int64_t oh, int64_t ow) {
return (((mb * p->ic + ic) * p->od + od) * p->oh + oh) * p->ow + ow;
}
inline void inv_dst_off_f(const prb_t *p, int64_t off, int64_t &mb, int64_t &ic,
int64_t &od, int64_t &oh, int64_t &ow) {
ow = off % p->ow;
off /= p->ow;
oh = off % p->oh;
off /= p->oh;
od = off % p->od;
off /= p->od;
ic = off % p->ic;
off /= p->ic;
mb = off % p->mb;
off /= p->mb;
assert(off == 0);
}
void compute_ref_fwd(const prb_t *p, const dnn_mem_t &src, dnn_mem_t &dst);
void compute_ref_bwd(
const prb_t *p, dnn_mem_t &diff_src, const dnn_mem_t &diff_dst);
int compare_src(const prb_t *p, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *r);
int compare_dst(const prb_t *p, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *r);
int fill_dat(const prb_t *p, dnn_mem_t &mem_dt, dnn_mem_t &mem_fp, res_t *r);
int doit(const prb_t *p, res_t *res);
int bench(int argc, char **argv);
} // namespace resampling
#endif
|
.386
.model flat,stdcall
option casemap:none
VirtualAlloc proto stdcall :DWORD, :DWORD, :DWORD, :DWORD
VirtualProtect proto stdcall :DWORD, :DWORD, :DWORD, :DWORD
VirtualFree proto stdcall :DWORD, :DWORD, :DWORD
includelib \masm32\lib\kernel32.lib
.code
main:
push ebp
mov ebp,esp
mov eax,dword ptr ss:[ebp+0ch]
cmp eax,1
jnz @returnf
push eax
push 40h
push 1000h
push 4h
push 0
call VirtualAlloc
mov ebx,eax
push ebx
push 40h
push 1h
push 445481h
call VirtualProtect
mov byte ptr ds:[445481h],03h
push 0
push dword ptr ds:[ebx]
push 1h
push 445481h
call VirtualProtect
push 4000h
push 4h
push ebx
call VirtualFree
pop eax
@returnf:
leave
retn 0ch
end main
;miksussy
|
;; Licensed to the .NET Foundation under one or more agreements.
;; The .NET Foundation licenses this file to you under the MIT license.
include asmmacros.inc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhpGetThread
;;
;;
;; INPUT:
;;
;; OUTPUT: RAX: Thread pointer
;;
;; TRASHES: R10
;;
;; MUST PRESERVE ARGUMENT REGISTERS
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEAF_ENTRY RhpGetThread, _TEXT
;; rax = GetThread(), TRASHES r10
INLINE_GETTHREAD rax, r10
ret
LEAF_END RhpGetThread, _TEXT
end
|
[org 0x0100]
jmp start
buffer: db 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32
startingBit: db 105
start: mov dx,1111111100000000b
mov bx,8
mov cx,0
mov ax,0
mov si,0
mov al, [startingBit]
div bl
mov bx, 0
mov bl,al
mov si,bx
cmp ah,0
jz scenario0
jnz scenario1
;Desired Byte doesn't split into two bytes
scenario0: mov bl, [buffer + si]
mov ax,bx
jmp end
;Desired Byte splits into two bytes
scenario1: mov cl, ah
mov bh, [buffer + si] ;Done to
mov bl, [buffer + si + 1] ;maintain the order of bytes in bx
shl bx, cl
and dx, bx
mov ax, 0
mov al, dh
jmp end
end: mov ax,0x4c00
int 21h |
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-20, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include "RAJA/RAJA.hpp"
#include "memoryManager.hpp"
/*
* EXERCISE #3: Mesh vertex area with "colored" TypedIndexSet
*
* In this exercise, you will use a RAJA TypedIndexSet containing 4
* ListSegments to parallelize the mesh vertex area computation.
* A sum is computed at each vertex on a logically-Cartesian 2D mesh
* where the sum represents the vertex "area" as an average of the 4
* element areas surrounding the vertex. The computation is written as
* a loop over elements. To avoid data races, where multiple element
* contributions may be written to the same vertex value at the same time,
* the elements are partitioned into 4 subsets, where no two elements in
* each subset share a vertex. A ListSegment enumerates the elements in
* each subset. When the ListSegments are put into an TypedIndexSet, the entire
* computation can be executed with one RAJA::forall() statement, where
* you iterate over the segments sequentially and execute each segment in
* parallel. This exercise illustrates how RAJA can be used to enable one
* to get some parallelism from such operations without fundamentally
* changing the way the algorithm looks in source code.
*
* This file contains sequential and OpenMP variants of the vertex area
* computation using C-style for-loops. You will fill in RAJA versions of
* these variants, plus a RAJA CUDA version if you have access to an NVIDIA
* GPU and a CUDA compiler, in empty code sections indicated by comments.
*
* RAJA features you will use:
* - `forall` loop iteration template method
* - Index list segment
* - TypedIndexSet segment container
* - Hierarchical execution policies
*
* If CUDA is enabled, CUDA unified memory is used.
*/
/*
CUDA_BLOCK_SIZE - specifies the number of threads in a CUDA thread block
*/
#if defined(RAJA_ENABLE_CUDA)
const int CUDA_BLOCK_SIZE = 256;
#endif
//
// Functions to check and print result.
//
void checkResult(double* a, double* aref, int n);
void printMeshData(double* v, int n, int joff);
int main(int RAJA_UNUSED_ARG(argc), char **RAJA_UNUSED_ARG(argv[]))
{
std::cout << "\n\nExercise #3: Mesh vertex area with 'colored' TypedIndexSet...\n";
//
// 2D mesh has N^2 elements (N+1)^2 vertices.
//
const int N = 1000;
const int Nelem = N;
const int Nvert = N + 1;
double* areae = memoryManager::allocate<double>(Nelem*Nelem);
double* areav = memoryManager::allocate<double>(Nvert*Nvert);
double* areav_ref = memoryManager::allocate<double>(Nvert*Nvert);
int* e2v_map = memoryManager::allocate<int>(4*Nelem*Nelem);
//
// Define mesh spacing factor 'h' and set up elem to vertex mapping array.
//
double h = 0.1;
for (int j = 0 ; j < Nelem ; ++j) {
for (int i = 0 ; i < Nelem ; ++i) {
int ielem = i + j*Nelem ;
int imap = 4 * ielem ;
e2v_map[imap] = ielem + j;
e2v_map[imap+1] = ielem + j + 1;
e2v_map[imap+2] = ielem + j + Nvert;
e2v_map[imap+3] = ielem + j + 1 + Nvert;
}
}
//
// Initialize element areas so each element area
// depends on the i,j coordinates of the element.
//
std::memset(areae, 0, Nelem*Nelem * sizeof(double));
for (int j = 0 ; j < Nelem ; ++j) {
for (int i = 0 ; i < Nelem ; ++i) {
int ielem = i + j*Nelem ;
areae[ielem] = h*(i+1) * h*(j+1);
}
}
//std::cout << "\n Element areas...\n";
//printMeshData(areae, Nelem, Nelem);
//----------------------------------------------------------------------------//
// C-style sequential variant establishes reference solution to compare with.
//----------------------------------------------------------------------------//
std::cout << "\n Running sequential C-style version of vertex sum...\n";
std::memset(areav_ref, 0, Nvert*Nvert * sizeof(double));
for (int ie = 0; ie < Nelem*Nelem; ++ie) {
int* iv = &(e2v_map[4*ie]);
areav_ref[ iv[0] ] += areae[ie] / 4.0 ;
areav_ref[ iv[1] ] += areae[ie] / 4.0 ;
areav_ref[ iv[2] ] += areae[ie] / 4.0 ;
areav_ref[ iv[3] ] += areae[ie] / 4.0 ;
}
//std::cout << "\n Vertex areas (reference)...\n";
//printMeshData(areav_ref, Nvert, jvoff);
//----------------------------------------------------------------------------//
//
// In the following, we partition the element iteration space into four
// subsets (or "colors") indicated by numbers in the figure below.
//
// -----------------
// | 2 | 3 | 2 | 3 |
// -----------------
// | 0 | 1 | 0 | 1 |
// -----------------
// | 2 | 3 | 2 | 3 |
// -----------------
// | 0 | 1 | 0 | 1 |
// -----------------
//
// Since none of the elements with the same number share a common vertex,
// we can iterate over each subset ("color") in parallel.
//
// We use RAJA ListSegments and a RAJA TypedIndexSet to define the element
// partitioning.
//
//
// Gather the element indices for each color in a vector.
//
std::vector< std::vector<int> > idx(4);
for (int j = 0 ; j < Nelem ; ++j) {
for (int i = 0 ; i < Nelem ; ++i) {
int ie = i + j*Nelem ;
if ( i % 2 == 0 ) {
if ( j % 2 == 0 ) {
idx[0].push_back(ie);
} else {
idx[2].push_back(ie);
}
} else {
if ( j % 2 == 0 ) {
idx[1].push_back(ie);
} else {
idx[3].push_back(ie);
}
}
}
}
//----------------------------------------------------------------------------//
// C-style OpenMP multithreading variant. Note that we use the vectors
// defined above in this variant to run each element subset in parallel.
//----------------------------------------------------------------------------//
#if defined(RAJA_ENABLE_OPENMP)
std::cout << "\n Running C-style OpenMP vertex sum...\n";
std::memset(areav, 0, Nvert*Nvert * sizeof(double));
for (int icol = 0; icol < 4; ++icol) {
const std::vector<int>& ievec = idx[icol];
const int len = static_cast<int>(ievec.size());
#pragma omp parallel for
for (int i = 0; i < len; ++i) {
int ie = ievec[i];
int* iv = &(e2v_map[4*ie]);
areav[ iv[0] ] += areae[ie] / 4.0 ;
areav[ iv[1] ] += areae[ie] / 4.0 ;
areav[ iv[2] ] += areae[ie] / 4.0 ;
areav[ iv[3] ] += areae[ie] / 4.0 ;
}
}
checkResult(areav, areav_ref, Nvert);
//std::cout << "\n Vertex areas (reference)...\n";
//printMeshData(areav_ref, Nvert, jvoff);
#endif
//
// Create a RAJA TypedIndexSet with four ListSegments, one for the indices of
// the elements in each subsut. This will be used in the RAJA OpenMP and CUDA
// variants of the vertex sum calculation.
//
// The TypedIndexSet is a variadic template, where the template arguments
// are the segment types that the TypedIndexSet can hold.
//
using SegmentType = RAJA::TypedListSegment<int>;
RAJA::TypedIndexSet<SegmentType> colorset;
colorset.push_back( SegmentType(&idx[0][0], idx[0].size()) );
colorset.push_back( SegmentType(&idx[1][0], idx[1].size()) );
colorset.push_back( SegmentType(&idx[2][0], idx[2].size()) );
colorset.push_back( SegmentType(&idx[3][0], idx[3].size()) );
//----------------------------------------------------------------------------//
// RAJA OpenMP vertex sum calculation using TypedIndexSet (sequential iteration
// over segments, OpenMP parallel iteration of each segment)
//----------------------------------------------------------------------------//
#if defined(RAJA_ENABLE_OPENMP)
std::cout << "\n Running RAJA OpenMP index set vertex sum...\n";
std::memset(areav, 0, Nvert*Nvert * sizeof(double));
using EXEC_POL3 = RAJA::ExecPolicy<RAJA::seq_segit,
RAJA::omp_parallel_for_exec>;
RAJA::forall<EXEC_POL3>(colorset, [=](int ie) {
int* iv = &(e2v_map[4*ie]);
areav[ iv[0] ] += areae[ie] / 4.0 ;
areav[ iv[1] ] += areae[ie] / 4.0 ;
areav[ iv[2] ] += areae[ie] / 4.0 ;
areav[ iv[3] ] += areae[ie] / 4.0 ;
});
checkResult(areav, areav_ref, Nvert);
//std::cout << "\n Vertex volumes...\n";
//printMeshData(areav, Nvert, Nvert);
#endif
//----------------------------------------------------------------------------//
// RAJA CUDA vertex sum calculation using TypedIndexSet (sequential iteration
// over segments, CUDA kernel launched for each segment)
//----------------------------------------------------------------------------//
#if defined(RAJA_ENABLE_CUDA)
std::cout << "\n Running RAJA CUDA index set vertex sum...\n";
std::memset(areav, 0, Nvert*Nvert * sizeof(double));
using EXEC_POL4 = RAJA::ExecPolicy<RAJA::seq_segit,
RAJA::cuda_exec<CUDA_BLOCK_SIZE>>;
RAJA::forall<EXEC_POL4>(colorset, [=] RAJA_DEVICE (int ie) {
int* iv = &(e2v_map[4*ie]);
areav[ iv[0] ] += areae[ie] / 4.0 ;
areav[ iv[1] ] += areae[ie] / 4.0 ;
areav[ iv[2] ] += areae[ie] / 4.0 ;
areav[ iv[3] ] += areae[ie] / 4.0 ;
});
checkResult(areav, areav_ref, Nvert);
//std::cout << "\n Vertex volumes...\n";
//printMeshData(areav, Nvert, jvoff);
#endif
//----------------------------------------------------------------------------//
// Clean up...
memoryManager::deallocate(areae);
memoryManager::deallocate(areav);
memoryManager::deallocate(areav_ref);
memoryManager::deallocate(e2v_map);
std::cout << "\n DONE!...\n";
return 0;
}
//
// Function to compare result to reference and print result P/F.
//
void checkResult(double* a, double* aref, int n)
{
bool correct = true;
for (int i = 0; i < n*n; i++) {
if ( correct && std::abs(a[i] - aref[i]) > 10e-12 ) { correct = false; }
}
if ( correct ) {
std::cout << "\n\t result -- PASS\n";
} else {
std::cout << "\n\t result -- FAIL\n";
}
}
//
// Function to print mesh data with mesh indices.
//
void printMeshData(double* v, int n, int joff)
{
std::cout << std::endl;
for (int j = 0 ; j < n ; ++j) {
for (int i = 0 ; i < n ; ++i) {
int ii = i + j*joff ;
std::cout << "v(" << i << "," << j << ") = "
<< v[ii] << std::endl;
}
}
std::cout << std::endl;
}
|
STACK SEGMENT STACK
DW 64 DUP(?)
STACK ENDS
CODE SEGMENT
ASSUME CS:CODE,SS:STACK
START: PUSH DS
MOV AX,0
PUSH AX
MOV AH,0FH
INT 10H
MOV AH,0
MOV AL,3
INT 10H
MOV CX,1
MOV DX,0
LOP: MOV AH,2
INT 10H
MOV AL,40H
MOV AH,0AH
INT 10H
INC DH
INC DL
CMP DH,19
JNE LOP
RET
CODE ENDS
END START
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; ReadPmc.Asm
;
; Abstract:
;
; AsmReadPmc function
;
; Notes:
;
;------------------------------------------------------------------------------
.586p
.model flat,C
.code
;------------------------------------------------------------------------------
; UINT64
; EFIAPI
; AsmReadPmc (
; IN UINT32 PmcIndex
; );
;------------------------------------------------------------------------------
AsmReadPmc PROC
mov ecx, [esp + 4]
rdpmc
ret
AsmReadPmc ENDP
END
|
// prophelp.cpp
//
// Implements AllocPropPageHelper.
//
// @doc MMCTL
//
#include "precomp.h"
#include "..\..\inc\mmctlg.h"
#include "..\..\inc\ochelp.h"
#include "debug.h"
//////////////////////////////////////////////////////////////////////////////
// CPropPageHelper
//
/* @object PropPageHelper |
Implements <i IPropertyPage>. Designed to be aggregated by an
object that wants to provide a specific propery page implementation.
@supint IPropertyPage | Standard OLE property page implementation. The
information about the property page is maintained in a
<t PropPageHelperInfo> structure that's allocated by the
aggregator and shared with <o PropPageHelper>.
@comm See <f AllocPropPageHelper> for more information.
*/
/* @struct PropPageHelperInfo |
Maintains information describing a property page. Used by
<o PropPageHelper>, but allocated by the object that aggregates
<o PropPageHelper>.
@field int | idDialog | ID of propery page dialog resource.
@field int | idTitle | ID of a string resource containing the page's title
(used on the page tab).
@field HINSTANCE | hinst | The instance of the DLL that contains the
resources specified by <p idDialog> and <p idTitle>.
@field PropPageHelperProc | pproc | A callback function that receives property
page window messages. <p pproc> is similar to a DLGPROC but has
extra parameters: a pointer to this structure, and a pointer to
an HRESULT to be used when responding to the following special
messages:
@flag WM_PPH_APPLY | <p pproc> should apply any property page
changes to the objects <p ppunk> that the property page
is operating on. This is the same as <om IPropertyPage.Apply>.
@flag WM_PPH_HELP | Identical to <om IPropertyPage.Help>.
The WPARAM parameter of <p pproc> contains the
LPCOLESTR argument of <om IPropertyPage.Help>.
@flag WM_PPH_TRANSLATEACCELERATOR | Identical to
<om IPropertyPage.TranslateAccelerator>.
The WPARAM parameter of <p pproc> contains the
LPMSG argument of <om IPropertyPage.TranslateAccelerator>.
@field IID | iid | The interface that will be used to communicate with
objects that the property page will operate upon.
@field DWORD | dwUser | Arbitrary information stored by the caller of
<f AllocPropPageHelper>.
@field IPropertyPageSite * | psite | The frame's page site object.
@field LPUNKNOWN * | ppunk | An array of <p cpunk> pointers to the objects
that this property page will operate upon. The interface ID of
each element of <p ppunk> is actually <p iid>. If <p cpunk>==0,
then presumably none of the objects that the property page was
requested to operate upon supports the interface <p iid>.
@field int | cpunk | The number of elements in <p ppunk>.
@field HWND | hwnd | The property page window.
@field BOOL | fDirty | TRUE if changes to the property page have not yet
been applied to the objects in <p ppunk>, FALSE otherwise. (If TRUE,
the Apply button should be visible.)
@field BOOL | fLockDirty | If TRUE, <p fDirty> should not be changed.
<p fLockDirty> is TRUE during initialization of the property page
(during which time it's inappropriate to be telling the property
page that it's dirty).
@comm See <f AllocPropPageHelper> for more information.
*/
struct CPropPageHelper : public INonDelegatingUnknown, public IPropertyPage
{
///// non-delegating IUnknown implementation
ULONG m_cRef; // object reference count
STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, LPVOID *ppv);
STDMETHODIMP_(ULONG) NonDelegatingAddRef();
STDMETHODIMP_(ULONG) NonDelegatingRelease();
///// delegating IUnknown implementation
LPUNKNOWN m_punkOuter; // controlling unknown
STDMETHODIMP QueryInterface(REFIID riid, LPVOID *ppv)
{ return m_punkOuter->QueryInterface(riid, ppv); }
STDMETHODIMP_(ULONG) AddRef()
{ return m_punkOuter->AddRef(); }
STDMETHODIMP_(ULONG) Release()
{ return m_punkOuter->Release(); }
///// IPropertyPage implementation
PropPageHelperInfo *m_pInfo; // object state (maintained by aggregator)
STDMETHODIMP SetPageSite(LPPROPERTYPAGESITE pPageSite);
STDMETHODIMP Activate(HWND hwndParent, LPCRECT lprc, BOOL bModal);
STDMETHODIMP Deactivate();
STDMETHODIMP GetPageInfo(LPPROPPAGEINFO pPageInfo);
STDMETHODIMP SetObjects(ULONG cObjects, LPUNKNOWN FAR* ppunk);
STDMETHODIMP Show(UINT nCmdShow);
STDMETHODIMP Move(LPCRECT prect);
STDMETHODIMP IsPageDirty();
STDMETHODIMP Apply();
STDMETHODIMP Help(LPCOLESTR lpszHelpDir);
STDMETHODIMP TranslateAccelerator(LPMSG lpMsg);
};
//////////////////////////////////////////////////////////////////////////////
// PropPageHelper Construction
//
/* @func HRESULT | AllocPropPageHelper |
Allocates a <o PropPageHelper> object which helps a control implement
a property page.
@parm LPUNKNOWN | punkOuter | The <i IUnknown> of the control's property page
object. Will be used as the controlling unknown of <o PropPageHelper>.
@parm PropPageHelperInfo * | pInfo | Points to a <t PropPageHelperInfo>
structure allocated within the control's property page object.
Note that <o PropPageHelper> will hold onto a pointer to this
structure. These fields of <p pInfo> must be initialized by the
caller: <p idDialog>, <p idTitle>, <p hinst>, <p pproc>, <p iid>, and
<p dwUser>. The other fields will be initialized by <o PropPageHelper>.
@parm UINT | cbInfo | The size of the structure pointed to by <p punkOuter>
(used for version checking).
@parm LPUNKNOWN * | ppunk | Where to store a pointer to the non-delegating
<i IUnknown> of the allocatedd <o PropPageHelper> object. NULL is
stored in *<p ppunk> on error.
*/
STDAPI AllocPropPageHelper(LPUNKNOWN punkOuter, PropPageHelperInfo *pInfo,
UINT cbInfo, LPUNKNOWN *ppunk)
{
HRESULT hrReturn = S_OK; // function return code
CPropPageHelper *pthis = NULL; // allocated object
// make sure the version of <pInfo> is compatible with this object
if (cbInfo != sizeof(*pInfo))
return E_INVALIDARG;
// set <pthis> to point to new object instance
if ((pthis = New CPropPageHelper) == NULL)
goto ERR_OUTOFMEMORY;
TRACE("CPropPageHelper 0x%08lx created\n", pthis);
// initialize IUnknown state
pthis->m_cRef = 1;
pthis->m_punkOuter = (punkOuter == NULL ?
(IUnknown *) (INonDelegatingUnknown *) pthis : punkOuter);
// initialize IPropertyPage state
pthis->m_pInfo = pInfo;
// initialize the parts of <*m_pInfo> we are responsible for initializing
pthis->m_pInfo->psite = NULL;
pthis->m_pInfo->ppunk = NULL;
pthis->m_pInfo->cpunk = 0;
pthis->m_pInfo->hwnd = NULL;
pthis->m_pInfo->fDirty = FALSE;
pthis->m_pInfo->fLockDirty = FALSE;
// return a pointer to the non-delegating IUnknown implementation
*ppunk = (LPUNKNOWN) (INonDelegatingUnknown *) pthis;
goto EXIT;
ERR_OUTOFMEMORY:
hrReturn = E_OUTOFMEMORY;
goto ERR_EXIT;
ERR_EXIT:
// error cleanup
if (pthis != NULL)
Delete pthis;
*ppunk = NULL;
goto EXIT;
EXIT:
// normal cleanup
// (nothing to do)
return hrReturn;
}
//////////////////////////////////////////////////////////////////////////////
// IUnknown Implementation
//
STDMETHODIMP CPropPageHelper::NonDelegatingQueryInterface(REFIID riid,
LPVOID *ppv)
{
*ppv = NULL;
#ifdef _DEBUG
char ach[200];
TRACE("PropPageHelper::QI('%s')\n", DebugIIDName(riid, ach));
#endif
if (IsEqualIID(riid, IID_IUnknown))
*ppv = (IUnknown *) (INonDelegatingUnknown *) this;
else
if (IsEqualIID(riid, IID_IPropertyPage))
*ppv = (IPropertyPage *) this;
else
return E_NOINTERFACE;
((IUnknown *) *ppv)->AddRef();
return S_OK;
}
STDMETHODIMP_(ULONG) CPropPageHelper::NonDelegatingAddRef()
{
return ++m_cRef;
}
STDMETHODIMP_(ULONG) CPropPageHelper::NonDelegatingRelease()
{
if (--m_cRef == 0L)
{
// free the object
TRACE("CPropPageHelper 0x%08lx destroyed\n", this);
SetPageSite(NULL);
SetObjects(0, NULL);
Delete this;
return 0;
}
else
return m_cRef;
}
//////////////////////////////////////////////////////////////////////////////
// Propery Page Dialog Procedure
//
INT_PTR CALLBACK PropPageHelperDlgProc(HWND hwnd, UINT uiMsg, WPARAM wParam,
LPARAM lParam)
{
CPropPageHelper *pthis; // property page object
const char * szPropName = "this"; // property to store <pthis>
HRESULT hr;
// set <pthis> to the property page object
if ((pthis = (CPropPageHelper *) GetProp(hwnd, szPropName)) == NULL)
{
if ((uiMsg == WM_INITDIALOG) && (lParam != 0))
{
pthis = (CPropPageHelper *) lParam;
SetProp(hwnd, szPropName, (HANDLE) pthis);
pthis->m_pInfo->fLockDirty = TRUE;
BOOL f = pthis->m_pInfo->pproc(hwnd, WM_INITDIALOG, wParam, lParam,
pthis->m_pInfo, &hr);
pthis->m_pInfo->fLockDirty = FALSE;
return f;
}
else
return FALSE;
}
// do nothing if this instance of this property page window
// was only created to get information about the property page
// (in which case NULL is passed for the last parameter of
// CreateDialogParam())
if (pthis == NULL)
return FALSE;
if (uiMsg == WM_DESTROY)
RemoveProp(hwnd, szPropName);
return pthis->m_pInfo->pproc(hwnd, uiMsg, wParam, lParam, pthis->m_pInfo,
&hr);
}
//////////////////////////////////////////////////////////////////////////////
// IPropertyPage Implementation
//
STDMETHODIMP CPropPageHelper::SetPageSite(LPPROPERTYPAGESITE pPageSite)
{
TRACE("CPropPageHelper::SetPageSite\n");
// store new site pointer
if (m_pInfo->psite != NULL)
m_pInfo->psite->Release();
m_pInfo->psite = pPageSite;
if (m_pInfo->psite != NULL)
m_pInfo->psite->AddRef();
return S_OK;
}
STDMETHODIMP CPropPageHelper::Activate(HWND hwndParent, LPCRECT prc,
BOOL bModal)
{
TRACE("CPropPageHelper::Activate\n");
// create the property page dialog box (if it doesn't exist already)
if (m_pInfo->hwnd == NULL)
{
if ((m_pInfo->hwnd = CreateDialogParam(m_pInfo->hinst,
MAKEINTRESOURCE(m_pInfo->idDialog), hwndParent,
PropPageHelperDlgProc,
(LPARAM) this)) == NULL)
return E_OUTOFMEMORY;
}
// set the dialog box position to <prc>
Move(prc);
return S_OK;
}
STDMETHODIMP CPropPageHelper::Deactivate()
{
TRACE("CPropPageHelper::Deactivate\n");
if (m_pInfo->hwnd != NULL)
{
DestroyWindow(m_pInfo->hwnd);
m_pInfo->hwnd = NULL;
}
return S_OK;
}
STDMETHODIMP CPropPageHelper::GetPageInfo(LPPROPPAGEINFO pPageInfo)
{
TRACE("CPropPageHelper::GetPageInfo\n");
// default value
pPageInfo->pszDocString = NULL;
pPageInfo->pszHelpFile = NULL;
pPageInfo->dwHelpContext = 0;
HWND hwnd = NULL; // page window
// temporarily create the page window so we can get information from it
if ((hwnd = CreateDialogParam(m_pInfo->hinst,
MAKEINTRESOURCE(m_pInfo->idDialog), GetDesktopWindow(),
PropPageHelperDlgProc, 0)) != NULL)
{
TCHAR ach[200];
RECT rc;
int cch;
// set the <pPageInfo->size> to the dimensions of the window
GetWindowRect(hwnd, &rc);
pPageInfo->size.cx = rc.right - rc.left;
pPageInfo->size.cy = rc.bottom - rc.top;
// set the <pPageInfo->pszTitle> to the page title
if ((cch = LoadString(m_pInfo->hinst, m_pInfo->idTitle, ach, sizeof(ach)))
== 0)
ach[0] = 0;
if ((pPageInfo->pszTitle = (OLECHAR *)
TaskMemAlloc(sizeof(OLECHAR) * (cch + 1))) != NULL)
ANSIToUNICODE(pPageInfo->pszTitle, ach, cch + 1);
DestroyWindow(hwnd);
}
else
{
// set defaults for <*pPageInfo>
// random default dimensions of the window
pPageInfo->size.cx = pPageInfo->size.cy = 300;
// default page title. MUST be set, assigning to NULL will cause crash!
static TCHAR szDefault[] = "Control";
if ((pPageInfo->pszTitle = (OLECHAR *)
TaskMemAlloc(sizeof(OLECHAR) * (sizeof(szDefault)/sizeof(TCHAR)))) != NULL)
ANSIToUNICODE(pPageInfo->pszTitle, szDefault, sizeof(szDefault));
}
return S_OK;
}
STDMETHODIMP CPropPageHelper::SetObjects(ULONG cObjects, LPUNKNOWN FAR* ppunk)
{
TRACE("CPropPageHelper::SetObjects\n");
// release all pointers in <m_pInfo->ppunk>, then release <m_pInfo->ppunk>
// itself
if (m_pInfo->ppunk != NULL)
{
for (int ipunk = 0; ipunk < m_pInfo->cpunk; ipunk++)
m_pInfo->ppunk[ipunk]->Release();
Delete [] m_pInfo->ppunk;
m_pInfo->ppunk = NULL;
m_pInfo->cpunk = 0;
}
// if the caller just wanted to free the existing pointer, we're done
if (cObjects == 0)
return S_OK;
// set <m_pInfo->ppunk> to an array of pointers to the controls
// that this property page is operating on
if ((m_pInfo->ppunk = New LPUNKNOWN [cObjects]) == NULL)
return E_OUTOFMEMORY;
for ( ; cObjects > 0; cObjects--, ppunk++)
{
if (SUCCEEDED((*ppunk)->QueryInterface(m_pInfo->iid,
(LPVOID *) (m_pInfo->ppunk + m_pInfo->cpunk))))
m_pInfo->cpunk++;
}
return S_OK;
}
STDMETHODIMP CPropPageHelper::Show(UINT nCmdShow)
{
TRACE("CPropPageHelper::Show\n");
if (m_pInfo->hwnd != NULL)
{
ShowWindow(m_pInfo->hwnd, nCmdShow);
if ((nCmdShow == SW_SHOW) || (nCmdShow == SW_SHOWNORMAL))
SetFocus(m_pInfo->hwnd);
}
return S_OK;
}
STDMETHODIMP CPropPageHelper::Move(LPCRECT prc)
{
TRACE("CPropPageHelper::Move\n");
if (m_pInfo->hwnd != NULL)
SetWindowPos(m_pInfo->hwnd, NULL, prc->left, prc->top,
prc->right - prc->left, prc->bottom - prc->top, SWP_NOZORDER);
return S_OK;
}
STDMETHODIMP CPropPageHelper::IsPageDirty()
{
TRACE("CPropPageHelper::IsPageDirty\n");
return (m_pInfo->fDirty ? S_OK : S_FALSE);
}
STDMETHODIMP CPropPageHelper::Apply()
{
TRACE("CPropPageHelper::Apply\n");
HRESULT hr = E_NOTIMPL;
m_pInfo->pproc(m_pInfo->hwnd, WM_PPH_APPLY, 0, 0, m_pInfo, &hr);
return hr;
}
STDMETHODIMP CPropPageHelper::Help(LPCOLESTR lpszHelpDir)
{
TRACE("CPropPageHelper::Help\n");
HRESULT hr = S_FALSE;
m_pInfo->pproc(m_pInfo->hwnd, WM_PPH_HELP, (WPARAM) lpszHelpDir, 0,
m_pInfo, &hr);
return hr;
}
// helper for TranslateAccelerator(...), it find out the current focused
// child control is at the end of the tab list for the property page.
//
// hwndPage: the window handle of the property page
// nCmd: GW_HWNDPREV or GW_HWNDNEXT, indicates the moving direction for tab.
//
static BOOL IsEndOfTabList(HWND hwndPage, UINT nCmd)
{
if ((SendMessage(hwndPage, WM_GETDLGCODE, 0, 0) &
(DLGC_WANTALLKEYS | DLGC_WANTMESSAGE | DLGC_WANTTAB)) == 0)
{
HWND hwnd = GetFocus();
if (IsChild(hwndPage, hwnd))
{
// Get top level child for controls with children, like combo.
while (GetParent(hwnd) != hwndPage)
{
hwnd = GetParent(hwnd);
ASSERT(IsWindow(hwnd));
}
// check if at the end of the tab list
do
{
if ((hwnd = GetWindow(hwnd, nCmd)) == NULL)
return TRUE;
}
while ((GetWindowLong(hwnd, GWL_STYLE) &
(WS_DISABLED | WS_TABSTOP)) != WS_TABSTOP);
}
}
return FALSE;
}
// helper for TranslateAccelerator(...), it processes key board input messages
//
// hwndPage: the window handle of the property page.
// lpMsg: the message to process.
//
static BOOL PreTranslateMessage(HWND hwndPage, LPMSG lpMsg)
{
// Return key or Escape key.
if ((lpMsg->message == WM_KEYDOWN) &&
((lpMsg->wParam == VK_RETURN) || (lpMsg->wParam == VK_ESCAPE)))
{
// Special case: if control with focus is an edit control with
// ES_WANTRETURN style, let it handle the Return key.
TCHAR szClass[10];
HWND hwndFocus = GetFocus();
if ((lpMsg->wParam == VK_RETURN) &&
(hwndFocus != NULL) && IsChild(hwndPage, hwndFocus) &&
(GetWindowLong(hwndFocus, GWL_STYLE) & ES_WANTRETURN) &&
GetClassName(hwndFocus, szClass, 10) &&
(lstrcmpi(szClass, _T("EDIT")) == 0))
{
SendMessage(hwndFocus, WM_CHAR, lpMsg->wParam, lpMsg->lParam);
return TRUE;
}
return FALSE;
}
// don't translate non-input events
if ((lpMsg->message < WM_KEYFIRST || lpMsg->message > WM_KEYLAST) &&
(lpMsg->message < WM_MOUSEFIRST || lpMsg->message > WM_MOUSELAST))
return FALSE;
BOOL bHandled;
// If it's a WM_SYSKEYDOWN, temporarily replace the hwnd in the
// message with the hwnd of our first control, and try to handle
// the message for ourselves.
if ((lpMsg->message == WM_SYSKEYDOWN) && !IsChild(hwndPage, lpMsg->hwnd))
{
HWND hWndSave = lpMsg->hwnd;
lpMsg->hwnd = GetWindow(hwndPage, GW_CHILD);
bHandled = IsDialogMessage(hwndPage, lpMsg);
lpMsg->hwnd = hWndSave;
}
else
{
bHandled = IsDialogMessage(hwndPage, lpMsg);
}
return bHandled;
}
STDMETHODIMP CPropPageHelper::TranslateAccelerator(LPMSG lpMsg)
{
TRACE("CPropPageHelper::TranslateAccelerator\n");
ASSERT(m_pInfo);
ASSERT(IsWindow(m_pInfo->hwnd));
HWND hwndPage = m_pInfo->hwnd; // for convience
// let the dialog proc get a chance to process it first
{
HRESULT hr = E_NOTIMPL;
m_pInfo->pproc(hwndPage, WM_PPH_TRANSLATEACCELERATOR,
(WPARAM)lpMsg, 0, m_pInfo, &hr);
if (hr == S_OK)
return hr;
}
if (lpMsg->message == WM_KEYDOWN && lpMsg->wParam == VK_TAB &&
GetKeyState(VK_CONTROL) >= 0)
{
if (IsChild(hwndPage, GetFocus()))
{
// We already have the focus. Let's determine whether we should
// pass focus up to the frame.
if (IsEndOfTabList(hwndPage, GetKeyState(VK_SHIFT) < 0 ?
GW_HWNDPREV : GW_HWNDNEXT))
{
// fix for default button border
DWORD dwDefID = (DWORD) SendMessage(hwndPage, DM_GETDEFID, 0, 0);
if (HIWORD(dwDefID) == DC_HASDEFID)
{
HWND hwndDef = GetDlgItem(hwndPage, LOWORD(dwDefID));
if (hwndDef != NULL && IsWindowEnabled(hwndDef))
SendMessage(hwndPage, WM_NEXTDLGCTL, (WPARAM)hwndDef, 1L);
}
// Pass focus to the frame by letting the page site handle
// this message.
if (m_pInfo->psite
&& m_pInfo->psite->TranslateAccelerator(lpMsg) == S_OK)
return S_OK;
}
}
else
{
// We don't already have the focus. The frame is passing the
// focus to us.
HWND hwnd = GetTopWindow(hwndPage);
if (hwnd != NULL)
{
UINT gwInit;
UINT gwMove;
if (GetKeyState(VK_SHIFT) >= 0)
{
// Set the focus to the first tabstop in the page.
gwInit = GW_HWNDFIRST;
gwMove = GW_HWNDNEXT;
}
else
{
// Set the focus to the last tabstop in the page.
gwInit = GW_HWNDLAST;
gwMove = GW_HWNDPREV;
}
hwnd = GetWindow(hwnd, gwInit);
while (hwnd != NULL)
{
if ((GetWindowLong(hwnd, GWL_STYLE) &
(WS_DISABLED | WS_TABSTOP)) == WS_TABSTOP)
{
SendMessage(hwndPage, WM_NEXTDLGCTL, (WPARAM)hwnd, 1L);
return S_OK;
}
hwnd = GetWindow(hwnd, gwMove);
}
}
}
}
return PreTranslateMessage(hwndPage, lpMsg) ? S_OK : S_FALSE;
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %r9
push %rcx
push %rsi
lea addresses_WT_ht+0x4d1c, %r15
nop
nop
nop
nop
nop
sub $6773, %r9
mov (%r15), %rsi
nop
add $7443, %rsi
lea addresses_D_ht+0x1771c, %r10
nop
nop
nop
nop
add %rsi, %rsi
mov (%r10), %cx
nop
sub %rsi, %rsi
pop %rsi
pop %rcx
pop %r9
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r9
push %rbp
push %rbx
push %rcx
push %rdx
push %rsi
// Store
lea addresses_WT+0xb31c, %rsi
nop
nop
nop
nop
add %rbp, %rbp
mov $0x5152535455565758, %rcx
movq %rcx, %xmm5
movups %xmm5, (%rsi)
nop
nop
nop
nop
cmp $32324, %rsi
// Store
lea addresses_RW+0x1dddc, %rdx
nop
nop
nop
nop
sub $8572, %rbx
movl $0x51525354, (%rdx)
sub $34623, %rcx
// Store
lea addresses_WC+0x7762, %rbx
clflush (%rbx)
nop
nop
nop
xor $58167, %r9
mov $0x5152535455565758, %r13
movq %r13, %xmm6
vmovups %ymm6, (%rbx)
nop
nop
nop
nop
add $27151, %r9
// Load
lea addresses_D+0x6602, %rdx
nop
nop
nop
nop
xor %rcx, %rcx
movb (%rdx), %r9b
nop
nop
nop
and $54866, %rdx
// Store
lea addresses_UC+0x871c, %rcx
clflush (%rcx)
nop
nop
add %rsi, %rsi
movl $0x51525354, (%rcx)
nop
nop
nop
cmp $25536, %rdx
// Store
lea addresses_WC+0x221c, %r13
nop
nop
add $17680, %rbp
mov $0x5152535455565758, %r9
movq %r9, %xmm1
movups %xmm1, (%r13)
nop
nop
inc %r9
// Load
mov $0xfe49f0000000c5c, %r9
nop
nop
nop
nop
nop
sub %rcx, %rcx
movups (%r9), %xmm5
vpextrq $1, %xmm5, %rbp
nop
nop
nop
nop
nop
add %rcx, %rcx
// Faulty Load
lea addresses_D+0xf71c, %rcx
nop
nop
nop
nop
nop
and %rbx, %rbx
movb (%rcx), %r13b
lea oracles, %rbp
and $0xff, %r13
shlq $12, %r13
mov (%rbp,%r13,1), %r13
pop %rsi
pop %rdx
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 10, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_UC'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 8, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 6, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_D'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'36': 27}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
//===-- Implementation of rintf function ----------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "src/math/rintf.h"
#include "src/__support/common.h"
#include "utils/FPUtil/NearestIntegerOperations.h"
namespace __llvm_libc {
LLVM_LIBC_FUNCTION(float, rintf, (float x)) {
return fputil::roundUsingCurrentRoundingMode(x);
}
} // namespace __llvm_libc
|
MRUG EQU 00100100B
LJMP START
ORG 100H
START:
MOV R2, #MRUG
SETB C
DIODA:
MOV P1.7, C
MOV A, #5
CALL DELAY_100MS
MOV A, R2
RLC A
MOV R2, A
SJMP DIODA |
; ********************************************************************************************
; ********************************************************************************************
;
; Name : continue.asm
; Purpose : ..
; Created : 15th Nov 1991
; Updated : 4th Jan 2021
; Authors : Fred Bowen
;
; ********************************************************************************************
; ********************************************************************************************
;**********************************************************
;*
;* CONTINUE Execution after STOP/END
;*
;**********************************************************
cont bne cont_rts ; make sure there is a terminator
bbs4 runmod,edit_err ; [910620]
bbs7 runmod,cont_rts ; if in run-mode just rts
ldx #errcn ; continue error.
ldy oldtxt+1 ; a stored txtptr of zero set up by INIT_STACK
+lbeq error ; indicates there is nothing to continue
lda oldtxt ; STOP, END, typing crlf to INPUT, and STOP key
sta txtptr
sty txtptr+1
lda oldlin
ldy oldlin+1
sta curlin
sty curlin+1
setexc smb7 runmod ; set up run mode
lda #0
sta autinc ; turn auto increment off
sta autinc+1
sta intval ; enable & reset collision-trapping mechanism
sta _autoinsert ; disable auto-insert mode ?????
ldx #2 ; turn off all interrupt trip flags
l72_1 sta int_trip_flag,x
dex
bpl l72_1
jsr _setmsg ; turn kernel messages off & rts
cont_rts
rts
;.end
; ********************************************************************************************
;
; Date Changes
; ==== =======
;
; ********************************************************************************************
|
extern m7_ippsSMS4EncryptCBC_CS1:function
extern n8_ippsSMS4EncryptCBC_CS1:function
extern y8_ippsSMS4EncryptCBC_CS1:function
extern e9_ippsSMS4EncryptCBC_CS1:function
extern l9_ippsSMS4EncryptCBC_CS1:function
extern n0_ippsSMS4EncryptCBC_CS1:function
extern k0_ippsSMS4EncryptCBC_CS1:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsSMS4EncryptCBC_CS1
.Larraddr_ippsSMS4EncryptCBC_CS1:
dq m7_ippsSMS4EncryptCBC_CS1
dq n8_ippsSMS4EncryptCBC_CS1
dq y8_ippsSMS4EncryptCBC_CS1
dq e9_ippsSMS4EncryptCBC_CS1
dq l9_ippsSMS4EncryptCBC_CS1
dq n0_ippsSMS4EncryptCBC_CS1
dq k0_ippsSMS4EncryptCBC_CS1
segment .text
global ippsSMS4EncryptCBC_CS1:function (ippsSMS4EncryptCBC_CS1.LEndippsSMS4EncryptCBC_CS1 - ippsSMS4EncryptCBC_CS1)
.Lin_ippsSMS4EncryptCBC_CS1:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsSMS4EncryptCBC_CS1:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsSMS4EncryptCBC_CS1]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsSMS4EncryptCBC_CS1:
|
#include "Window.h"
#include "App.h"
#include "Defs.h"
#include "Log.h"
#include "SDL/include/SDL.h"
Window::Window(App* application, bool start_enabled) : Module(application, start_enabled)
{
window = NULL;
screenSurface = NULL;
name.Create("window");
}
// Destructor
Window::~Window()
{
}
// Called before render is available
bool Window::Awake(pugi::xml_node& config)
{
LOG("Init SDL window & surface");
bool ret = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
// Create window
// L01: DONE 6: Load all required configurations from config.xml
Uint32 flags = SDL_WINDOW_SHOWN;
fullscreen = config.child("fullscreen").attribute("value").as_bool(false);
bool borderless = config.child("borderless").attribute("value").as_bool(false);
bool resizable = config.child("resizable").attribute("value").as_bool(false);
bool fullscreen_window = config.child("fullscreen_window").attribute("value").as_bool(false);
width = config.child("resolution").attribute("width").as_int(640);
height = config.child("resolution").attribute("height").as_int(480);
scale = config.child("resolution").attribute("scale").as_int(1);
if(fullscreen == true) flags |= SDL_WINDOW_FULLSCREEN;
if(borderless == true) flags |= SDL_WINDOW_BORDERLESS;
if(resizable == true) flags |= SDL_WINDOW_RESIZABLE;
if(fullscreen_window == true) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
window = SDL_CreateWindow(app->GetTitle(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags);
if(window == NULL)
{
LOG("Window could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
// Get window surface
screenSurface = SDL_GetWindowSurface(window);
}
}
return ret;
}
// Called before quitting
bool Window::CleanUp()
{
LOG("Destroying SDL window and quitting all SDL systems");
// Destroy window
if(window != NULL)
{
SDL_DestroyWindow(window);
}
// Quit SDL subsystems
SDL_Quit();
return true;
}
// Set new window title
void Window::SetTitle(const char* new_title)
{
//title.create(new_title);
SDL_SetWindowTitle(window, new_title);
}
void Window::GetWindowSize(uint& width, uint& height) const
{
width = this->width;
height = this->height;
}
uint Window::GetScale() const
{
return scale;
}
// Retrieve window Width
int Window::GetWidth() const
{
return (int) width;
}
// Retrieve window height
int Window::GetHeight() const
{
return (int) height;
}
void Window::SwitchScreen()
{
if (fullscreen == true)
{
SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN);
}
else
{
SDL_SetWindowFullscreen(window, 0);
}
} |
; A033970: Trajectory of 1 under map n->27n+1 if n odd, n->n/2 if n even
; Submitted by Jon Maiga
; 1,28,14,7,190,95,2566,1283,34642,17321,467668,233834,116917,3156760,1578380,789190,394595,10654066,5327033,143829892,71914946,35957473,970851772,485425886,242712943,6553249462
add $0,1
mov $1,$0
mov $0,3
lpb $1
mov $2,$0
mod $2,2
mov $3,2
sub $3,$2
mov $4,$0
mul $0,2
lpb $2
mul $0,9
add $0,2
mul $0,3
sub $2,1
lpe
lpb $3
div $0,2
sub $3,1
lpe
sub $1,1
lpe
mov $0,$4
div $0,3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r14
push %r15
push %r8
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0xcae7, %rdi
nop
nop
and $5699, %r8
movb (%rdi), %r13b
and %rax, %rax
lea addresses_A_ht+0x4648, %r10
nop
nop
nop
nop
and $23361, %r14
mov (%r10), %r15w
nop
nop
xor $59452, %rdi
lea addresses_WT_ht+0x19258, %r15
nop
nop
nop
nop
inc %r13
movups (%r15), %xmm6
vpextrq $1, %xmm6, %r10
nop
nop
nop
nop
xor $16837, %r14
lea addresses_A_ht+0x39fa, %rsi
lea addresses_normal_ht+0x179c8, %rdi
nop
nop
nop
nop
xor %rax, %rax
mov $32, %rcx
rep movsb
nop
cmp %r10, %r10
lea addresses_A_ht+0x3318, %r10
nop
nop
nop
nop
nop
and $44514, %r14
movb (%r10), %r8b
nop
cmp %r8, %r8
lea addresses_UC_ht+0x1a248, %rsi
and %r10, %r10
mov (%rsi), %r15w
sub %rax, %rax
lea addresses_WT_ht+0x1193c, %rsi
lea addresses_normal_ht+0x1df79, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
cmp %r10, %r10
mov $105, %rcx
rep movsb
nop
nop
add $29582, %r8
lea addresses_WC_ht+0x15e88, %r10
clflush (%r10)
nop
and $45864, %rax
movb (%r10), %r13b
nop
nop
nop
nop
nop
sub $58827, %r8
lea addresses_normal_ht+0x17508, %r14
nop
nop
sub $63477, %r8
movb $0x61, (%r14)
nop
nop
nop
nop
xor %rax, %rax
lea addresses_WT_ht+0x4b28, %rsi
lea addresses_normal_ht+0x1cfc8, %rdi
clflush (%rsi)
nop
nop
nop
nop
and %r15, %r15
mov $53, %rcx
rep movsl
nop
nop
nop
nop
nop
add $12545, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r15
pop %r14
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r8
push %rcx
push %rdx
push %rsi
// Store
lea addresses_D+0x6f78, %r12
nop
nop
sub %r10, %r10
movw $0x5152, (%r12)
nop
dec %rdx
// Store
lea addresses_WC+0x17542, %r11
clflush (%r11)
nop
nop
nop
nop
add %rdx, %rdx
movl $0x51525354, (%r11)
add $57609, %rcx
// Store
lea addresses_A+0x1a248, %r10
nop
nop
nop
nop
cmp %r12, %r12
movw $0x5152, (%r10)
cmp %rdx, %rdx
// Load
lea addresses_D+0x2068, %r10
nop
nop
nop
sub %r11, %r11
movb (%r10), %cl
nop
nop
add $4740, %r12
// Faulty Load
lea addresses_D+0xf848, %r11
nop
nop
nop
xor $46489, %rsi
movups (%r11), %xmm0
vpextrq $0, %xmm0, %r8
lea oracles, %rdx
and $0xff, %r8
shlq $12, %r8
mov (%rdx,%r8,1), %r8
pop %rsi
pop %rdx
pop %rcx
pop %r8
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 9}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_WT_ht'}, 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_normal_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 5}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
*
* COPYRIGHT:
*
* Unless otherwise noted, all files are Copyright (c) 1999 Amiga, Inc.
* All rights reserved.
*
* DISCLAIMER:
*
* This software is provided "as is". No representations or warranties
* are made with respect to the accuracy, reliability, performance,
* currentness, or operation of this software, and all use is at your
* own risk. Neither Amiga nor the authors assume any responsibility
* or liability whatsoever with respect to your use of this software.
*
; classinit.asm
;
; OPTIMON
SECTION text,code
;---------------------------------------------------------------------------
NOLIST
INCLUDE "exec/types.i"
INCLUDE "exec/libraries.i"
INCLUDE "exec/lists.i"
INCLUDE "exec/alerts.i"
INCLUDE "exec/initializers.i"
INCLUDE "exec/resident.i"
INCLUDE "libraries/dos.i"
INCLUDE "cdxl_rev.i"
INCLUDE "classbase.i"
LIST
;---------------------------------------------------------------------------
XREF _LibInit
XREF _LibOpen
XREF _LibClose
XREF _LibExpunge
XREF _ObtainCDXLEngine
;---------------------------------------------------------------------------
XDEF LibReserved
;---------------------------------------------------------------------------
; First executable location, must return an error to the caller
Start:
moveq #-1,d0
rts
;-----------------------------------------------------------------------
ROMTAG:
DC.W RTC_MATCHWORD ; UWORD RT_MATCHWORD
DC.L ROMTAG ; APTR RT_MATCHTAG
DC.L ENDTAG ; APTR RT_ENDSKIP
DC.B RTF_AUTOINIT ; UBYTE RT_FLAGS
DC.B VERSION ; UBYTE RT_VERSION
DC.B NT_LIBRARY ; UBYTE RT_TYPE
DC.B 0 ; BYTE RT_PRI
DC.L LibName ; APTR RT_NAME
DC.L LibId ; APTR RT_IDSTRING
DC.L LibInitTable ; APTR RT_INIT
ENDTAG:
LibName DC.B 'cdxl.datatype',0
LibId VSTRING
CNOP 0,4
LibInitTable:
DC.L ClassBase_SIZEOF
DC.L LibFuncTable
DC.L LibDataTable
DC.L _LibInit
V_DEF MACRO
DC.W \1+(*-LibFuncTable)
ENDM
LibFuncTable:
DC.W -1
V_DEF _LibOpen
V_DEF _LibClose
V_DEF _LibExpunge
V_DEF LibReserved
V_DEF _ObtainCDXLEngine
DC.W -1
LibDataTable:
INITWORD LIB_REVISION,REVISION
DC.W 0
CNOP 0,4
;-----------------------------------------------------------------------
LibReserved:
moveq #0,d0
rts
;-----------------------------------------------------------------------
END
|
; int __FASTCALL__ strlen(char *s)
; return length of s
; 12.2006 aralbrec
SECTION code_clib
PUBLIC strlen
PUBLIC _strlen
; enter: hl = char *s
; exit : hl = length, z flag set if 0 length
; uses : af, bc, hl
.strlen
._strlen
IF FORrcmx000
ld b,h
ld c,l
dec bc
ld hl,-1 ; our counter
.strlen1
inc bc
inc hl
ld a,(bc)
and a
jp nz, strlen1
ld a,h
or l
ret
ELSE
; A funky version that's quicker than the
; usual implementation for lengths > 1
xor a
ld c,a
ld b,a
cpir
ld hl,$ffff
sbc hl,bc
ret
ENDIF
|
<%
from pwnlib.shellcraft.arm.linux import syscall
%>
<%page args="path"/>
<%docstring>
Invokes the syscall chdir. See 'man 2 chdir' for more information.
Arguments:
path(char): path
</%docstring>
${syscall('SYS_chdir', path)}
|
; int close(int fd)
SECTION code_fcntl
PUBLIC _close
EXTERN _close_fastcall
_close:
pop af
pop hl
push hl
push af
jp _close_fastcall
|
; A226405: Expansion of x/((1-x-x^3)*(1-x)^3).
; 0,1,4,10,21,40,71,120,196,312,487,749,1139,1717,2571,3830,5683,8407,12408,18281,26898,39537,58071,85245,125082,183478,269074,394534,578418,847927,1242926,1821840,2670295,3913782,5736217,8407142,12321590,18058510,26466393,38788763,56848093,83315347,122105013,178954052,262270389,384376437,563331570,825603087,1209980700,1773313495,2598917857,3808899883,5582214756,8181134044,11990035412,17572251708,25753387348,37743424413,55315677832,81069066950,118812493193,174128172916,255197241819,374009737028,548137912024,803335155988,1177344895227,1725482809529,2528817967863,3706162865505,5431645677519,7960463647938,11666626516071,17098272196291,25058735847004,36725362365925,53823634565142,78882370415149,115607732784155,169431367352457,248313737770846,363921470558322,533352837914182,781666575688514,1145588046250406,1678940884168243,2460607459860498,3606195506114732,5285136390286891,7745743850151394,11351939356270221,16637075746561298,24382819596716970,35734758952991562,52371834699557325,76754654296278855,112489413249275073,164861247948837151,241615902245120857,354105315494400880
mov $3,$0
mov $5,$0
lpb $3
mov $0,$5
sub $3,1
sub $0,$3
mov $2,$0
seq $0,48625 ; Pisot sequence P(4,6).
sub $2,1
sub $0,$2
sub $0,6
mov $4,$0
cmp $6,0
add $4,$6
div $0,$4
add $0,$4
add $1,$0
lpe
mov $0,$1
|
[BotW_Gamespeed_V208]
moduleMatches = 0x6267BFD0
.origin = codecave
# Constants
const_0.5:
.float 0.5
const_1:
.float 1
const_1.5:
.float 1.5
const_30:
.float 30
busSpeed:
.float 62156250
convSub:
.uint 0x43300000
.uint 0x80000000
# Variables
fpsLimit:
.float $fpsLimit
lowFPSLimit:
.float $lowFPSLimit
bufferSizeDivider:
.float $frameAverageAmount
averageFPS30:
.float $fpsLimit
averageFPS30Inv:
.float 900/$fpsLimit
averageFPS1.5:
.float (1.5*$fpsLimit)/30
averageFPS1.5Inv:
.float 45/$fpsLimit
averageFPS1:
.float $fpsLimit/30
averageFPS1Inv:
.float 30/$fpsLimit
averageFPS0.5:
.float $fpsLimit/60
averageFPS0.5Inv:
.float 30/(2*$fpsLimit)
averageSum:
.float $fpsLimit*$frameAverageAmount
initBuffer:
.byte 0
bufferStart:
.ptr 0xD8
bufferCurrEntry:
.ptr 0xD8
bufferEnd:
.ptr 0xD8+(4*$frameAverageAmount)
; Useful for trying potential FPS values. Need to set debugMode = 1 to enable the debugging in the interface and code.
debugAddr:
.ptr 0x00000000
debugMultiplier:
.float $debugMultiplier
# Code
_calculateGamespeed:
stw r0, 0x78(r30) ; Execute original instruction that got replaced with a jump to this function
; If static FPS is enabled, always set currently "running" FPS to $fpsLimit
li r3, $staticFPSMode ; Load the $staticFPSMode setting into r3
cmpwi r3, 1 ; Compare with 1, which is when it's enabled
bne _calculateDynamicFPS ; If the comparison is not equal, run
lis r3, fpsLimit@ha ; Load current FPS limit...
lfs f10, fpsLimit@l(r3) ; ...into f10
b _setGamespeed ; Skip dynamic FPS code when static mode is enabled and go to the game speed setting code
; Calculate speed of current frame (FPS). It's calculated by using the ticks between the previous frame and now, which is stored in r12, and the amount of ticks that the Wii U executes in a second (the bus speed).
_calculateDynamicFPS:
xoris r12, r12, 0x8000 ; Flip the sign bit of int ticks for floating point conversion
stw r12, 0xD4(r30) ; Store sign flipped ticks in memory as lower half of double
lis r12, 0x4330 ; Create upper half of ticks double
stw r12, 0xD0(r30) ; Store it in upper half of memory
lfd f10, 0xD0(r30) ; Load full double ticks into f10
lis r12, convSub@ha ; Load number to subtract from tick double...
lfd f12, convSub@l(r12) ; ...to create tick float into f12
fsub f10, f10, f12 ; Do the subtraction
frsp f10, f10 ; Round to single precision and tick float is in f10
lis r12, const_1@ha ; Load float of 1...
lfs f12, const_1@l(r12) ; ...into f12
fdivs f10, f12, f10 ; Divide 1 by ticks
lis r12, busSpeed@ha ; Load wii u bus speed...
lfs f12, busSpeed@l(r12) ; ...into f12
fmuls f10, f12, f10 ; Multiply bus speed to have current fps in f10. (1/ticks)*bus speed
; Initialize the circular buffer with default values whenever a setting gets changed
_initializeAverageBuffer:
lis r12, initBuffer@ha ; Load the initBuffer variable to see whether the buffer has to be initialized/reset again
lbz r11, initBuffer@l(r12) ; ...to check whether/what the current buffer settings are
cmpwi r11, 1 ; Compare the previously $frameAverageAmount with the current $frameAverageAmount
beq _calcAverageFPS ; Continue to calulating the average FPS if the previous settings are the same as the permanently set settings
li r11, 1 ; Load "1" into r11
stb r11, initBuffer@l(r12) ; Store that 1 into the initBuffer so that it will only initialize this once
lis r12, fpsLimit@ha ; Load current FPS limit...
lfs f10, fpsLimit@l(r12) ; ...into f10
lis r12, bufferStart@ha ; Load offset to the start of the averaging buffer...
lwz r12, bufferStart@l(r12) ; ...into r12
lis r3, bufferEnd@ha ; Load offset to the end of the averaging buffer...
lwz r3, bufferEnd@l(r3) ; ...into r3
add r11, r12, r30 ; Make full offset by adding r30 (the empty buffer offset) to r12, which is the buffer offset.
stfs f10, 0x0(r11) ; Store f10 to the address in r12 + 0x04 using this specific instruction, which also adds the 0x04 to r12
addi r12, r12, 0x04 ; Add 0x04 to the buffer offset to make the next entry offset
cmpw r12, r3 ; Compare the current address offset in r12 with the address offset in r3
ble .-0x10 ; Loop back until the whole buffer is initialized with the value from f12
; Calculate the rolling average FPS over the last N amount of frames which are stored in the circular buffer
_calcAverageFPS:
lis r3, bufferCurrEntry@ha ; Load the offset to the current value
lwz r12, bufferCurrEntry@l(r3) ; Load the current buffer offset
lis r11, averageSum@ha ; Load the current average sum
lfs f7, averageSum@l(r11) ; ...into f7
add r3, r12, r30 ; Add r12 to r30 to create the whole offset, since Cemu's assembly doesn't support LFSX and STFX
lfs f12, 0x0(r3) ; Load the value that's stored in the current offset
fadds f7, f7, f10 ; Add the FPS from this current frame
fsubs f7, f7, f12 ; Subtract this value from the current average sum
stfs f7, averageSum@l(r11) ; Store this new average sum again
stfs f10, 0x0(r3) ; Store the FPS value from this current frame in place of the old value
; Store the offset to the next buffer entry
lis r11, bufferEnd@ha ; Load offset to the end of the averaging buffer
lwz r11, bufferEnd@l(r11) ; ...into r11
addi r12, r12, 0x04 ; Add 0x04 to the current entry offset to have the next entry offset
cmpw r11, r12 ; Compare this new entry offset to the end offset
bgt .+0x0C ; Skip the next 2 lines if the next entry offset is smaller
lis r12, bufferStart@ha ; Load start of the buffer offset...
lwz r12, bufferStart@l(r12) ; ...into r12
lis r3, bufferCurrEntry@ha ; Load current buffer entry
stw r12, bufferCurrEntry@l(r3) ; ...into r12
lis r3, bufferSizeDivider@ha ; Load the buffer size divider
lfs f10, bufferSizeDivider@l(r3); ...into f10
fdivs f10, f7, f10 ; Divide the average FPS sum by the buffer size divider to get the average FPS
; Calculates the gamespeed (which is stored in f10 regardless of average or static code path)
_setGamespeed:
; Prevent the FPS from going below 30FPS.
lis r11, lowFPSLimit@ha ; Load the lowest FPS that the game speed may be set to...
lfs f12, lowFPSLimit@l(r11) ; ...into f12
fcmpu cr0, f10, f12 ; Compare the calculated FPS with the lowest FPS limit
bgt .+0x08 ; Skip the next line when the calculated FPS is higher then the low limit
fmr f10, f12 ; ...if this line isn't skipped, set the FPS to that low limit
; Set average speed (30 range)
lis r11, averageFPS30@ha ; Store the calculated FPS...
stfs f10, averageFPS30@l(r11) ; ...to replace constants that normally use 30
; Set average speed (1.5 range)
lis r11, const_1.5@ha ; Load a constant float with 1.5
lfs f7, const_1.5@l(r11) ; ...into f7
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f7, f10, f7 ; Multiply the calculated FPS by 1.5
fdivs f7, f7, f12 ; Divide this new divided calculated FPS by 30
lis r11, averageFPS1.5@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS1.5@l(r11) ; ...to replace constants that normally use 1.5
; Set average speed (1.0 range)
fdivs f7, f10, f12 ; Divide the calculated FPS by 30
lis r11, averageFPS1@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS1@l(r11) ; ...to replace constants that normally use 1
; Set average speed (0.5 range)
fadds f12, f12, f12 ; Add 30.0 to 30.0 to get 60.0
fdivs f7, f10, f12 ; Divide the calculated FPS by 60
lis r11, averageFPS0.5@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS0.5@l(r11) ; ...to replace constants that normally use 0.5
; Set average speed (inverted 30 range)
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f12, f12, f12 ; Multiply 30.0 by 30.0 to get 900.0
fdivs f7, f12, f10 ; Divide 900.0 by the calculated FPS to invert the FPS
lis r11, averageFPS30Inv@ha ; Store the inverted 30.0 float...
stfs f7, averageFPS30Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 1.5 range)
lis r11, const_1.5@ha ; Load a constant float with 1.5...
lfs f7, const_1.5@l(r11) ; ...into f7
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f7, f7, f12 ; Multiply 30.0 by 1.5 to get 45.0 and store it in f7
fdivs f7, f7, f10 ; Divide 45.0 by the calculated FPS to invert the FPS
lis r11, averageFPS1.5Inv@ha ; Store the inverted 1.5 float...
stfs f7, averageFPS1.5Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 1.0 range)
fdivs f7, f12, f10 ; Divides 30.0 by the calculated FPS to invert the FPS
lis r11, averageFPS1Inv@ha ; Store the inverted 1.0 float...
stfs f7, averageFPS1Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 0.5 range)
fadds f7, f10, f10 ; Add the calculated FPS to itself and store it in f7
fdivs f7, f12, f7 ; Divide 30.0 by 2 * the calculated FPS and store it in f7
lis r11, averageFPS0.5Inv@ha ; Store the inverted 0.5 float...
stfs f7, averageFPS0.5Inv@l(r11); ...to replace constants that are lower when FPS is higher
; Check whether debug mode is on
li r11, $debugMode ; Load debugMode value in r11
cmpwi r11, 1 ; Compare the value with 1
bnelr ; If it's not equal, return back to the link register. Otherwise, run the following lines too...
lis r11, debugMultiplier@ha ; Load the debug multiplier...
lfs f12, debugMultiplier@l(r11) ; ...which is used to modify the calulated FPS to experiment with potential FPS values
fmuls f7, f7, f12 ; Multiply the current FPS with this debug multiplier
lis r11, debugAddr@ha ; Load the pointer to the debug value address...
lwz r11, debugAddr@l(r11) ; ...into r11
stfs f7, 0x0(r11) ; Store the multiplied value in the address from the pointer
blr ; Return back to the address stored in the link register
; Multiplies the time draining using the calculated FPS
_changeArrowTimeDrain:
lfs f1, 0xFC(r11) ; Execute original instruction that got replaced with this codecave jump
lis r12, averageFPS1Inv@ha ; Load the average FPS...
lfs f0, averageFPS1Inv@l(r12) ; ...into f0
fmuls f1, f1, f0 ; Multiply the time draining value by the average FPS divider
blr ; Return to the address that's stored in the link register
; Multiplies the distance you travel during the flurry rush dash using the calculated FPS
_changeFlurryRush:
lis r4, averageFPS1@ha ; Load average FPS into f8..
lfs f8, averageFPS1@l(r4) ; ...which is a float register that's safe to use since it's initialized later
fmuls f13, f13, f8 ; Multiply the flurry rush distance (stored in f1) with the FPS multiplier
fcmpu cr0, f13, f29 ; Execute original instruction that got replaced with this codecave jump
blr ; Return to the address that's stored in the link register
# Patches
0x1031E2C0 = .float 2
0x031FACD0 = nop ; Disable vsync
0x031FACF4 = nop ; Disable vsync loop
0x031FA97C = bla _calculateGamespeed ; Replace an instruction that gets called every frame to calculate the FPS
0x100775AC = .float -999.0 ; Disable something that makes thunderblight ganon yeet off
0x02C6B8F8 = bla _changeFlurryRush ; Fix the flurry rush distance
0x02D5F760 = bla _changeArrowTimeDrain ; Fix the stamina drain during arrow time
0x03793328 = nop
0x03793334 = nop
0x03793378 = lis r29, averageFPS1Inv@ha ; Load the calculated FPS value
0x03793380 = lfs f0, averageFPS1Inv@l(r29) ; ...to use that as animation speed
0x0379338C = nop ; Prevent an instruction from overwriting the loaded value
0x03415C1C = lis r12, averageFPS1Inv@ha ; Load the calculated FPS value
0x03415C24 = lfs f0, averageFPS1Inv@l(r12) ; ...to store that for the GUI speed value
0x03415C2C = nop ; Prevent an instruction from overwriting the loaded value
0x02D90D2C = lis r10, averageFPS30@ha
0x02D90D30 = lfs f11, averageFPS30@l(r10)
0x02D90D88 = lis r10, averageFPS30@ha ; Fix stamina regen by loading the calculated FPS value...
0x02D90D8C = lfs f11, averageFPS30@l(r10) ; ...instead of the normal static 30.0 float it uses
0x037DC35C = lis r12, averageFPS1Inv@ha ; Fix audio looping by loading the calculated FPS value...
0x037DC360 = lfs f13, averageFPS1Inv@l(r12) ; ...instead of the normal static 1.0 float it uses
0x02F62B3C = lis r12, averageFPS1Inv@ha ; Fix map scrolling by loading the calculated FPS value...
0x02F62B40 = lfs f0, averageFPS1Inv@l(r12) ; ...instead of the normal static 1.0 float it uses
0x020E730C = lis r12, averageFPS30Inv@ha ; Fix arrow speed by loading the calculated FPS value...
0x020E731C = lfs f13, averageFPS30Inv@l(r12); ...instead of the normal static 30.0 float it uses
0x020E3EB0 = lis r12, averageFPS0.5@ha ; Modify something to do with arrow bounce and distance by loading the calculated FPS value...
0x020E3EB8 = lfs f13, averageFPS0.5@l(r12) ; ...instead of the normal static 0.5 float it uses
0x020E5390 = lis r10, averageFPS0.5@ha ; Modify the distance arrows travel straight by loading the calculated FPS value...
0x020E5398 = lfs f13, averageFPS0.5@l(r10) ; ...instead of the normal static 0.5 float it uses
0x033609D8 = lis r6, averageFPS1Inv@ha ; Fix shield surfing by loading the calculated FPS value...
0x033609E0 = lfs f0, averageFPS1Inv@l(r6) ; ...instead of the normal static 1.0 float it uses
0x02B951E8 = lis r4, averageFPS1.5Inv@ha ; Fix vertical sensitivity while using runes by loading the calculated FPS value...
0x02B951F0 = lfs f11, averageFPS1.5Inv@l(r4); ...instead of the normal static 1.5 float it uses
0x02B95238 = lis r7, averageFPS30@ha ; Fix vertical gyro sensitivity while using runes by loading the calculated FPS value...
0x02B95240 = lfs f9, averageFPS30@l(r7) ; ...instead of the normal static 30.o float it uses
|
; A127233: a(n) = n!*(n*(n+1)/2)!.
; Submitted by Jon Maiga
; 1,1,12,4320,87091200,156920924160000,36785478363630796800000,1536637256843037856927580160000000,14998770936168817088309737749441675264000000000,43408511507665453002645192043544271642563569306828800000000000
mov $2,$0
seq $0,52295 ; a(n) = (n*(n+1)/2)!.
lpb $2
mul $0,$2
sub $2,1
lpe
|
; A107868: Column 0 of triangle A107867; a(n) = C( n*(n-1)/2 + n + 1, n).
; 1,2,6,35,330,4368,74613,1560780,38608020,1101716330,35607051480,1285063345176,51209646652255,2232785266876080,105710363656182600,5399936810873056584,295998326072989842600,17328840976366636057110
sub $1,$0
bin $1,2
add $1,1
bin $1,$0
mov $0,$1
|
IN 10H
CALL SHUTDOWN ;; SHUTDOWN WILL CLEAR OUR SCREEN
PUSH PSW
PUSH B
PUSH H
PUSH D
CALL STDM ;; STDM MAY CHANGE REGISTERS
;; SO WE SAVE THEM
POP H
POP D
POP B
POP PSW
CALL DCD
MVI B,00H ;; COUNTER FOR CHARACTERS GIVEN
MVI E,00H ;; FOR RANDOM USE
BEGIN:
CALL KIND ;; READ INPUT
CPI 85H ;; COMPARE WITH FETCH PC CODE
JNZ BEGIN ;; IF NOT EQUAL WAIT UNTIL WE PRESS IT
JMP OP1 ;; WE PRESSED OUR FIRST FETCH PC
READ_IN:
CALL CUSTOM_KIND;; INPUT
MOV C,A ;; SAVE INPUT
CPI 85H ;; COMPARE WITH THE CODE OF FETCH_PC
JNZ CHECK ;; WE DIDNT PRESS FETCH_PC
MOV A,B ;; WE PRESSED FETCH_PC
CPI 00H ;; FETCH_PC WILL EFFECT US
;; ONLY IF WE HAVE
;; REACHED OUR 4TH CHARACKTER
JNZ OP
OP1:
CALL INITIALIZE ;; FETCH_PC EFFECT
;; OUTPUT MUST BE . . _ _ _ _
SHINE: ;; LET IT SHINE
LXI D,0B00H ;; SET OUR BEGINNING OUTPUT ADDRESS
CALL DISPLAY ;; DIPLAY
JMP READ_IN
OP:
CPI 04H ;; COMPARE WITH 4
JC READ_IN ;; WE HAVNT REACH OUR 4TH CHARACKET
JMP OP1
CHECK: ;; WE DIDNT PRESS FETCH_PC
MOV A,C ;; MOVE TO A OUR INPUT
CPI 10H
JNC READ_IN ;; CHECH IF THE INPUT
;; IS AN ACCEPTABLE CHARACTER( 0-F )
ALLOCATE: ;; ALL OK TIME TO ALLOCATE THE INPUT
MOV A,B
CPI 04H ;; IF IT THE 5TH CHARACTER GIVEN
JNC ROLLING ;; WE ACCEPT ONLY 1 - 2 - 3
;; FOR ROLLING OR CENTRILIZE
LXI H,0B00H ;; WE START CHECKING FOR
;; FREE SPACE TO PUT OUR INPUT
PRO:
CPI 00H ;; WE START FROM THE FIRST
;; 7SEGMENT AND INCREASE
;; UNTIL WE REACH OUR LOCATION
JZ HIT ;; WE FOUND OUR FREE SPACE
MOV D,M ;; WE MOVE OUR CONTENT
MOV M,C ;; TO THE LEFT
MOV C,D
DCR A ;; A == HOW MANY LEFT ROTATIONS
;; I HAVE TO MAKE
INX H ;; INCREASE THE POSITION OF
;; THE 7SEGMENT THAT WE CHECK
JMP PRO
HIT:
INR B ;; INPUT ++
MOV M,C ;; FINALLY WE OUR ABLE ALLOCATE
JMP SHINE ;; DISPLAY
ROLLING:
MOV A,C
CPI 01H ;; 1-RIGHT
JZ RIGHT
CPI 02H ;; 2-LEFT
JZ LEFT
CPI 03H ;; 3-CENTER
JZ CENTER
JMP READ_IN ;; NO OTHER CHARS ARE ACCEPTABLE
RIGHT: ;; WE ROTATE ONE POSITION
;; RIGHT ALL OF OUR CONTENT
INR B ;; INCREASE THE NUMBER OF INPUT GIVEN
LXI H,0B00H
MOV E,M
LXI H,0B05H
MOV D,M
MOV M,E
LXI H,0B04H
MOV E,M
MOV M,D
LXI H,0B03H
MOV D,M
MOV M,E
LXI H,0B02H
MOV E,M
MOV M,D
LXI H,0B01H
MOV D,M
MOV M,E
LXI H,0B00H
MOV M,D
JMP SHINE
LEFT: ;; WE ROTATE ONE POSITION LEFT
;; ALL OF OUR CONTENT
INR B ;; INCREASE THE NUMBER OF INPUT GIVEN
LXI H,0B00H
MOV E,M
LXI H,0B01H
MOV D,M
MOV M,E
LXI H,0B02H
MOV E,M
MOV M,D
LXI H,0B03H
MOV D,M
MOV M,E
LXI H,0B04H
MOV E,M
MOV M,D
LXI H,0B05H
MOV D,M
MOV M,E
LXI H,0B00H
MOV M,D
JMP SHINE
CENTER: ;; WITH THIS FUNCTION WE FIND THE
;; LOCATION OF THE SECOND BLANK
MVI E,00H ;; 7-SEGMENT
LXI H,0B00H ;; START LOOKING FROM H
FIND:
MOV A,M
CPI 10H ;; WE FOUND ONE BLANK 7-SEGMENT
JZ WE_ARE_CLOSE ;; CHECK IT IS THE FIRST OR THE SECOND
INX H ;; INR MEMORY POINTER
INR E ;; INR TIMES THAT WE CHECKED
JMP FIND
WE_ARE_CLOSE:
INX H
MOV A,M
CPI 10H
JNZ GOTCHA ;; WE HIT A CHARACTER ON THE
;; LEFT SO WE FOUND WHAT WE WANTED
INR E
MOV A,E
CPI 05H ;; IF WE REACH THE 5TH POSITION
;; THEN WE ARE FINE
JZ GOTCHA
JMP WE_ARE_CLOSE
GOTCHA: ;; WE ROTATE RIGHT UNTIL THE SECOND BLANK
;;7-SEGMENT REACH FIRST POSITION
MOV A,E ;; eg (.) . _ _ _ _ -> . _ _ _ _(.)
CPI 00H
JZ SHINE
LXI H,0B00H
MOV E,M
LXI H,0B05H
MOV D,M
MOV M,E
LXI H,0B04H
MOV E,M
MOV M,D
LXI H,0B03H
MOV D,M
MOV M,E
LXI H,0B02H
MOV E,M
MOV M,D
LXI H,0B01H
MOV D,M
MOV M,E
LXI H,0B00H
MOV M,D
MOV E,A
DCR E
JMP GOTCHA
SHUTDOWN: ;; HAVE A CLEAR START
MVI A,00H
LXI B,0000H
LXI D,0B00H
LXI H,0B00H
MVI M,10H
INX H
MVI M,10H
INX H
MVI M,10H
INX H
MVI M,10H
INX H
MVI M,10H
INX H
MVI M,10H
RET
INITIALIZE: ;; FETCH-PC EFFECT OUR OUPTU SHOULD BE
LXI D,0B00H
LXI H,0B00H
MVI M,17H
INX H ;; . . _ _ _ _
MVI M,17H
INX H
MVI M,17H
INX H
MVI M,17H
INX H
MVI M,10H
INX H
MVI M,10H
MVI B,00H
RET
DISPLAY: ;; SHINE ON YOU
PUSH PSW
PUSH B ;; SAVE REGISTERS IN CASE STDM CHANGES THEM
PUSH H
PUSH D
CALL STDM
POP H
POP D
POP B
POP PSW
CALL DCD
RET
DOTS: ;; WITH THIS FUNCTION WE
;; FIND WHERE THE DOTS SHOULD BE
LXI H,0B00H ;; AND DISPLAY THEM
MVI D,80H
GO:
MOV A,M
CPI 10H ;; WE FOUND OUR FIRST DOT
JNZ FIRST ;; ALL WE NEEDED
MOV A,D ;; NOW WE CAN DEFINE THE SECOND DOT
RLC
MOV E,A
CPI 01H
JZ FIX
RLC
GO_1:
ORA E ;; A= THE LOCATION OF THE TWO 7SEGMENTS
STA 2800H
MVI A,7FH
STA 3800H ;; PRINT DOT
RET
FIX:
INX H
MOV A,M
CPI 10H
JZ FIX_2
MVI A,20H
JMP GO_1
FIX_2:
MVI A,02H
JMP GO_1
FIRST:
MOV A,D
RLC
INX H
MOV D,A
JMP GO
ROLL_ON: ;; WITH THIS FUNCTION WE CHECK
;; IF WE MUST ROLL INSIDE
;; THE CUSTOM KIND
MOV A,B
CPI 05H
JNC FIFTH ;; WE HAVE GIVEN 5 OR MORE
;; CHARACTERS SO WE
;; MUST CKECH IF ITS TIME TO ROTATE
RET
FIFTH:
MOV A,C
CPI 01H
JZ RIGHT1 ;; BINGO WE MUST ROTATE
;; RIGHT UNTIL ANOTHER
;; ACCEPTABLE CHARACTER IS GIVEN
CPI 02H
JZ LEFT1 ;; ^^ WE ROTATE LEFT
RET
RIGHT1: ;; ROTATE ONE POSITION RIGHT
PUSH B ;; SAVE REGISTER
LXI B,0040H ;; OUR DELB DURATION
CALL DELB
POP B
PUSH D ;; SAVE REGISTERS IN CASE
;; CUSTOM_KIND NEEDS THEM
PUSH H
LXI H,0B00H
MOV E,M
LXI H,0B05H
MOV D,M
MOV M,E
LXI H,0B04H
MOV E,M
MOV M,D
LXI H,0B03H
MOV D,M
MOV M,E
LXI H,0B02H
MOV E,M
MOV M,D
LXI H,0B01H
MOV D,M
MOV M,E
LXI H,0B00H
MOV M,D
POP H
LXI D,0B00H
CALL DISPLAY
POP D
RET
LEFT1: ;; ROTATE ONE POSITION LEFT
PUSH B ;; SAVE RESGISTER
LXI B,0040H ;; OUR DELB DURATION
CALL DELB
POP B
PUSH D ;; SAVE REGISTERS IN CASE
;; CUSTOM KIND NEEDS THEM
PUSH H
LXI H,0B00H
MOV E,M
LXI H,0B01H
MOV D,M
MOV M,E
LXI H,0B02H
MOV E,M
MOV M,D
LXI H,0B03H
MOV D,M
MOV M,E
LXI H,0B04H
MOV E,M
MOV M,D
LXI H,0B05H
MOV D,M
MOV M,E
LXI H,0B00H
MOV M,D
POP H
LXI D,0B00H
CALL DISPLAY
POP D
RET
CUSTOM_KIND:
PUSH D
PUSH H
CUSTOM_KIND1:
CALL DCD ;; UPDATE DISPLAY AND WAIT
CALL ROLL_ON
CALL DOTS ;; DISPLAY DOTS
CALL KPU ;; CHK FOR PUSHED KEY
JNZ CUSTOM_KIND1 ;; IF KEY STILL PUSHED
CUSTOM_KIND2:
CALL DCD ;; UPDATE DISP AND WAIT
CALL ROLL_ON
CALL DOTS ;; DISPLAY DOTS
CALL KPU ;; SHK FOR PUSHED KEY
JZ CUSTOM_KIND2 ;; IF KEY NOT PUSHED
TEAM:
LXI H,0BE8H ;; ADRS OF FIRST KEY ROW SCAN
MVI D,FFH ;; LOAD ROW COUNTER TO 0-1
CUSTOM_KIND3:
MOV A,M ;; GET ROW N KEY DATA
CPI F7H ;; IS IT THE HDWR STEP KEY?
JZ CUSTOM_KIND5 ;; YES JUMPS
CMA ;; INVERT KEY DATA
INR L ;; NEXT ROW
INR D ;; NEXT TABLE BLOCK
ANA A ;; TEST ROW N FOR 0
JZ CUSTOM_KIND3 ;; JUMP IF KEY NOT PUSHED
CPI 04H ;; SEE IF D3=1
JNZ CUSTOM_KIND4 ;; IF SO
DCR A ;; ELSE SET A=3
CUSTOM_KIND4:
ADD D ;; ADD 3X THE ROW N TO
ADD D ;; GET THE TABLE OFFSET
ADD D
MOV E,A ;; STORE TABLE INDEX
MVI D,00H ;; CLEAR MS BYTE OF DE
LXI H,01AFH ;; ADRS OF KEY CODE TABLE
DAD D ;; ADD INDEX TO TABLE ADRS
MOV A,M ;; PUT KEY CODE IN A
CALL REWIND
CUSTOM_KIND5:
POP H
POP D
RET
REWIND:
MOV A,B
CPI 05H ;; IF WE HAVE GIVEN MORE THAN 5 CHARS
JNC REWIND1 ;; THERE IS A SPECIAL CASE WE MUST
;; CHECK
MOV A,M
RET
REWIND1: ;; WITH THIS SUBROUTINE WE MAINTAIN OUR
;; INPUT SO WE CAN CONSTANTLY ROTATE
MOV A,M
CPI 85H ;; CHECK IF WE PRESSES FETCH PC
;; SO WE MUST INITIALIZE
JNZ OL
RET
OL:
CPI 00H
JZ REWIND2
CPI 04H
JNC REWIND2
RET
REWIND2:
MOV A,C ;; C == THE PREVIOUS ACCEPTABLE INPUT
RET
END
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x1c75, %rsi
lea addresses_normal_ht+0x6965, %rdi
clflush (%rsi)
clflush (%rdi)
sub $38840, %r9
mov $1, %rcx
rep movsw
xor %rcx, %rcx
lea addresses_normal_ht+0xea45, %r11
clflush (%r11)
nop
xor %rdx, %rdx
movw $0x6162, (%r11)
nop
nop
nop
xor %rsi, %rsi
lea addresses_UC_ht+0x1dc45, %r11
nop
nop
nop
sub %rsi, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm2
movups %xmm2, (%r11)
nop
nop
inc %rcx
lea addresses_A_ht+0x8e1d, %rsi
nop
nop
nop
nop
nop
xor $29041, %r14
mov (%rsi), %rdx
nop
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_A_ht+0x14815, %rcx
nop
add $25706, %r14
mov (%rcx), %esi
xor $30769, %rdi
lea addresses_WT_ht+0x14e45, %rdx
nop
nop
nop
nop
nop
xor $53687, %rcx
movb (%rdx), %r9b
nop
nop
nop
dec %rdx
lea addresses_A_ht+0x1f35, %rsi
lea addresses_WC_ht+0x2739, %rdi
nop
nop
nop
add %r13, %r13
mov $2, %rcx
rep movsw
sub $37862, %rdx
lea addresses_normal_ht+0x17c45, %r14
nop
nop
nop
nop
nop
xor %rdi, %rdi
mov $0x6162636465666768, %r13
movq %r13, %xmm7
vmovups %ymm7, (%r14)
nop
and %r9, %r9
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r8
push %r9
push %rax
push %rsi
// Store
lea addresses_A+0xf83d, %r8
and $14222, %r9
movl $0x51525354, (%r8)
nop
nop
nop
cmp $54692, %r13
// Store
lea addresses_PSE+0x15e82, %r12
nop
nop
and $17434, %r11
mov $0x5152535455565758, %rsi
movq %rsi, (%r12)
dec %r12
// Store
lea addresses_normal+0x6a45, %r11
nop
nop
nop
nop
nop
and %r9, %r9
mov $0x5152535455565758, %r13
movq %r13, (%r11)
nop
nop
sub %r9, %r9
// Load
lea addresses_D+0xb245, %r13
nop
nop
nop
nop
nop
and $23692, %r8
mov (%r13), %ax
nop
nop
nop
nop
nop
add $23786, %r11
// Load
mov $0x245, %r12
nop
nop
and $1207, %r13
movb (%r12), %r9b
nop
nop
nop
nop
xor %r12, %r12
// Store
lea addresses_US+0x14ed5, %r9
nop
sub $31942, %r11
movw $0x5152, (%r9)
add $13699, %r13
// Faulty Load
lea addresses_US+0xa245, %r13
clflush (%r13)
nop
nop
nop
nop
add %r12, %r12
mov (%r13), %rsi
lea oracles, %r13
and $0xff, %rsi
shlq $12, %rsi
mov (%r13,%rsi,1), %rsi
pop %rsi
pop %rax
pop %r9
pop %r8
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_US', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A', 'AVXalign': True, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}}
{'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_D', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_P', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_US', 'AVXalign': False, 'size': 2}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_US', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}}
{'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 32}}
{'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
*/
|
#ifndef GODOT_CPP_RECTANGLESHAPE2D_HPP
#define GODOT_CPP_RECTANGLESHAPE2D_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Shape2D.hpp"
namespace godot {
class RectangleShape2D : public Shape2D {
struct ___method_bindings {
godot_method_bind *mb_get_extents;
godot_method_bind *mb_set_extents;
};
static ___method_bindings ___mb;
static void *_detail_class_tag;
public:
static void ___init_method_bindings();
inline static size_t ___get_id() { return (size_t)_detail_class_tag; }
static inline const char *___get_class_name() { return (const char *) "RectangleShape2D"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
// constants
static RectangleShape2D *_new();
// methods
Vector2 get_extents() const;
void set_extents(const Vector2 extents);
};
}
#endif |
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <fstream>
#include <sys/types.h>
#include <dirent.h>
#include <dvs_msgs/Event.h>
#include <dvs_msgs/EventArray.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/Imu.h>
#include <unordered_map>
#define foreach BOOST_FOREACH
bool parse_arguments(int argc, char* argv[],
std::string* path_to_input_rosbag)
{
if(argc < 2)
{
std::cerr << "Not enough arguments" << std::endl;
std::cerr << "Usage: rosrun dvs_rosbag_stats dvs_rosbag_stats path_to_bag.bag";
return false;
}
*path_to_input_rosbag = std::string(argv[1]);
return true;
}
bool compute_stats(const std::string path_to_input_rosbag,
int& num_events,
int& num_frames,
double& duration)
{
std::cout << "Processing: " << path_to_input_rosbag << std::endl;
auto const pos = path_to_input_rosbag.find_last_of('/');
const std::string output_dir = path_to_input_rosbag.substr(0, pos + 1) + "stats/";
const std::string output_filename = path_to_input_rosbag.substr(
pos + 1, path_to_input_rosbag.length() - (pos + 1) - 4) + ".txt";
const std::string path_to_output = output_dir + output_filename;
boost::filesystem::create_directories(output_dir);
rosbag::Bag input_bag;
try
{
input_bag.open(path_to_input_rosbag, rosbag::bagmode::Read);
}
catch(rosbag::BagIOException e)
{
std::cerr << "Error: could not open rosbag: " << path_to_input_rosbag << std::endl;
return false;
}
rosbag::View view(input_bag);
std::unordered_map<std::string, std::vector<dvs_msgs::Event>> event_packets_for_each_event_topic;
const uint32_t num_messages = view.size();
uint32_t message_index = 0;
int num_events_tmp = 0;
int num_frames_tmp = 0;
double start_time;
double end_time = 0;
bool first_msg = true;
foreach(rosbag::MessageInstance const m, view)
{
if (m.getDataType() == "dvs_msgs/EventArray")
{
std::vector<dvs_msgs::Event>& events = event_packets_for_each_event_topic[m.getTopic()];
dvs_msgs::EventArrayConstPtr s = m.instantiate<dvs_msgs::EventArray>();
num_events_tmp += s->events.size();
if (first_msg)
{
start_time = s->events.front().ts.toSec();
first_msg = false;
}
end_time = std::max(s->events.back().ts.toSec(), end_time);
}
else if (m.getDataType() == "sensor_msgs/Image")
{
num_frames_tmp += 1;
}
}
input_bag.close();
num_events = num_events_tmp;
num_frames = num_frames_tmp;
duration = end_time - start_time;
return true;
}
bool write_stats(const std::string path_to_output,
const int& num_events,
const int& num_frames,
const double& duration)
{
std::ofstream stats_file;
stats_file.open(path_to_output);
// stats_file << "Number of events: " << num_events << '\n';
// stats_file << "Number of frames: " << num_frames << '\n';
// stats_file << "Total duration (s): " << duration << '\n';
stats_file << num_events << ", " << num_frames << ", " << duration << std::endl;
stats_file.close();
return true;
}
bool hasEnding (std::string const &fullString, std::string const &ending) {
if (fullString.length() >= ending.length()) {
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
} else {
return false;
}
}
int main(int argc, char* argv[])
{
std::string path_to_input_rosbag;
int max_num_events_per_packet;
ros::Duration max_duration_event_packet;
if (!parse_arguments(argc, argv, &path_to_input_rosbag))
{
return -1;
}
int num_events;
int num_frames;
double duration;
if (!compute_stats(path_to_input_rosbag,
num_events,
num_frames,
duration))
{
return -1;
}
auto const pos = path_to_input_rosbag.find_last_of('/');
const std::string output_dir = path_to_input_rosbag.substr(0, pos + 1) + "stats/";
const std::string output_filename = path_to_input_rosbag.substr(
pos + 1, path_to_input_rosbag.length() - (pos + 1) - 4) + ".txt";
const std::string path_to_output = output_dir + output_filename;
boost::filesystem::create_directories(output_dir);
write_stats(path_to_output,
num_events,
num_frames,
duration);
return 0;
}
|
/*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#include <iostream>
#include <limits>
#include "galois/Galois.h"
#include "galois/gstl.h"
#include "Lonestar/BoilerPlate.h"
#include "galois/runtime/CompilerHelperFunctions.h"
#include "galois/runtime/dGraph_edgeCut.h"
#include "galois/runtime/dGraph_vertexCut.h"
#include "galois/DReducible.h"
#include "galois/runtime/Tracer.h"
#ifdef __GALOIS_HET_CUDA__
#include "galois/cuda/cuda_device.h"
#include "gen_cuda.h"
struct CUDA_Context* cuda_ctx;
enum Personality { CPU, GPU_CUDA, GPU_OPENCL };
std::string personality_str(Personality p) {
switch (p) {
case CPU:
return "CPU";
case GPU_CUDA:
return "GPU_CUDA";
case GPU_OPENCL:
return "GPU_OPENCL";
}
assert(false && "Invalid personality");
return "";
}
#endif
static const char* const name =
"BFS - Distributed Heterogeneous with worklist.";
static const char* const desc = "BFS on Distributed Galois.";
static const char* const url = 0;
namespace cll = llvm::cl;
static cll::opt<std::string>
inputFile(cll::Positional, cll::desc("<input file>"), cll::Required);
static cll::opt<std::string> partFolder("partFolder",
cll::desc("path to partitionFolder"),
cll::init(""));
static cll::opt<unsigned int>
maxIterations("maxIterations",
cll::desc("Maximum iterations: Default 10000"),
cll::init(10000));
static cll::opt<unsigned int>
src_node("startNode", cll::desc("ID of the source node"), cll::init(0));
static cll::opt<bool>
verify("verify",
cll::desc("Verify ranks by printing to 'page_ranks.#hid.csv' file"),
cll::init(false));
static cll::opt<bool>
enableVCut("enableVertexCut",
cll::desc("Use vertex cut for graph partitioning."),
cll::init(false));
#ifdef __GALOIS_HET_CUDA__
static cll::opt<int> gpudevice(
"gpu",
cll::desc("Select GPU to run on, default is to choose automatically"),
cll::init(-1));
static cll::opt<Personality>
personality("personality", cll::desc("Personality"),
cll::values(clEnumValN(CPU, "cpu", "Galois CPU"),
clEnumValN(GPU_CUDA, "gpu/cuda", "GPU/CUDA"),
clEnumValN(GPU_OPENCL, "gpu/opencl", "GPU/OpenCL"),
clEnumValEnd),
cll::init(CPU));
static cll::opt<std::string>
personality_set("pset",
cll::desc("String specifying personality for each host. "
"'c'=CPU,'g'=GPU/CUDA and 'o'=GPU/OpenCL"),
cll::init(""));
static cll::opt<unsigned>
scalegpu("scalegpu",
cll::desc("Scale GPU workload w.r.t. CPU, default is "
"proportionally equal workload to CPU and GPU (1)"),
cll::init(1));
static cll::opt<unsigned>
scalecpu("scalecpu",
cll::desc("Scale CPU workload w.r.t. GPU, default is "
"proportionally equal workload to CPU and GPU (1)"),
cll::init(1));
static cll::opt<int> num_nodes(
"num_nodes",
cll::desc("Num of physical nodes with devices (default = num of hosts): "
"detect GPU to use for each host automatically"),
cll::init(-1));
#endif
const unsigned int infinity = std::numeric_limits<unsigned int>::max() / 4;
struct NodeData {
std::atomic<unsigned int> dist_current;
unsigned int dist_old;
};
typedef galois::graphs::DistGraph<NodeData, void> Graph;
typedef galois::graphs::DistGraphEdgeCut<NodeData, void> Graph_edgeCut;
typedef galois::graphs::DistGraphHybridCut<NodeData, void> Graph_vertexCut;
typedef typename Graph::GraphNode GNode;
struct InitializeGraph {
Graph* graph;
InitializeGraph(Graph* _graph) : graph(_graph) {}
void static go(Graph& _graph) {
galois::do_all(_graph.begin(), _graph.end(), InitializeGraph{&_graph},
galois::loopname("InitializeGraph"),
galois::numrun(_graph.get_run_identifier()));
}
void operator()(GNode src) const {
NodeData& sdata = graph->getData(src);
sdata.dist_current = (graph->getGID(src) == src_node) ? 0 : infinity;
sdata.dist_old = (graph->getGID(src) == src_node) ? 0 : infinity;
}
};
struct BFS {
Graph* graph;
BFS(Graph* _graph) : graph(_graph) {}
void static go(Graph& _graph) {
using namespace galois::worklists;
typedef PerSocketChunkFIFO<64> PSchunk;
galois::for_each(src_node, BFS(&_graph), galois::loopname("BFS"));
}
void operator()(GNode src, galois::UserContext<GNode>& ctx) const {
NodeData& snode = graph->getData(src);
snode.dist_old = snode.dist_current;
for (auto jj = graph->edge_begin(src), ee = graph->edge_end(src); jj != ee;
++jj) {
GNode dst = graph->getEdgeDst(jj);
auto& dnode = graph->getData(dst);
unsigned int new_dist = 1 + snode.dist_current;
galois::atomicMin(dnode.dist_current, new_dist);
if (dnode.dist_old > dnode.dist_current) {
ctx.push(graph->getGID(dst));
}
}
}
};
int main(int argc, char** argv) {
try {
LonestarStart(argc, argv, name, desc, url);
galois::runtime::reportStat("(NULL)", "Max Iterations",
(unsigned long)maxIterations, 0);
galois::runtime::reportStat("(NULL)", "Source Node ID",
(unsigned long)src_node, 0);
galois::StatManager statManager;
auto& net = galois::runtime::getSystemNetworkInterface();
galois::StatTimer StatTimer_init("TIMER_GRAPH_INIT"),
StatTimer_total("TimerTotal"), StatTimer_hg_init("TIMER_HG_INIT");
StatTimer_total.start();
std::vector<unsigned> scalefactor;
#ifdef __GALOIS_HET_CUDA__
const unsigned my_host_id = galois::runtime::getHostID();
int gpu_device = gpudevice;
// Parse arg string when running on multiple hosts and update/override
// personality with corresponding value.
if (personality_set.length() == galois::runtime::NetworkInterface::Num) {
switch (personality_set.c_str()[my_host_id]) {
case 'g':
personality = GPU_CUDA;
break;
case 'o':
assert(0);
personality = GPU_OPENCL;
break;
case 'c':
default:
personality = CPU;
break;
}
if ((personality == GPU_CUDA) && (gpu_device == -1)) {
gpu_device = get_gpu_device_id(personality_set, num_nodes);
}
for (unsigned i = 0; i < personality_set.length(); ++i) {
if (personality_set.c_str()[i] == 'c')
scalefactor.push_back(scalecpu);
else
scalefactor.push_back(scalegpu);
}
}
#endif
StatTimer_hg_init.start();
Graph* hg;
if (enableVCut) {
hg = new Graph_vertexCut(inputFile, partFolder, net.ID, net.Num,
scalefactor);
} else {
hg = new Graph_edgeCut(inputFile, partFolder, net.ID, net.Num,
scalefactor);
}
#ifdef __GALOIS_HET_CUDA__
if (personality == GPU_CUDA) {
cuda_ctx = get_CUDA_context(my_host_id);
if (!init_CUDA_context(cuda_ctx, gpu_device))
return -1;
MarshalGraph m = (*hg).getMarshalGraph(my_host_id);
load_graph_CUDA(cuda_ctx, m, net.Num);
} else if (personality == GPU_OPENCL) {
// galois::opencl::cl_env.init(cldevice.Value);
}
#endif
StatTimer_hg_init.stop();
std::cout << "[" << net.ID << "] InitializeGraph::go called\n";
StatTimer_init.start();
InitializeGraph::go((*hg));
StatTimer_init.stop();
for (auto run = 0; run < numRuns; ++run) {
std::cout << "[" << net.ID << "] BFS::go run " << run << " called\n";
std::string timer_str("Timer_" + std::to_string(run));
galois::StatTimer StatTimer_main(timer_str.c_str());
StatTimer_main.start();
BFS::go((*hg));
StatTimer_main.stop();
if ((run + 1) != numRuns) {
galois::runtime::getHostBarrier().wait();
(*hg).reset_num_iter(run + 1);
InitializeGraph::go((*hg));
}
}
StatTimer_total.stop();
// Verify
if (verify) {
#ifdef __GALOIS_HET_CUDA__
if (personality == CPU) {
#endif
for (auto ii = (*hg).begin(); ii != (*hg).end(); ++ii) {
if ((*hg).isOwned((*hg).getGID(*ii)))
galois::runtime::printOutput("% %\n", (*hg).getGID(*ii),
(*hg).getData(*ii).dist_current);
}
#ifdef __GALOIS_HET_CUDA__
} else if (personality == GPU_CUDA) {
for (auto ii = (*hg).begin(); ii != (*hg).end(); ++ii) {
if ((*hg).isOwned((*hg).getGID(*ii)))
galois::runtime::printOutput(
"% %\n", (*hg).getGID(*ii),
get_node_dist_current_cuda(cuda_ctx, *ii));
}
}
#endif
}
return 0;
} catch (const char* c) {
std::cerr << "Error: " << c << "\n";
return 1;
}
}
|
page ,160
;
;----------------------------------------------------------------------------
;
; Modification history
;
; 26-Feb-1991 sudeepb Ported for NT DOSEm
;----------------------------------------------------------------------------
include version.inc ; set build flags
include biosseg.inc ; establish bios segment structure
sysinitseg segment
public badopm,crlfm,badsiz_pre,badld_pre,badcom,badcountry
public badmem,badblock,badstack
public insufmemory,badcountrycom
public badorder,errorcmd
public badparm
public toomanydrivesmsg ;M029
include msbio.cl3
sysinitseg ends
end
|
; A086851: a(0) = 1, a(n+1) = a(n)^2 - n.
; 1,1,0,-2,1,-3,4,10,93,8641,74666872,5575141774264374,31082205803147712138788845611865,966103517589229313003894215813508352493573272034098666228778213,933356006698282312572303256489816012122783406254583141248499016192865214116760703502264792586180597344027491798667186743473356
mov $2,1
lpb $0
sub $0,1
pow $2,2
add $2,$3
sub $3,1
lpe
mov $0,$2
|
; DRAW XOR SPRITE 2 BYTE DEFINITION ROTATED, ON LEFT BORDER
; 01.2006 aralbrec, Sprite Pack v3.0
; sinclair spectrum version
XLIB SP1_DRAW_XOR2LB
LIB SP1_DRAW_XOR2NR
XREF SP1RETSPRDRAW, SP1V_ROTTBL, SP1V_PIXELBUFFER
; following data segment copied into struct sp1_cs
ld hl,0
nop
ld de,0
call SP1_DRAW_XOR2LB
; following draw code called by way of SP1UpdateNow
;
; a = hor rot table
; bc = graphic disp
; hl = graphic def ptr
; de = left graphic def ptr
;
; 32 + 106*4 - 6 + 10 = 460 cycles
.SP1_DRAW_XOR2LB
cp SP1V_ROTTBL/256
jp z, SP1_DRAW_XOR2NR
add hl,bc
ld d,a
; d = shift table
; hl = sprite def (mask,graph) pairs
.SP1Xor2LBRotate
; 0
ld bc,(SP1V_PIXELBUFFER+0)
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor c
ld (SP1V_PIXELBUFFER+0),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor b
ld (SP1V_PIXELBUFFER+1),a
; 1
ld bc,(SP1V_PIXELBUFFER+2)
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor c
ld (SP1V_PIXELBUFFER+2),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor b
ld (SP1V_PIXELBUFFER+3),a
; 2
ld bc,(SP1V_PIXELBUFFER+4)
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor c
ld (SP1V_PIXELBUFFER+4),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor b
ld (SP1V_PIXELBUFFER+5),a
; 3
ld bc,(SP1V_PIXELBUFFER+6)
inc hl
ld e,(hl)
inc hl
ld a,(de)
xor c
ld (SP1V_PIXELBUFFER+6),a
inc hl
ld e,(hl)
ld a,(de)
xor b
ld (SP1V_PIXELBUFFER+7),a
jp SP1RETSPRDRAW
|
; A045321: Primes congruent to {1, 2, 3} mod 5.
; Submitted by Christian Krause
; 2,3,7,11,13,17,23,31,37,41,43,47,53,61,67,71,73,83,97,101,103,107,113,127,131,137,151,157,163,167,173,181,191,193,197,211,223,227,233,241,251,257,263,271,277,281,283,293,307,311,313,317,331,337,347,353,367,373,383,397,401,421,431,433,443,457,461,463,467,487,491,503,521,523,541,547,557,563,571,577,587,593,601,607,613,617,631,641,643,647,653,661,673,677,683,691,701,727,733,743
mov $2,332202
lpb $2
mov $3,$6
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,10
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,18
sub $5,2
add $5,$1
div $5,8
mov $6,$5
sub $5,1
lpe
mov $0,$5
add $0,2
|
; A100057: Sum of absolute differences of p(n) defined in A054065, oriented around a clock.
; 2,4,8,12,18,24,30,40,50,60,70,80,96,112,128,144,160,176,192,208,234,260,286,312,338,364,390,416,442,468,494,520,546,588,630,672,714,756,798,840,882,924,966,1008,1050,1092,1134,1176,1218,1260,1302,1344,1386
mov $14,$0
mov $16,$0
add $16,1
lpb $16
clr $0,14
mov $0,$14
sub $16,1
sub $0,$16
mov $11,$0
mov $13,$0
add $13,1
lpb $13
mov $0,$11
sub $13,1
sub $0,$13
mov $7,$0
mov $9,2
lpb $9
sub $9,1
add $0,$9
sub $0,1
mov $1,1
mov $2,$0
add $4,$0
lpb $2
lpb $4
mov $3,$6
mov $5,1
mov $6,$1
add $1,$3
trn $4,$1
lpe
lpb $5
trn $5,$1
mov $6,0
lpe
sub $2,1
lpe
mov $10,$9
lpb $10
mov $8,$1
sub $10,1
lpe
lpe
lpb $7
mov $7,0
sub $8,$1
lpe
mov $1,$8
mul $1,2
add $12,$1
lpe
add $15,$12
lpe
mov $1,$15
|
; A084943: Decagorials: n-th polygorial for k=10.
; Submitted by Jamie Morken(s1)
; 1,1,10,270,14040,1193400,150368400,26314470000,6104957040000,1813172240880000,670873729125600000,302564051835645600000,163384587991248624000000,104075982550425373488000000
mov $1,1
mov $2,1
lpb $0
mul $1,$0
sub $0,1
mul $1,$2
add $2,4
lpe
mov $0,$1
|
// Copyright (c) 2018-2021 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "extversionmessage.h"
#include "hashwrapper.h"
#include "random.h"
#include "streams.h"
#include "util.h"
uint64_t CExtversionMessage::as_u64c(const uint64_t k) const
{
LOCK(cacheProtector);
const auto xmap_iter = xmap.find(k);
if (xmap_iter == xmap.end())
{
// we dont have that key, assuming zero
return 0;
}
const auto cache_iter = cache_u64c.find(k);
if (cache_iter == cache_u64c.end())
{
uint64_t v = 0;
const std::vector<uint8_t> &vec = xmap_iter->second;
try
{
CDataStream s(vec, SER_NETWORK, PROTOCOL_VERSION);
v = ReadCompactSizeWithLimit(s, std::numeric_limits<uint64_t>::max());
}
catch (...)
{
LOG(NET, "Error reading extended configuration key %016llx as u64c. Assuming zero.\n", k);
v = 0;
}
cache_u64c[k] = v;
return v;
}
return cache_iter->second;
}
void CExtversionMessage::set_u64c(const uint64_t key, const uint64_t val)
{
CDataStream s(SER_NETWORK, PROTOCOL_VERSION);
WriteCompactSize(s, val);
std::vector<uint8_t> vec;
vec.insert(vec.begin(), s.begin(), s.end());
LOCK(cacheProtector);
xmap[key] = std::move(vec);
cache_u64c[key] = val;
}
|
/// gravity tutorial
#include "tutorialpartroll.h"
#include "logger.h"
//#include "rollthrustshipcontroller.h"
#include "PlayerControlledShipControllers.h"
CTutorialpartRoll::CTutorialpartRoll(CShip* aShip):CTutorialpartBox(aShip) {
mShipController=new CRollThrustShipController( mShip );
}
CTutorialpartRoll::~CTutorialpartRoll() {
// delete( mShipController );
}
void CTutorialpartRoll::init() {
LOG("\nTutorial Part Roll init");
mTutDataMax=4;
mTutData[0].x=2;
mTutData[0].y=2;
mTutData[0].z=0;
mTutData[1].x=4;
mTutData[1].y=5;
mTutData[1].z=0;
mTutData[2].x=2;
mTutData[2].y=-3;
mTutData[2].z=0;
mTutData[3].x=-1;
mTutData[3].y=-4;
mTutData[3].z=0;
mTutData[4].x=-3;
mTutData[4].y=-4;
mTutData[4].z=0;
mTutNum=0;
CTutorialpartBox::init();
mMessage.push_back("Roll tutorial");
// mMessage.push_back(" ");
mMessage.push_back("* Roll orientation enabled ");
mMessage.push_back("* Yaw & Pitch orientation disabled");
mMessage.push_back("* Thrust enabled");
mMessage.push_back(" ");
mMessage.push_back("Goal : Stabilize in each cube for 1 second");
mMessage.push_back("Use : the left mouse button to thrust, mouse left/right");
// mMessage.push_back(" ");
// mMessage.push_back(" *** Press space to continue ***");
}
bool CTutorialpartRoll::getYawEnabled() {
return(false);
}
bool CTutorialpartRoll::getPitchEnabled() {
return(false);
}
bool CTutorialpartRoll::getRollEnabled() {
return(true);
}
bool CTutorialpartRoll::getThrustEnabled() {
return(true);
}
std::vector<std::string> CTutorialpartRoll::getMessage() {
return(mMessage);
}
|
// Test that address vars are turned into load/store and located at hardcoded addresses
// Hard-coded mainmem-page address - global variable
// Commodore 64 PRG executable file
.file [name="address-2.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(__start)
.label SCREEN = $400
.label i = $2000
.segment Code
__start: {
// char __address(0x2000) i = 3
lda #3
sta i
jsr main
rts
}
main: {
__b1:
// while(i<7)
lda i
cmp #7
bcc __b2
// }
rts
__b2:
// SCREEN[i++] = i
ldy i
tya
sta SCREEN,y
// SCREEN[i++] = i;
inc i
jmp __b1
}
|
SECTION code_clib
PUBLIC asm_set_palette
PUBLIC asm_get_palette
; Set the palette bitsets
;
; Entry: l = blue bitset
; h = red bitset
; e = green bitset
asm_set_palette:
ld bc,$1000
out (c),l ;Blue
inc b
out (c),h ;Red
inc b
out (c),e ;Green
ld (__x1_default_palette),hl
ld a,e
ld (__x1_default_palette+2),a
ret
asm_get_palette:
ld hl,(__x1_default_palette)
ld a,(__x1_default_palette+2)
ld e,a
ret
SECTION data_clib
__x1_default_palette:
defb $aa, $cc, $f0
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "coincontrol.h"
#include "kernel.h"
#include "masternode-budget.h"
#include "net.h"
#include "script/script.h"
#include "script/sign.h"
#include "spork.h"
#include "swifttx.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
using namespace std;
/**
* Settings
*/
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
unsigned int nTxConfirmTarget = 1;
bool bSpendZeroConfChange = true;
bool fSendFreeTransactions = false;
bool fPayAtLeastCustomFee = true;
/**
* Fees smaller than this (in duffs) are considered zero fee (for transaction creation)
* We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher
* so it's still 10 times lower comparing to bitcoin.
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(10000);
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly {
bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
{
return t1.first < t2.first;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
}
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return NULL;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey()
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey secret;
secret.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
// Create new metadata
int64_t nCreationTime = GetTime();
mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
nTimeFirstKey = nCreationTime;
if (!AddKeyPubKey(secret, pubkey))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return pubkey;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
return false;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script))
RemoveWatchOnly(script);
if (!fFileBacked)
return true;
if (!IsCrypted()) {
return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddCryptedKey(const CPubKey& vchPubKey,
const vector<unsigned char>& vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
if (!fFileBacked)
return true;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
}
return false;
}
bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
nTimeFirstKey = meta.nCreateTime;
mapKeyMetadata[pubkey.GetID()] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) {
std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript& dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
nTimeFirstKey = 1; // No birthday information for watch-only keys.
NotifyWatchonlyChanged(true);
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript& dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (fFileBacked)
if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript& dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly)
{
SecureString strWalletPassphraseFinal;
if (!IsLocked()) {
fWalletUnlockAnonymizeOnly = anonymizeOnly;
return true;
}
strWalletPassphraseFinal = strWalletPassphrase;
CCrypter crypter;
CKeyingMaterial vMasterKey;
{
LOCK(cs_wallet);
BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) {
if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(vMasterKey)) {
fWalletUnlockAnonymizeOnly = anonymizeOnly;
return true;
}
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase;
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial vMasterKey;
BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) {
if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(vMasterKey)) {
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
if (fFileBacked) {
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
BOOST_FOREACH (const CTxIn& txin, wtx.vin) {
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
result.insert(it->second);
}
return result;
}
void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = NULL;
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos) {
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it) {
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
return true; // Spent
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(make_pair(outpoint, wtxid));
pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
assert(mapWallet.count(wtxid));
CWalletTx& thisTx = mapWallet[wtxid];
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
BOOST_FOREACH (const CTxIn& txin, thisTx.vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
// Find possible candidates
std::vector<COutput> vPossibleCoins;
AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000);
if (vPossibleCoins.empty()) {
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n");
return false;
}
if (strTxHash.empty()) // No output specified, select the first one
return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet);
// Find specific vin
uint256 txHash = uint256S(strTxHash);
int nOutputIndex;
try {
nOutputIndex = std::stoi(strOutputIndex.c_str());
} catch (const std::exception& e) {
LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what());
return false;
}
BOOST_FOREACH (COutput& out, vPossibleCoins)
if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it!
return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet);
LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n");
return false;
}
bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
CScript pubScript;
txinRet = CTxIn(out.tx->GetHash(), out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcoinAddress address2(address1);
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n");
return false;
}
if (!GetKey(keyID, keyRet)) {
LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n");
return false;
}
pubKeyRet = keyRet.GetPubKey();
return true;
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial vMasterKey;
RandAddSeedPerfmon();
vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
RandAddSeedPerfmon();
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
if (fFileBacked) {
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(strWalletFile);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
}
if (!EncryptKeys(vMasterKey)) {
if (fFileBacked) {
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
}
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload their unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (fFileBacked) {
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload their unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = NULL;
}
Lock();
Unlock(strWalletPassphrase);
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
CDB::Rewrite(strWalletFile);
}
NotifyStatusChanged(this);
return true;
}
int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
{
AssertLockHeld(cs_wallet); // mapWallet
CWalletDB walletdb(strWalletFile);
// First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
TxItems txOrdered;
// Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
// would make this much faster for applications that do this a lot.
for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
CWalletTx* wtx = &((*it).second);
txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
}
acentries.clear();
walletdb.ListAccountCreditDebit(strAccount, acentries);
BOOST_FOREACH (CAccountingEntry& entry, acentries) {
txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
}
return txOrdered;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
{
uint256 hash = wtxIn.GetHash();
if (fFromLoadWallet) {
mapWallet[hash] = wtxIn;
mapWallet[hash].BindWallet(this);
AddToSpends(hash);
} else {
LOCK(cs_wallet);
// Inserts only if not already there, returns tx inserted or tx found
pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew) {
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext();
wtx.nTimeSmart = wtx.nTimeReceived;
if (wtxIn.hashBlock != 0) {
if (mapBlockIndex.count(wtxIn.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
{
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
std::list<CAccountingEntry> acentries;
TxItems txOrdered = OrderedTxItems(acentries);
for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
if (pwtx == &wtx)
continue;
CAccountingEntry* const pacentry = (*it).second.second;
int64_t nSmartTime;
if (pwtx) {
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime)
nSmartTime = pwtx->nTimeReceived;
} else
nSmartTime = pacentry->nTime;
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow)
latestNow = nSmartTime;
break;
}
}
}
int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else
LogPrintf("AddToWallet() : found %s in block %s not in index\n",
wtxIn.GetHash().ToString(),
wtxIn.hashBlock.ToString());
}
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew) {
// Merge
if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) {
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) {
wtx.vMerkleBranch = wtxIn.vMerkleBranch;
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) {
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!wtx.WriteToDisk())
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = GetArg("-walletnotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it.
* pblock is optional, but should be provided if the transaction is known to be in a block.
* If fUpdate is true, existing transactions will be updated.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
{
AssertLockHeld(cs_wallet);
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx)) {
CWalletTx wtx(this, tx);
// Get merkle branch if transaction was found in a block
if (pblock)
wtx.SetMerkleBranch(*pblock);
return AddToWallet(wtx);
}
}
return false;
}
void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
{
LOCK2(cs_main, cs_wallet);
if (!AddToWalletIfInvolvingMe(tx, pblock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
if (mapWallet.count(txin.prevout.hash))
mapWallet[txin.prevout.hash].MarkDirty();
}
}
void CWallet::EraseFromWallet(const uint256& hash)
{
if (!fFileBacked)
return;
{
LOCK(cs_wallet);
if (mapWallet.erase(hash))
CWalletDB(strWalletFile).EraseTx(hash);
}
return;
}
isminetype CWallet::IsMine(const CTxIn& txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
return IsMine(prev.vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size())
if (IsMine(prev.vout[txin.prevout.n]) & filter)
return prev.vout[txin.prevout.n].nValue;
}
}
return 0;
}
// Recursively determine the rounds of a given input (How deep is the Obfuscation chain for a given input)
int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const
{
static std::map<uint256, CMutableTransaction> mDenomWtxes;
if (rounds >= 16) return 15; // 16 rounds max
uint256 hash = in.prevout.hash;
unsigned int nout = in.prevout.n;
const CWalletTx* wtx = GetWalletTx(hash);
if (wtx != NULL) {
std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash);
// not known yet, let's add it
if (mdwi == mDenomWtxes.end()) {
LogPrint("obfuscation", "GetInputObfuscationRounds INSERTING %s\n", hash.ToString());
mDenomWtxes[hash] = CMutableTransaction(*wtx);
}
// found and it's not an initial value, just return it
else if (mDenomWtxes[hash].vout[nout].nRounds != -10) {
return mDenomWtxes[hash].vout[nout].nRounds;
}
// bounds check
if (nout >= wtx->vout.size()) {
// should never actually hit this
LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4);
return -4;
}
if (pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) {
mDenomWtxes[hash].vout[nout].nRounds = -3;
LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
//make sure the final output is non-denominate
if (/*rounds == 0 && */ !IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM
{
mDenomWtxes[hash].vout[nout].nRounds = -2;
LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
bool fAllDenoms = true;
BOOST_FOREACH (CTxOut out, wtx->vout) {
fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue);
}
// this one is denominated but there is another non-denominated output found in the same tx
if (!fAllDenoms) {
mDenomWtxes[hash].vout[nout].nRounds = 0;
LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
int nShortest = -10; // an initial value, should be no way to get this by calculations
bool fDenomFound = false;
// only denoms here so let's look up
BOOST_FOREACH (CTxIn in2, wtx->vin) {
if (IsMine(in2)) {
int n = GetRealInputObfuscationRounds(in2, rounds + 1);
// denom found, find the shortest chain or initially assign nShortest with the first found value
if (n >= 0 && (n < nShortest || nShortest == -10)) {
nShortest = n;
fDenomFound = true;
}
}
}
mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed
:
0; // too bad, we are the fist one in that chain
LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds);
return mDenomWtxes[hash].vout[nout].nRounds;
}
return rounds - 1;
}
// respect current settings
int CWallet::GetInputObfuscationRounds(CTxIn in) const
{
LOCK(cs_wallet);
int realObfuscationRounds = GetRealInputObfuscationRounds(in, 0);
return realObfuscationRounds > nObfuscationRounds ? nObfuscationRounds : realObfuscationRounds;
}
bool CWallet::IsDenominated(const CTxIn& txin) const
{
{
LOCK(cs_wallet);
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end()) {
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue);
}
}
return false;
}
bool CWallet::IsDenominated(const CTransaction& tx) const
{
/*
Return false if ANY inputs are non-denom
*/
bool ret = true;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
if (!IsDenominated(txin)) {
ret = false;
}
}
return ret;
}
bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const
{
BOOST_FOREACH (CAmount d, obfuScationDenominations)
if (nInputAmount == d)
return true;
return false;
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey)) {
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase()) {
// Generated block
if (hashBlock != 0) {
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
} else {
// Did anyone request this transaction?
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end()) {
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && hashBlock != 0) {
map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
list<COutputEntry>& listSent,
CAmount& nFee,
string& strSentAccount,
const isminefilter& filter) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < vout.size(); ++i) {
const CTxOut& txout = vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0) {
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
} else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address)) {
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
COutputEntry output = {address, txout.nValue, (int)i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
}
void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
{
nReceived = nSent = nFee = 0;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (strAccount == strSentAccount) {
BOOST_FOREACH (const COutputEntry& s, listSent)
nSent += s.amount;
nFee = allFee;
}
{
LOCK(pwallet->cs_wallet);
BOOST_FOREACH (const COutputEntry& r, listReceived) {
if (pwallet->mapAddressBook.count(r.destination)) {
map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
nReceived += r.amount;
} else if (strAccount.empty()) {
nReceived += r.amount;
}
}
}
}
bool CWalletTx::WriteToDisk()
{
return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*/
int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
{
int ret = 0;
int64_t nNow = GetTime();
CBlockIndex* pindex = pindexStart;
{
LOCK2(cs_main, cs_wallet);
// no need to read and scan block, if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
pindex = chainActive.Next(pindex);
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
while (pindex) {
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
CBlock block;
ReadBlockFromDisk(block, pindex);
BOOST_FOREACH (CTransaction& tx, block.vtx) {
if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
ret++;
}
pindex = chainActive.Next(pindex);
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
}
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) {
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && nDepth < 0) {
// Try to add to memory pool
LOCK(mempool.cs);
wtx.AcceptToMemoryPool(false);
}
}
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
if (mempool.exists(GetHash())) {
return true;
}
return false;
}
void CWalletTx::RelayWalletTransaction(std::string strCommand)
{
if (!IsCoinBase()) {
if (GetDepthInMainChain() == 0) {
uint256 hash = GetHash();
LogPrintf("Relaying wtx %s\n", hash.ToString());
if (strCommand == "ix") {
mapTxLockReq.insert(make_pair(hash, (CTransaction) * this));
CreateNewLock(((CTransaction) * this));
RelayTransactionLockReq((CTransaction) * this, true);
} else {
RelayTransaction((CTransaction) * this);
}
}
}
}
set<uint256> CWalletTx::GetConflicts() const
{
set<uint256> result;
if (pwallet != NULL) {
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
void CWallet::ResendWalletTransactions()
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nTimeBestReceived < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast any of our txes that aren't in a block yet
LogPrintf("ResendWalletTransactions()\n");
{
LOCK(cs_wallet);
// Sort them in chronological order
multimap<unsigned int, CWalletTx*> mapSorted;
BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) {
CWalletTx& wtx = item.second;
// Don't rebroadcast until it's had plenty of time that
// it should have gotten in already by now.
if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
}
BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) {
CWalletTx& wtx = *item.second;
wtx.RelayWalletTransaction();
}
}
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetAnonymizableBalance() const
{
if (fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAnonymizableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetAnonymizedBalance() const
{
if (fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAnonymizedCredit();
}
}
return nTotal;
}
// Note: calculated including unconfirmed,
// that's ok as long as we use it for informational purposes only
double CWallet::GetAverageAnonymizedRounds() const
{
if (fLiteMode) return 0;
double fTotal = 0;
double fCount = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
uint256 hash = (*it).first;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxIn vin = CTxIn(hash, i);
if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue;
int rounds = GetInputObfuscationRounds(vin);
fTotal += (float)rounds;
fCount += 1;
}
}
}
if (fCount == 0) return 0;
return fTotal / fCount;
}
// Note: calculated including unconfirmed,
// that's ok as long as we use it for informational purposes only
CAmount CWallet::GetNormalizedAnonymizedBalance() const
{
if (fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
uint256 hash = (*it).first;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxIn vin = CTxIn(hash, i);
if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue;
if (pcoin->GetDepthInMainChain() < 0) continue;
int rounds = GetInputObfuscationRounds(vin);
nTotal += pcoin->vout[i].nValue * rounds / nObfuscationRounds;
}
}
}
return nTotal;
}
CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const
{
if (fLiteMode) return 0;
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetDenominatedCredit(unconfirmed);
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
/**
* populate vCoins with vector of available COutputs.
*/
void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const
{
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const uint256& wtxid = it->first;
const CWalletTx* pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (fOnlyConfirmed && !pcoin->IsTrusted())
continue;
if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain(false);
// do not use IX for inputs that have less then 6 blockchain confirmations
if (fUseIX && nDepth < 6)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
bool found = false;
if (nCoinType == ONLY_DENOMINATED) {
found = IsDenominatedAmount(pcoin->vout[i].nValue);
} else if (nCoinType == ONLY_NOT10000IFMN) {
found = !(fMasterNode && pcoin->vout[i].nValue == 10000 * COIN);
} else if (nCoinType == ONLY_NONDENOMINATED_NOT10000IFMN) {
if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts
found = !IsDenominatedAmount(pcoin->vout[i].nValue);
if (found && fMasterNode) found = pcoin->vout[i].nValue != 10000 * COIN; // do not use Hot MN funds
} else if (nCoinType == ONLY_10000) {
found = pcoin->vout[i].nValue == 10000 * COIN;
} else {
found = true;
}
if (!found) continue;
isminetype mine = IsMine(pcoin->vout[i]);
if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
(!IsLockedCoin((*it).first, i) || nCoinType == ONLY_10000) &&
(pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
(!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected((*it).first, i)))
vCoins.push_back(COutput(pcoin, i, nDepth,
((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO)));
}
}
}
}
map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue)
{
vector<COutput> vCoins;
AvailableCoins(vCoins, fConfirmed);
map<CBitcoinAddress, vector<COutput> > mapCoins;
BOOST_FOREACH (COutput out, vCoins) {
if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue)
continue;
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
mapCoins[CBitcoinAddress(address)].push_back(out);
}
return mapCoins;
}
static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
seed_insecure_rand();
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) {
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) {
for (unsigned int i = 0; i < vValue.size(); i++) {
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) {
nTotal += vValue[i].first;
vfIncluded[i] = true;
if (nTotal >= nTargetValue) {
fReachedTarget = true;
if (nTotal < nBest) {
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].first;
vfIncluded[i] = false;
}
}
}
}
}
}
// TODO: find appropriate place for this sort function
// move denoms down
bool less_then_denom(const COutput& out1, const COutput& out2)
{
const CWalletTx* pcoin1 = out1.tx;
const CWalletTx* pcoin2 = out2.tx;
bool found1 = false;
bool found2 = false;
BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms
{
if (pcoin1->vout[out1.i].nValue == d) found1 = true;
if (pcoin2->vout[out2.i].nValue == d) found2 = true;
}
return (!found1 && found2);
}
bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int> >& setCoins, CAmount nTargetAmount) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins, true);
CAmount nAmountSelected = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//make sure not to outrun target amount
if (nAmountSelected + out.tx->vout[out.i].nValue > nTargetAmount)
continue;
//minimum imput stake
if (out.tx->vout[out.i].nValue < Params().StakingMinInput())
continue;
//new nNewStakeMinAge
// if (ActiveProtocol() >= MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT)
// nStakeMinAge = nNewStakeMinAge;
//check for min age
if (GetTime() - out.tx->GetTxTime() < nStakeMinAge)
continue;
//check that it is matured
if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10))
continue;
// check min input
if (ActiveProtocol() >= MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT) {
if (out.tx->vout[out.i].nValue < Params().StakingMinInput())
continue;
}
//add to our stake set
setCoins.insert(make_pair(out.tx, out.i));
nAmountSelected += out.tx->vout[out.i].nValue;
}
return true;
}
bool CWallet::MintableCoins()
{
CAmount nBalance = GetBalance();
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
return error("MintableCoins() : invalid reserve balance amount");
if (nBalance <= nReserveBalance)
return false;
vector<COutput> vCoins;
AvailableCoins(vCoins, true);
//new nNewStakeMinAge
//if (ActiveProtocol() >= MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT)
// nStakeMinAge = nNewStakeMinAge;
BOOST_FOREACH (const COutput& out, vCoins) {
if (GetTime() - out.tx->GetTxTime() > nStakeMinAge)
return true;
}
return false;
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger;
coinLowestLarger.first = std::numeric_limits<CAmount>::max();
coinLowestLarger.second.first = NULL;
vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
// move denoms down on the list
sort(vCoins.begin(), vCoins.end(), less_then_denom);
// try to find nondenom first to prevent unneeded spending of mixed coins
for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) {
if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom);
vValue.clear();
nTotalLower = 0;
BOOST_FOREACH (const COutput& output, vCoins) {
if (!output.fSpendable)
continue;
const CWalletTx* pcoin = output.tx;
// if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth);
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
int i = output.i;
CAmount n = pcoin->vout[i].nValue;
if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run
pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i));
if (n == nTargetValue) {
setCoinsRet.insert(coin.second);
nValueRet += coin.first;
return true;
} else if (n < nTargetValue + CENT) {
vValue.push_back(coin);
nTotalLower += n;
} else if (n < coinLowestLarger.first) {
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue) {
for (unsigned int i = 0; i < vValue.size(); ++i) {
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
}
return true;
}
if (nTotalLower < nTargetValue) {
if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue
{
if (tryDenom == 0)
// we didn't look at denom yet, let's do it
continue;
else
// we looked at everything possible and didn't find anything, no luck
return false;
}
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
return true;
}
// nTotalLower > nTargetValue
break;
}
// Solve subset sum by stochastic approximation
sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger.second.first &&
((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) {
setCoinsRet.insert(coinLowestLarger.second);
nValueRet += coinLowestLarger.first;
} else {
string s = "CWallet::SelectCoinsMinConf best subset: ";
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
setCoinsRet.insert(vValue[i].second);
nValueRet += vValue[i].first;
s += FormatMoney(vValue[i].first) + " ";
}
}
LogPrintf("%s - total %s\n", s, FormatMoney(nBest));
}
return true;
}
bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const
{
// Note: this function should never be used for "always free" tx types like dstx
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected()) {
BOOST_FOREACH (const COutput& out, vCoins) {
if (!out.fSpendable)
continue;
if (coin_type == ONLY_DENOMINATED) {
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
int rounds = GetInputObfuscationRounds(vin);
// make sure it's actually anonymized
if (rounds < nObfuscationRounds) continue;
}
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
//if we're doing only denominated, we need to round up to the nearest .1 DLC
if (coin_type == ONLY_DENOMINATED) {
// Make outputs by looping through denominations, from large to small
BOOST_FOREACH (CAmount v, obfuScationDenominations) {
BOOST_FOREACH (const COutput& out, vCoins) {
if (out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for
&& nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 DLC over
) {
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
int rounds = GetInputObfuscationRounds(vin);
// make sure it's actually anonymized
if (rounds < nObfuscationRounds) continue;
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.insert(make_pair(out.tx, out.i));
}
}
}
return (nValueRet >= nTargetValue);
}
return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
}
struct CompareByPriority {
bool operator()(const COutput& t1,
const COutput& t2) const
{
return t1.Priority() > t2.Priority();
}
};
bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax)
{
vCoinsRet.clear();
nValueRet = 0;
vCoinsRet2.clear();
vector<COutput> vCoins;
AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED);
std::random_shuffle(vCoins.rbegin(), vCoins.rend());
//keep track of each denomination that we have
bool fFound10000 = false;
bool fFound1000 = false;
bool fFound100 = false;
bool fFound10 = false;
bool fFound1 = false;
bool fFoundDot1 = false;
//Check to see if any of the denomination are off, in that case mark them as fulfilled
if (!(nDenom & (1 << 0))) fFound10000 = true;
if (!(nDenom & (1 << 1))) fFound1000 = true;
if (!(nDenom & (1 << 2))) fFound100 = true;
if (!(nDenom & (1 << 3))) fFound10 = true;
if (!(nDenom & (1 << 4))) fFound1 = true;
if (!(nDenom & (1 << 5))) fFoundDot1 = true;
BOOST_FOREACH (const COutput& out, vCoins) {
// masternode-like input should not be selected by AvailableCoins now anyway
if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) {
bool fAccepted = false;
// Function returns as follows:
//
// bit 0 - 10000 DLC+1 ( bit on if present )
// bit 1 - 1000 DLC+1
// bit 2 - 100 DLC+1
// bit 3 - 10 DLC+1
// bit 4 - 1 DLC+1
// bit 5 - .1 DLC+1
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
int rounds = GetInputObfuscationRounds(vin);
if (rounds >= nObfuscationRoundsMax) continue;
if (rounds < nObfuscationRoundsMin) continue;
if (fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1) { //if fulfilled
//we can return this for submission
if (nValueRet >= nValueMin) {
//random reduce the max amount we'll submit for anonymity
nValueMax -= (rand() % (nValueMax / 5));
//on average use 50% of the inputs or less
int r = (rand() % (int)vCoins.size());
if ((int)vCoinsRet.size() > r) return true;
}
//Denomination criterion has been met, we can take any matching denominations
if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) {
fAccepted = true;
} else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) {
fAccepted = true;
} else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) {
fAccepted = true;
} else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) {
fAccepted = true;
} else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) {
fAccepted = true;
} else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) {
fAccepted = true;
}
} else {
//Criterion has not been satisfied, we will only take 1 of each until it is.
if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) {
fAccepted = true;
fFound10000 = true;
} else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) {
fAccepted = true;
fFound1000 = true;
} else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) {
fAccepted = true;
fFound100 = true;
} else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) {
fAccepted = true;
fFound10 = true;
} else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) {
fAccepted = true;
fFound1 = true;
} else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) {
fAccepted = true;
fFoundDot1 = true;
}
}
if (!fAccepted) continue;
vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet += out.tx->vout[out.i].nValue;
vCoinsRet.push_back(vin);
vCoinsRet2.push_back(out);
}
}
return (nValueRet >= nValueMin && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1);
}
bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) const
{
CCoinControl* coinControl = NULL;
setCoinsRet.clear();
nValueRet = 0;
vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl, nObfuscationRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED);
set<pair<const CWalletTx*, unsigned int> > setCoinsRet2;
//order the array so largest nondenom are first, then denominations, then very small inputs.
sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority());
BOOST_FOREACH (const COutput& out, vCoins) {
//do not allow inputs less than 1 CENT
if (out.tx->vout[out.i].nValue < CENT) continue;
//do not allow collaterals to be selected
if (IsCollateralAmount(out.tx->vout[out.i].nValue)) continue;
if (fMasterNode && out.tx->vout[out.i].nValue == 10000 * COIN) continue; //masternode input
if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) {
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
int rounds = GetInputObfuscationRounds(vin);
if (rounds >= nObfuscationRoundsMax) continue;
if (rounds < nObfuscationRoundsMin) continue;
vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.push_back(vin);
setCoinsRet2.insert(make_pair(out.tx, out.i));
}
}
// if it's more than min, we're good to return
if (nValueRet >= nValueMin) return true;
return false;
}
bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet) const
{
vector<COutput> vCoins;
//LogPrintf(" selecting coins for collateral\n");
AvailableCoins(vCoins);
//LogPrintf("found coins %d\n", (int)vCoins.size());
set<pair<const CWalletTx*, unsigned int> > setCoinsRet2;
BOOST_FOREACH (const COutput& out, vCoins) {
// collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five
if (IsCollateralAmount(out.tx->vout[out.i].nValue)) {
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
nValueRet += out.tx->vout[out.i].nValue;
setCoinsRet.push_back(vin);
setCoinsRet2.insert(make_pair(out.tx, out.i));
return true;
}
}
return false;
}
int CWallet::CountInputsWithAmount(CAmount nInputAmount)
{
CAmount nTotal = 0;
{
LOCK(cs_wallet);
for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted()) {
int nDepth = pcoin->GetDepthInMainChain(false);
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
COutput out = COutput(pcoin, i, nDepth, true);
CTxIn vin = CTxIn(out.tx->GetHash(), out.i);
if (out.tx->vout[out.i].nValue != nInputAmount) continue;
if (!IsDenominatedAmount(pcoin->vout[i].nValue)) continue;
if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue;
nTotal++;
}
}
}
}
return nTotal;
}
bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const
{
vector<COutput> vCoins;
AvailableCoins(vCoins, fOnlyConfirmed);
int nFound = 0;
BOOST_FOREACH (const COutput& out, vCoins)
if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++;
return nFound > 0;
}
bool CWallet::IsCollateralAmount(CAmount nInputAmount) const
{
return nInputAmount != 0 && nInputAmount % OBFUSCATION_COLLATERAL == 0 && nInputAmount < OBFUSCATION_COLLATERAL * 5 && nInputAmount > OBFUSCATION_COLLATERAL;
}
bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason)
{
/*
To doublespend a collateral transaction, it will require a fee higher than this. So there's
still a significant cost.
*/
CAmount nFeeRet = 1 * COIN;
txCollateral.vin.clear();
txCollateral.vout.clear();
CReserveKey reservekey(this);
CAmount nValueIn2 = 0;
std::vector<CTxIn> vCoinsCollateral;
if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) {
strReason = "Error: Obfuscation requires a collateral transaction and could not locate an acceptable input!";
return false;
}
// make our change address
CScript scriptChange;
CPubKey vchPubKey;
assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
reservekey.KeepKey();
BOOST_FOREACH (CTxIn v, vCoinsCollateral)
txCollateral.vin.push_back(v);
if (nValueIn2 - OBFUSCATION_COLLATERAL - nFeeRet > 0) {
//pay collateral charge in fees
CTxOut vout3 = CTxOut(nValueIn2 - OBFUSCATION_COLLATERAL, scriptChange);
txCollateral.vout.push_back(vout3);
}
int vinNumber = 0;
BOOST_FOREACH (CTxIn v, txCollateral.vin) {
if (!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) {
BOOST_FOREACH (CTxIn v, vCoinsCollateral)
UnlockCoin(v.prevout);
strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n";
return false;
}
vinNumber++;
}
return true;
}
bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX)
{
CWalletTx wtx;
if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) {
tx = (CTransaction)wtx;
return true;
}
return false;
}
bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX)
{
// make our change address
CReserveKey reservekey(pwalletMain);
CScript scriptChange;
scriptChange << OP_RETURN << ToByteVector(hash);
CAmount nFeeRet = 0;
std::string strFail = "";
vector<pair<CScript, CAmount> > vecSend;
vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX));
CCoinControl* coinControl = NULL;
bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0);
if (!success) {
LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail);
return false;
}
return true;
}
bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<CAmount>& vecAmounts)
{
BOOST_FOREACH (CTxIn i, vCoins) {
if (mapWallet.count(i.prevout.hash)) {
CWalletTx& wtx = mapWallet[i.prevout.hash];
if (i.prevout.n < wtx.vout.size()) {
vecAmounts.push_back(wtx.vout[i.prevout.n].nValue);
}
} else {
LogPrintf("ConvertList -- Couldn't find transaction\n");
}
}
return true;
}
bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
CWalletTx& wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet,
std::string& strFailReason,
const CCoinControl* coinControl,
AvailableCoinsType coin_type,
bool useIX,
CAmount nFeePay)
{
if (useIX && nFeePay < CENT) nFeePay = CENT;
CAmount nValue = 0;
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
if (nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
nValue += s.second;
}
if (vecSend.empty() || nValue < 0) {
strFailReason = _("Transaction amounts must be positive");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
{
LOCK2(cs_main, cs_wallet);
{
nFeeRet = 0;
if (nFeePay > 0) nFeeRet = nFeePay;
while (true) {
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
CAmount nTotalValue = nValue + nFeeRet;
double dPriority = 0;
// vouts to the payees
if (coinControl && !coinControl->fSplitBlock) {
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
CTxOut txout(s.second, s.first);
if (txout.IsDust(::minRelayTxFee)) {
strFailReason = _("Transaction amount too small");
return false;
}
txNew.vout.push_back(txout);
}
} else //UTXO Splitter Transaction
{
int nSplitBlock;
if (coinControl)
nSplitBlock = coinControl->nSplitBlock;
else
nSplitBlock = 1;
BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) {
for (int i = 0; i < nSplitBlock; i++) {
if (i == nSplitBlock - 1) {
uint64_t nRemainder = s.second % nSplitBlock;
txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first));
} else
txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first));
}
}
}
// Choose coins to use
set<pair<const CWalletTx*, unsigned int> > setCoins;
CAmount nValueIn = 0;
if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) {
if (coin_type == ALL_COINS) {
strFailReason = _("Insufficient funds.");
} else if (coin_type == ONLY_NOT10000IFMN) {
strFailReason = _("Unable to locate enough funds for this transaction that are not equal 10000 DLC.");
} else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN) {
strFailReason = _("Unable to locate enough Obfuscation non-denominated funds for this transaction that are not equal 10000 DLC.");
} else {
strFailReason = _("Unable to locate enough Obfuscation denominated funds for this transaction.");
strFailReason += " " + _("Obfuscation uses exact denominated amounts to send funds, you might simply need to anonymize some more coins.");
}
if (useIX) {
strFailReason += " " + _("SwiftTX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again.");
}
return false;
}
BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) {
CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
//The coin age after the next block (depth+1) is used instead of the current,
//reflecting an assumption the user would accept a bit more delay for
//a chance at a free transaction.
//But mempool inputs might still be in the mempool, so their age stays 0
int age = pcoin.first->GetDepthInMainChain();
if (age != 0)
age += 1;
dPriority += (double)nCredit * age;
}
CAmount nChange = nValueIn - nValue - nFeeRet;
//over pay for denominated transactions
if (coin_type == ONLY_DENOMINATED) {
nFeeRet += nChange;
nChange = 0;
wtxNew.mapValue["DS"] = "1";
}
if (nChange > 0) {
// Fill a vout to ourself
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-delirium-address
CScript scriptChange;
// coin control: send change to custom address
if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
scriptChange = GetScriptForDestination(coinControl->destChange);
// no coin control: send change to newly generated address
else {
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey);
assert(ret); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
}
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (newTxOut.IsDust(::minRelayTxFee)) {
nFeeRet += nChange;
nChange = 0;
reservekey.ReturnKey();
} else {
// Insert change txn at random position:
vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1);
txNew.vout.insert(position, newTxOut);
}
} else
reservekey.ReturnKey();
// Fill vin
BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins)
txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second));
// Sign
int nIn = 0;
BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins)
if (!SignSignature(*this, *coin.first, txNew, nIn++)) {
strFailReason = _("Signing transaction failed");
return false;
}
// Embed the constructed transaction data in wtxNew.
*static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
// Limit size
unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= MAX_STANDARD_TX_SIZE) {
strFailReason = _("Transaction too large");
return false;
}
dPriority = wtxNew.ComputePriority(dPriority, nBytes);
// Can we complete this as a free transaction?
if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) {
// Not enough fee: enough priority?
double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
// Not enough mempool history to estimate: use hard-coded AllowFree.
if (dPriorityNeeded <= 0 && AllowFree(dPriority))
break;
// Small enough, and priority high enough, to send for free
if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
break;
}
CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool));
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) {
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) // Done, enough fee included
break;
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
}
return true;
}
bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay)
{
vector<pair<CScript, CAmount> > vecSend;
vecSend.push_back(make_pair(scriptPubKey, nValue));
return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay);
}
// ppcoin: create coin stake transaction
bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime)
{
// The following split & combine thresholds are important to security
// Should not be adjusted if you don't understand the consequences
//int64_t nCombineThreshold = 0;
txNew.vin.clear();
txNew.vout.clear();
// Mark coin stake transaction
CScript scriptEmpty;
scriptEmpty.clear();
txNew.vout.push_back(CTxOut(0, scriptEmpty));
// Choose coins to use
CAmount nBalance = GetBalance();
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
return error("CreateCoinStake : invalid reserve balance amount");
if (nBalance <= nReserveBalance)
return false;
// presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use
static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins;
static int nLastStakeSetUpdate = 0;
if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) {
setStakeCoins.clear();
if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance))
return false;
nLastStakeSetUpdate = GetTime();
}
if (setStakeCoins.empty())
return false;
vector<const CWalletTx*> vwtxPrev;
CAmount nCredit = 0;
CScript scriptPubKeyKernel;
//prevent staking a time that won't be accepted
if (GetAdjustedTime() <= chainActive.Tip()->nTime)
MilliSleep(10000);
BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) {
//make sure that enough time has elapsed between
CBlockIndex* pindex = NULL;
BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock);
if (it != mapBlockIndex.end())
pindex = it->second;
else {
if (fDebug)
LogPrintf("CreateCoinStake() failed to find block index \n");
continue;
}
// Read block header
CBlockHeader block = pindex->GetBlockHeader();
bool fKernelFound = false;
uint256 hashProofOfStake = 0;
COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
nTxNewTime = GetAdjustedTime();
//iterates each utxo inside of CheckStakeKernelHash()
if (CheckStakeKernelHash(nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) {
//Double check that this will pass time requirements
if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) {
LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n");
continue;
}
// Found a kernel
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : kernel found\n");
vector<valtype> vSolutions;
txnouttype whichType;
CScript scriptPubKeyOut;
scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) {
LogPrintf("CreateCoinStake : failed to parse kernel\n");
break;
}
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType);
if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) {
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType);
break; // only support pay to public key and pay to address
}
if (whichType == TX_PUBKEYHASH) // pay to address type
{
//convert to pay to public key type
CKey key;
if (!keystore.GetKey(uint160(vSolutions[0]), key)) {
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
break; // unable to find corresponding public key
}
scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
} else
scriptPubKeyOut = scriptPubKeyKernel;
txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
nCredit += pcoin.first->vout[pcoin.second].nValue;
vwtxPrev.push_back(pcoin.first);
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
//presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs
const CBlockIndex* pIndex0 = chainActive.Tip();
uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + GetBlockValue(pIndex0->nHeight);
//presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down)
if (nTotalSize / 2 > nStakeSplitThreshold * COIN)
txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
if (fDebug && GetBoolArg("-printcoinstake", false))
LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType);
fKernelFound = true;
break;
}
if (fKernelFound)
break; // if kernel is found stop searching
}
if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
return false;
// Calculate reward
CAmount nReward;
const CBlockIndex* pIndex0 = chainActive.Tip();
nReward = GetBlockValue(pIndex0->nHeight);
nCredit += nReward;
CAmount nMinFee = 0;
while (true) {
// Set output amount
if (txNew.vout.size() == 3) {
txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
} else
txNew.vout[1].nValue = nCredit - nMinFee;
// Limit size
unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5)
return error("CreateCoinStake : exceeded coinstake size limit");
CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
// Check enough fee is paid
if (nMinFee < nFeeNeeded) {
nMinFee = nFeeNeeded;
continue; // try signing again
} else {
if (fDebug)
LogPrintf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
break;
}
}
//Masternode payment
FillBlockPayee(txNew, nMinFee, true);
// Sign
int nIn = 0;
BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) {
if (!SignSignature(*this, *pcoin, txNew, nIn++))
return error("CreateCoinStake : failed to sign coinstake");
}
// Successfully generated coinstake
nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
{
// This is only to keep the database open to defeat the auto-flush for the
// duration of this scope. This is the only place where this optimization
// maybe makes sense; please don't do it anywhere else.
CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL;
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
set<uint256> updated_hahes;
BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) {
// notify only once
if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue;
CWalletTx& coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
updated_hahes.insert(txin.prevout.hash);
}
if (fFileBacked)
delete pwalletdb;
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
// Broadcast
if (!wtxNew.AcceptToMemoryPool(false)) {
// This must not fail. The transaction has already been signed and recorded.
LogPrintf("CommitTransaction() : Error: Transaction not valid\n");
return false;
}
wtxNew.RelayWalletTransaction(strCommand);
}
return true;
}
CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
{
// payTxFee is user-set "I want to pay this much"
CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
// user selected total at least (default=true)
if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
nFeeNeeded = payTxFee.GetFeePerK();
// User didn't set: use -txconfirmtarget to estimate...
if (nFeeNeeded == 0)
nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
// ... unless we don't have enough mempool data, in which case fall
// back to a hard-coded fee
if (nFeeNeeded == 0)
nFeeNeeded = minTxFee.GetFee(nTxBytes);
// prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
// But always obey the maximum
if (nFeeNeeded > maxTxFee)
nFeeNeeded = maxTxFee;
return nFeeNeeded;
}
CAmount CWallet::GetTotalValue(std::vector<CTxIn> vCoins)
{
CAmount nTotalValue = 0;
CWalletTx wtx;
BOOST_FOREACH (CTxIn i, vCoins) {
if (mapWallet.count(i.prevout.hash)) {
CWalletTx& wtx = mapWallet[i.prevout.hash];
if (i.prevout.n < wtx.vout.size()) {
nTotalValue += wtx.vout[i.prevout.n].nValue;
}
} else {
LogPrintf("GetTotalValue -- Couldn't find transaction\n");
}
}
return nTotalValue;
}
string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds)
{
if (IsLocked())
return _("Error: Wallet locked, unable to create transaction!");
if (obfuScationPool.GetState() != POOL_STATUS_ERROR && obfuScationPool.GetState() != POOL_STATUS_SUCCESS)
if (obfuScationPool.GetEntriesCount() > 0)
return _("Error: You already have pending entries in the Obfuscation pool");
// ** find the coins we'll use
std::vector<CTxIn> vCoins;
std::vector<CTxIn> vCoinsResult;
std::vector<COutput> vCoins2;
CAmount nValueIn = 0;
CReserveKey reservekey(this);
/*
Select the coins we'll use
if minRounds >= 0 it means only denominated inputs are going in and coming out
*/
if (minRounds >= 0) {
if (!SelectCoinsByDenominations(obfuScationPool.sessionDenom, 0.1 * COIN, OBFUSCATION_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds))
return _("Error: Can't select current denominated inputs");
}
LogPrintf("PrepareObfuscationDenominate - preparing obfuscation denominate . Got: %d \n", nValueIn);
{
LOCK(cs_wallet);
BOOST_FOREACH (CTxIn v, vCoins)
LockCoin(v.prevout);
}
CAmount nValueLeft = nValueIn;
std::vector<CTxOut> vOut;
/*
TODO: Front load with needed denominations (e.g. .1, 1 )
*/
// Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times.
// This way we can be pretty sure that it should have at least one of each needed denomination.
// NOTE: No need to randomize order of inputs because they were
// initially shuffled in CWallet::SelectCoinsByDenominations already.
int nStep = 0;
int nStepsMax = 5 + GetRandInt(5);
while (nStep < nStepsMax) {
BOOST_FOREACH (CAmount v, obfuScationDenominations) {
// only use the ones that are approved
bool fAccepted = false;
if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) {
fAccepted = true;
} else if ((obfuScationPool.sessionDenom & (1 << 1)) && v == ((1000 * COIN) + 1000000)) {
fAccepted = true;
} else if ((obfuScationPool.sessionDenom & (1 << 2)) && v == ((100 * COIN) + 100000)) {
fAccepted = true;
} else if ((obfuScationPool.sessionDenom & (1 << 3)) && v == ((10 * COIN) + 10000)) {
fAccepted = true;
} else if ((obfuScationPool.sessionDenom & (1 << 4)) && v == ((1 * COIN) + 1000)) {
fAccepted = true;
} else if ((obfuScationPool.sessionDenom & (1 << 5)) && v == ((.1 * COIN) + 100)) {
fAccepted = true;
}
if (!fAccepted) continue;
// try to add it
if (nValueLeft - v >= 0) {
// Note: this relies on a fact that both vectors MUST have same size
std::vector<CTxIn>::iterator it = vCoins.begin();
std::vector<COutput>::iterator it2 = vCoins2.begin();
while (it2 != vCoins2.end()) {
// we have matching inputs
if ((*it2).tx->vout[(*it2).i].nValue == v) {
// add new input in resulting vector
vCoinsResult.push_back(*it);
// remove corresponting items from initial vectors
vCoins.erase(it);
vCoins2.erase(it2);
CScript scriptChange;
CPubKey vchPubKey;
// use a unique change address
assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked
scriptChange = GetScriptForDestination(vchPubKey.GetID());
reservekey.KeepKey();
// add new output
CTxOut o(v, scriptChange);
vOut.push_back(o);
// subtract denomination amount
nValueLeft -= v;
break;
}
++it;
++it2;
}
}
}
nStep++;
if (nValueLeft == 0) break;
}
{
// unlock unused coins
LOCK(cs_wallet);
BOOST_FOREACH (CTxIn v, vCoins)
UnlockCoin(v.prevout);
}
if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) {
// unlock used coins on failure
LOCK(cs_wallet);
BOOST_FOREACH (CTxIn v, vCoinsResult)
UnlockCoin(v.prevout);
return "Error: can't make current denominated outputs";
}
// randomize the output order
std::random_shuffle(vOut.begin(), vOut.end());
// We also do not care about full amount as long as we have right denominations, just pass what we found
obfuScationPool.SendObfuscationDenominate(vCoinsResult, vOut, nValueIn - nValueLeft);
return "";
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
if (!fFileBacked)
return DB_LOAD_OK;
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE) {
if (CDB::Rewrite(strWalletFile, "\x04pool")) {
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// the requires a new key.
}
}
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
fFirstRunRet = !vchDefaultKey.IsValid();
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
if (!fFileBacked)
return DB_LOAD_OK;
DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE) {
if (CDB::Rewrite(strWalletFile, "\x04pool")) {
LOCK(cs_wallet);
setKeyPool.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW));
if (!fFileBacked)
return false;
if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
return false;
return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
if (fFileBacked) {
// Delete destdata tuples associated with address
std::string strAddress = CBitcoinAddress(address).ToString();
BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) {
CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
}
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
if (!fFileBacked)
return false;
CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
}
bool CWallet::SetDefaultKey(const CPubKey& vchPubKey)
{
if (fFileBacked) {
if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
return false;
}
vchDefaultKey = vchPubKey;
return true;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH (int64_t nIndex, setKeyPool)
walletdb.ErasePool(nIndex);
setKeyPool.clear();
if (IsLocked())
return false;
int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0);
for (int i = 0; i < nKeys; i++) {
int64_t nIndex = i + 1;
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
}
return true;
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
CWalletDB walletdb(strWalletFile);
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0);
while (setKeyPool.size() < (nTargetSize + 1)) {
int64_t nEnd = 1;
if (!setKeyPool.empty())
nEnd = *(--setKeyPool.end()) + 1;
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
double dProgress = 100.f * nEnd / (nTargetSize + 1);
std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress);
uiInterface.InitMessage(strMsg);
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
// Get the oldest key
if (setKeyPool.empty())
return;
CWalletDB walletdb(strWalletFile);
nIndex = *(setKeyPool.begin());
setKeyPool.erase(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool))
throw runtime_error("ReserveKeyFromKeyPool() : read failed");
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
if (fFileBacked) {
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex)
{
// Return to key pool
{
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result)
{
int64_t nIndex = 0;
CKeyPool keypool;
{
LOCK(cs_wallet);
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1) {
if (IsLocked()) return false;
result = GenerateNewKey();
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
int64_t nIndex = 0;
CKeyPool keypool;
ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex == -1)
return GetTime();
ReturnKey(nIndex);
return keypool.nTime;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) {
CWalletTx* pcoin = &walletEntry.second;
if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
CTxDestination addr;
if (!IsMine(pcoin->vout[i]))
continue;
if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
set<set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
set<set<CTxDestination> > groupings;
set<CTxDestination> grouping;
BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) {
CWalletTx* pcoin = &walletEntry.second;
if (pcoin->vin.size() > 0) {
bool any_mine = false;
// group all input addresses with each other
BOOST_FOREACH (CTxIn txin, pcoin->vin) {
CTxDestination address;
if (!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine) {
BOOST_FOREACH (CTxOut txout, pcoin->vout)
if (IsChange(txout)) {
CTxDestination txoutAddr;
if (!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0) {
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (unsigned int i = 0; i < pcoin->vout.size(); i++)
if (IsMine(pcoin->vout[i])) {
CTxDestination address;
if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses
map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it
BOOST_FOREACH (set<CTxDestination> grouping, groupings) {
// make a set of all the groups hit by this new group
set<set<CTxDestination>*> hits;
map<CTxDestination, set<CTxDestination>*>::iterator it;
BOOST_FOREACH (CTxDestination address, grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
set<CTxDestination>* merged = new set<CTxDestination>(grouping);
BOOST_FOREACH (set<CTxDestination>* hit, hits) {
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
BOOST_FOREACH (CTxDestination element, *merged)
setmap[element] = merged;
}
set<set<CTxDestination> > ret;
BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) {
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
{
LOCK(cs_wallet);
set<CTxDestination> result;
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) {
const CTxDestination& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey)
{
if (nIndex == -1) {
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1)
pwallet->ReturnKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
{
setAddress.clear();
CWalletDB walletdb(strWalletFile);
LOCK2(cs_main, cs_wallet);
BOOST_FOREACH (const int64_t& id, setKeyPool) {
CKeyPool keypool;
if (!walletdb.ReadPool(id, keypool))
throw runtime_error("GetAllReserveKeyHashes() : read failed");
assert(keypool.vchPubKey.IsValid());
CKeyID keyID = keypool.vchPubKey.GetID();
if (!HaveKey(keyID))
throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
setAddress.insert(keyID);
}
}
bool CWallet::UpdatedTransaction(const uint256& hashTx)
{
{
LOCK(cs_wallet);
// Only notify UI if this transaction is in this wallet
map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
if (mi != mapWallet.end()) {
NotifyTransactionChanged(this, hashTx, CT_UPDATED);
return true;
}
}
return false;
}
void CWallet::LockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
class CAffectedKeysVisitor : public boost::static_visitor<void>
{
private:
const CKeyStore& keystore;
std::vector<CKeyID>& vKeys;
public:
CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript& script)
{
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
BOOST_FOREACH (const CTxDestination& dest, vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID& keyId)
{
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID& scriptId)
{
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination& none) {}
};
void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
if (it->second.nCreateTime)
mapKeyBirth[it->first] = it->second.nCreateTime;
// map in which we'll infer heights of other keys
CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
std::set<CKeyID> setKeys;
GetKeys(setKeys);
BOOST_FOREACH (const CKeyID& keyid, setKeys) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
setKeys.clear();
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx& wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
BOOST_FOREACH (const CKeyID& keyid, vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
}
bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
}
bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
if (!fFileBacked)
return true;
return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
}
bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if (i != mapAddressBook.end()) {
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if (j != i->second.destdata.end()) {
if (value)
*value = j->second;
return true;
}
}
return false;
}
void CWallet::AutoCombineDust()
{
if (IsInitialBlockDownload() || IsLocked()) {
return;
}
map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0);
//coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address
for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) {
vector<COutput> vCoins, vRewardCoins;
vCoins = it->second;
//find masternode rewards that need to be combined
CCoinControl* coinControl = new CCoinControl();
CAmount nTotalRewardsValue = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//no coins should get this far if they dont have proper maturity, this is double checking
if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < COINBASE_MATURITY + 1)
continue;
if (out.Value() > nAutoCombineThreshold * COIN)
continue;
COutPoint outpt(out.tx->GetHash(), out.i);
coinControl->Select(outpt);
vRewardCoins.push_back(out);
nTotalRewardsValue += out.Value();
}
//if no inputs found then return
if (!coinControl->HasSelected())
continue;
//we cannot combine one coin with itself
if (vRewardCoins.size() <= 1)
continue;
vector<pair<CScript, CAmount> > vecSend;
CScript scriptPubKey = GetScriptForDestination(it->first.Get());
vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue));
// Create the transaction and commit it to the network
CWalletTx wtx;
CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
string strErr;
CAmount nFeeRet = 0;
//get the fee amount
CWalletTx wtxdummy;
CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0));
vecSend[0].second = nTotalRewardsValue - nFeeRet - 500;
if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) {
LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr);
continue;
}
if (!CommitTransaction(wtx, keyChange)) {
LogPrintf("AutoCombineDust transaction commit failed\n");
continue;
}
LogPrintf("AutoCombineDust sent transaction\n");
delete coinControl;
}
}
bool CWallet::MultiSend()
{
if (IsInitialBlockDownload() || IsLocked()) {
return false;
}
if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) {
LogPrintf("Multisend: lastmultisendheight is higher than current best height\n");
return false;
}
std::vector<COutput> vCoins;
AvailableCoins(vCoins);
int stakeSent = 0;
int mnSent = 0;
BOOST_FOREACH (const COutput& out, vCoins) {
//need output with precise confirm count - this is how we identify which is the output to send
if (out.tx->GetDepthInMainChain() != COINBASE_MATURITY + 1)
continue;
COutPoint outpoint(out.tx->GetHash(), out.i);
bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx);
bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both
if (!(sendMSOnStake || sendMSonMNReward))
continue;
CTxDestination destMyAddress;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) {
LogPrintf("Multisend: failed to extract destination\n");
continue;
}
//Disabled Addresses won't send MultiSend transactions
if (vDisabledAddresses.size() > 0) {
for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) {
if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) {
LogPrintf("Multisend: disabled address preventing multisend\n");
return false;
}
}
}
// create new coin control, populate it with the selected utxo, create sending vector
CCoinControl* cControl = new CCoinControl();
COutPoint outpt(out.tx->GetHash(), out.i);
cControl->Select(outpt);
cControl->destChange = destMyAddress;
CWalletTx wtx;
CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch
CAmount nFeeRet = 0;
vector<pair<CScript, CAmount> > vecSend;
// loop through multisend vector and add amounts and addresses to the sending vector
const isminefilter filter = ISMINE_SPENDABLE;
CAmount nAmount = 0;
for (unsigned int i = 0; i < vMultiSend.size(); i++) {
// MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int
nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100;
CBitcoinAddress strAddSend(vMultiSend[i].first);
CScript scriptPubKey;
scriptPubKey = GetScriptForDestination(strAddSend.Get());
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
//get the fee amount
CWalletTx wtxdummy;
string strErr;
CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0));
CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second;
if (nLastSendAmount < nFeeRet + 500) {
LogPrintf("%s: fee of %s is too large to insert into last output\n");
return false;
}
vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500;
// Create the transaction and commit it to the network
if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) {
LogPrintf("MultiSend createtransaction failed\n");
return false;
}
if (!CommitTransaction(wtx, keyChange)) {
LogPrintf("MultiSend transaction commit failed\n");
return false;
} else
fMultiSendNotify = true;
delete cControl;
//write nLastMultiSendHeight to DB
CWalletDB walletdb(strWalletFile);
nLastMultiSendHeight = chainActive.Tip()->nHeight;
if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight))
LogPrintf("Failed to write MultiSend setting to DB\n");
LogPrintf("MultiSend successfully sent\n");
if (sendMSOnStake)
stakeSent++;
else
mnSent++;
//stop iterating if we are done
if (mnSent > 0 && stakeSent > 0)
return true;
if (stakeSent > 0 && !fMultiSendMasternodeReward)
return true;
if (mnSent > 0 && !fMultiSendStake)
return true;
}
return true;
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
int CMerkleTx::SetMerkleBranch(const CBlock& block)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)block.vtx.size()) {
vMerkleBranch.clear();
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = block.GetMerkleBranch(nIndex);
// Is the tx in a block that's in the main chain
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
const CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified) {
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
if (enableIX) {
if (nResult < 6) {
int signatures = GetTransactionLockSignatures();
if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) {
return nSwiftTXDepth + nResult;
}
}
}
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees)
{
CValidationState state;
return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees);
}
int CMerkleTx::GetTransactionLockSignatures() const
{
if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2;
if (!IsSporkActive(SPORK_2_SWIFTTX)) return -3;
if (!fEnableSwiftTX) return -1;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()) {
return (*i).second.CountSignatures();
}
return -1;
}
bool CMerkleTx::IsTransactionLockTimedOut() const
{
if (!fEnableSwiftTX) return 0;
//compile consessus vote
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash());
if (i != mapTxLocks.end()) {
return GetTime() > (*i).second.nTimeout;
}
return false;
}
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtXmlPatterns module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsourcelocation.h"
#include "qsourcelocationreflection_p.h"
QT_BEGIN_NAMESPACE
using namespace QPatternist;
QSourceLocation SourceLocationReflection::sourceLocation() const
{
return QSourceLocation();
}
const SourceLocationReflection *DelegatingSourceLocationReflection::actualReflection() const
{
return m_r->actualReflection();
}
QString DelegatingSourceLocationReflection::description() const
{
return m_r->description();
}
QT_END_NAMESPACE
|
MOV $0, #0
MOV $1, #1
MOV $2, #0
LOD $3, fib_digit
loop: b: c:
d:
ADD $4, $0, $1
MOV $0, $1
MOV $1, $4
ADD $2, $2, #1
CMP $5, $2, $3
BRA loop, !LT $5
e: DBG
DIE
fib_digit: DAT #10
|
; A179059: Number of non-attacking placements of 4 rooks on an n X n board.
; 0,0,0,24,600,5400,29400,117600,381024,1058400,2613600,5880600,12269400,24048024,44717400,79497600,135945600,224726400,360561024,563376600,859685400,1284221400,1881864600,2709885024,3840540000,5364060000,7392060000,10061415000,13538640024,18024816600,23761109400,31034918400,40186713600,51617601024,65797670400,83275176600,104686608600,130767701400,162365448024,200451170400,246134709600,300679797600,365520674400,442280016024,532788240600,639104261400,763537757400,908673033600,1077394545024,1272914160000,1498800240000,1759008615000,2057915535000,2400352680024,2791644312600,3237646658400,3744789602400,4320120789600,4971352221024,5706909437400,6535983384600,7468585056600,8515603013400,9688863873024,11001195878400,12466495641600,14099798169600,15917350277400,17936687496024,20176714584600,22657789757400,25401812738400,28432316757600,31774564605024,35455648860000,39504596415000,43952477415000,48832518735000,54180222120024,60033487113600,66432738902400,73421061206400,81044334345600,89351378616024,98394103109400,108227660112600,118910605224600,130505063330400,143076900573024,156695902466400,171435958293600,187375251936600,204596459285400,223186952376024,243239010408600,264850037798400,288122789414400,313165603161600,340092640065024,369024132015000
add $0,1
bin $0,4
pow $0,2
mul $0,24
|
%include "colon.inc"
%include "words.inc"
global _start
extern print_string
extern read_word
extern exit
extern find_word
extern print_newline
extern string_length
%define STD_OUT 0x01
%define STD_ERR 0x02
section .rodata
mes_enter: db "enter the key: ", 0
mes_key_not_found_str: db "ERROR: such key is not in dictionary", 10, 0
mes_string_too_long: db "ERROR: input string is too long", 10, 0
mes_result: db "value: ", 0
section .text
_start:
sub rsp, 256
mov rdi, mes_enter
mov rsi, STD_OUT
call print_string
mov rdi, rsp
mov rsi, 256
call read_word
cmp rax, 0
je .print_error_length
mov rdi, rax
mov rsi, LAST_LABEL ; LAST_LABEL - directive in colon.inc
call find_word
test rax, rax
jz .print_not_found
.print_key:
mov rdi, rax
add rdi, 8 ; address of key element
push rdi
call string_length
pop rdi
add rdi, rax
inc rdi ; goto value (key length + 1)
mov rsi, STD_OUT
call print_string
call print_newline
add rsp, 256
call exit
.print_error_length:
mov rdi, mes_string_too_long
mov rsi, STD_ERR
call print_string
add rsp, 256
call exit
.print_not_found:
mov rdi, mes_key_not_found_str
mov rsi, STD_ERR
call print_string
add rsp, 256
call exit
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>signalfd4(vararg_0, vararg_1, vararg_2, vararg_3, vararg_4) -> str
Invokes the syscall signalfd4.
See 'man 2 signalfd4' for more information.
Arguments:
vararg(int): vararg
Returns:
long
</%docstring>
<%page args="vararg_0=None, vararg_1=None, vararg_2=None, vararg_3=None, vararg_4=None"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['vararg_0', 'vararg_1', 'vararg_2', 'vararg_3', 'vararg_4']
argument_values = [vararg_0, vararg_1, vararg_2, vararg_3, vararg_4]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_signalfd4']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* signalfd4(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
; char *stpncpy(char * restrict s1, const char * restrict s2, size_t n)
IF !__CPU_GBZ80__
SECTION code_clib
SECTION code_string
PUBLIC stpncpy_callee
EXTERN asm_stpncpy
stpncpy_callee:
pop af
pop bc
pop hl
pop de
push af
jp asm_stpncpy
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _stpncpy_callee
defc _stpncpy_callee = stpncpy_callee
ENDIF
ENDIF
|
// Copyright (c) 2014-2015 The FargoCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <vector>
#include <boost/test/unit_test.hpp>
#define SKIPLIST_LENGTH 300000
BOOST_FIXTURE_TEST_SUITE(skiplist_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(skiplist_test)
{
std::vector<CBlockIndex> vIndex(SKIPLIST_LENGTH);
for (int i=0; i<SKIPLIST_LENGTH; i++) {
vIndex[i].nHeight = i;
vIndex[i].pprev = (i == 0) ? NULL : &vIndex[i - 1];
vIndex[i].BuildSkip();
}
for (int i=0; i<SKIPLIST_LENGTH; i++) {
if (i > 0) {
BOOST_CHECK(vIndex[i].pskip == &vIndex[vIndex[i].pskip->nHeight]);
BOOST_CHECK(vIndex[i].pskip->nHeight < i);
} else {
BOOST_CHECK(vIndex[i].pskip == NULL);
}
}
for (int i=0; i < 1000; i++) {
int from = insecure_rand() % (SKIPLIST_LENGTH - 1);
int to = insecure_rand() % (from + 1);
BOOST_CHECK(vIndex[SKIPLIST_LENGTH - 1].GetAncestor(from) == &vIndex[from]);
BOOST_CHECK(vIndex[from].GetAncestor(to) == &vIndex[to]);
BOOST_CHECK(vIndex[from].GetAncestor(0) == &vIndex[0]);
}
}
BOOST_AUTO_TEST_CASE(getlocator_test)
{
// Build a main chain 100000 blocks long.
std::vector<uint256> vHashMain(100000);
std::vector<CBlockIndex> vBlocksMain(100000);
for (unsigned int i=0; i<vBlocksMain.size(); i++) {
vHashMain[i] = ArithToUint256(i); // Set the hash equal to the height, so we can quickly check the distances.
vBlocksMain[i].nHeight = i;
vBlocksMain[i].pprev = i ? &vBlocksMain[i - 1] : NULL;
vBlocksMain[i].phashBlock = &vHashMain[i];
vBlocksMain[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksMain[i].GetBlockHash()).GetLow64(), vBlocksMain[i].nHeight);
BOOST_CHECK(vBlocksMain[i].pprev == NULL || vBlocksMain[i].nHeight == vBlocksMain[i].pprev->nHeight + 1);
}
// Build a branch that splits off at block 49999, 50000 blocks long.
std::vector<uint256> vHashSide(50000);
std::vector<CBlockIndex> vBlocksSide(50000);
for (unsigned int i=0; i<vBlocksSide.size(); i++) {
vHashSide[i] = ArithToUint256(i + 50000 + (arith_uint256(1) << 128)); // Add 1<<128 to the hashes, so GetLow64() still returns the height.
vBlocksSide[i].nHeight = i + 50000;
vBlocksSide[i].pprev = i ? &vBlocksSide[i - 1] : &vBlocksMain[49999];
vBlocksSide[i].phashBlock = &vHashSide[i];
vBlocksSide[i].BuildSkip();
BOOST_CHECK_EQUAL((int)UintToArith256(vBlocksSide[i].GetBlockHash()).GetLow64(), vBlocksSide[i].nHeight);
BOOST_CHECK(vBlocksSide[i].pprev == NULL || vBlocksSide[i].nHeight == vBlocksSide[i].pprev->nHeight + 1);
}
// Build a CChain for the main branch.
CChain chain;
chain.SetTip(&vBlocksMain.back());
// Test 100 random starting points for locators.
for (int n=0; n<100; n++) {
int r = insecure_rand() % 150000;
CBlockIndex* tip = (r < 100000) ? &vBlocksMain[r] : &vBlocksSide[r - 100000];
CBlockLocator locator = chain.GetLocator(tip);
// The first result must be the block itself, the last one must be genesis.
BOOST_CHECK(locator.vHave.front() == tip->GetBlockHash());
BOOST_CHECK(locator.vHave.back() == vBlocksMain[0].GetBlockHash());
// Entries 1 through 11 (inclusive) go back one step each.
for (unsigned int i = 1; i < 12 && i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i]).GetLow64(), tip->nHeight - i);
}
// The further ones (excluding the last one) go back with exponential steps.
unsigned int dist = 2;
for (unsigned int i = 12; i < locator.vHave.size() - 1; i++) {
BOOST_CHECK_EQUAL(UintToArith256(locator.vHave[i - 1]).GetLow64() - UintToArith256(locator.vHave[i]).GetLow64(), dist);
dist *= 2;
}
}
}
BOOST_AUTO_TEST_SUITE_END()
|
// Copyright (c) 2020 Tom Hancocks
//
// 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.
#if !defined(KDL_UNNAMED_REFERENCE_VALUE_PARSER_HPP)
#define KDL_UNNAMED_REFERENCE_VALUE_PARSER_HPP
#include "parser/parser.hpp"
namespace kdl { namespace sema {
class unnamed_reference_value_parser
{
private:
parser& m_parser;
build_target::kdl_type& m_explicit_type;
build_target::type_field& m_field;
build_target::type_field_value& m_field_value;
build_target::type_template::binary_field m_binary_field;
public:
unnamed_reference_value_parser(parser& parser, build_target::type_field& field,
build_target::type_field_value& field_value,
build_target::type_template::binary_field binary_field,
build_target::kdl_type& type);
auto parse(build_target::resource_instance& instance) -> void;
};
}};
#endif //KDL_UNNAMED_REFERENCE_VALUE_PARSER_HPP
|
; A188656: Decimal expansion of (1+sqrt(65))/8.
; Submitted by Jon Maiga
; 1,1,3,2,7,8,2,2,1,8,5,3,7,3,1,8,7,0,6,5,4,5,8,2,6,6,5,3,7,8,7,9,7,1,3,9,1,3,9,1,7,9,9,5,3,8,2,0,1,0,7,1,6,7,3,4,9,2,0,7,4,0,4,8,6,5,7,9,8,4,3,6,8,8,7,8,2,1,1,0,2,5,3,7,0,0,1,9,2,8,3,3,3,9,6,5,3,8,3,0
mov $1,1
mov $2,1
mov $3,$0
mul $3,6
lpb $3
mul $1,$3
mul $2,$3
add $1,$2
add $5,1
div $1,$5
div $2,$5
add $2,$1
mul $2,4
sub $3,4
lpe
mov $4,10
pow $4,$0
div $2,$4
div $1,$2
mod $1,10
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r13
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x50e, %rdx
nop
nop
sub %r12, %r12
mov $0x6162636465666768, %rsi
movq %rsi, %xmm2
and $0xffffffffffffffc0, %rdx
vmovntdq %ymm2, (%rdx)
nop
nop
nop
cmp $14953, %r8
lea addresses_A_ht+0xdd0e, %r13
nop
nop
nop
nop
sub $48869, %r10
movb $0x61, (%r13)
nop
and $45676, %rdx
lea addresses_WT_ht+0x1fbe, %rsi
lea addresses_WT_ht+0x1c68e, %rdi
nop
nop
nop
nop
nop
cmp $62512, %rdx
mov $125, %rcx
rep movsl
nop
nop
nop
nop
nop
sub $2845, %r10
lea addresses_A_ht+0xdc2e, %r12
nop
nop
nop
nop
nop
cmp $33787, %r13
movups (%r12), %xmm6
vpextrq $0, %xmm6, %rcx
xor %r13, %r13
lea addresses_UC_ht+0x170e, %r8
nop
nop
nop
xor %rdi, %rdi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm5
vmovups %ymm5, (%r8)
nop
inc %r8
lea addresses_UC_ht+0x1a50e, %r10
nop
nop
nop
nop
and %r8, %r8
mov (%r10), %r12d
nop
nop
nop
cmp $5953, %rcx
lea addresses_A_ht+0xf90e, %rdx
xor %rcx, %rcx
movw $0x6162, (%rdx)
nop
nop
xor %rdx, %rdx
lea addresses_normal_ht+0x448e, %r10
nop
nop
nop
cmp $33528, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm0
movups %xmm0, (%r10)
nop
sub $35293, %rsi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r13
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r15
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_UC+0xc04e, %r12
nop
nop
nop
and %rdx, %rdx
movl $0x51525354, (%r12)
nop
nop
nop
nop
xor $62550, %r8
// Store
lea addresses_PSE+0x15080, %r8
nop
nop
nop
nop
and %r11, %r11
mov $0x5152535455565758, %r10
movq %r10, (%r8)
nop
nop
nop
and $55585, %rdx
// Store
lea addresses_normal+0x436a, %r10
nop
nop
cmp $31280, %rsi
movl $0x51525354, (%r10)
nop
nop
nop
nop
nop
add $6073, %r15
// Store
lea addresses_A+0x35b6, %r8
nop
and $48167, %rdx
movb $0x51, (%r8)
nop
nop
nop
nop
sub %r12, %r12
// Store
lea addresses_WT+0x1ce36, %rdx
nop
nop
nop
nop
nop
xor %r11, %r11
mov $0x5152535455565758, %r8
movq %r8, %xmm6
vmovups %ymm6, (%rdx)
nop
nop
dec %r15
// Load
lea addresses_WC+0x1782e, %r15
nop
nop
nop
nop
inc %r8
mov (%r15), %rsi
nop
nop
nop
sub $46466, %r8
// Store
lea addresses_PSE+0xac0e, %r8
cmp %r12, %r12
mov $0x5152535455565758, %r10
movq %r10, %xmm6
vmovups %ymm6, (%r8)
nop
nop
nop
sub %rdx, %rdx
// Store
lea addresses_PSE+0x17c0e, %r15
nop
nop
sub $53592, %r8
movb $0x51, (%r15)
nop
nop
nop
nop
inc %rsi
// REPMOV
lea addresses_D+0x1590e, %rsi
lea addresses_WC+0xec0e, %rdi
add $37955, %rdx
mov $81, %rcx
rep movsl
nop
nop
and $60147, %rdx
// Store
lea addresses_WC+0x1e00e, %rdi
nop
nop
nop
nop
nop
xor $29285, %r15
movw $0x5152, (%rdi)
nop
nop
nop
cmp %r15, %r15
// Faulty Load
lea addresses_WT+0x1310e, %r15
nop
nop
nop
nop
nop
xor %r8, %r8
mov (%r15), %di
lea oracles, %rdx
and $0xff, %rdi
shlq $12, %rdi
mov (%rdx,%rdi,1), %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r15
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WT', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}}
{'src': {'type': 'addresses_WC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': True, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}}
{'src': {'type': 'addresses_D', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC', 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}}
[Faulty Load]
{'src': {'type': 'addresses_WT', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32, 'NT': True, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1, 'NT': True, 'same': False, 'congruent': 10}}
{'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': True}}
{'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 8}}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0xf319, %r9
nop
nop
nop
and %r13, %r13
movw $0x6162, (%r9)
nop
nop
nop
nop
and $35916, %rdi
lea addresses_A_ht+0x12233, %rsi
lea addresses_A_ht+0xa3fd, %rdi
nop
nop
nop
nop
sub $6447, %r15
mov $8, %rcx
rep movsq
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_D_ht+0x19d8f, %rcx
nop
nop
and $16852, %rdi
mov $0x6162636465666768, %rsi
movq %rsi, %xmm1
movups %xmm1, (%rcx)
nop
nop
and $36026, %r15
lea addresses_normal_ht+0x40fd, %rcx
nop
nop
nop
nop
cmp $22526, %rdi
mov (%rcx), %si
nop
nop
xor %rsi, %rsi
lea addresses_WC_ht+0xdd7d, %rdi
clflush (%rdi)
nop
nop
nop
nop
cmp %rcx, %rcx
mov (%rdi), %r9w
nop
nop
xor $9286, %rax
lea addresses_A_ht+0xfd77, %rsi
lea addresses_WC_ht+0xdefd, %rdi
nop
nop
nop
cmp $25473, %r10
mov $73, %rcx
rep movsq
nop
nop
nop
nop
nop
add %r15, %r15
lea addresses_WT_ht+0x1e12d, %rsi
lea addresses_normal_ht+0xdb85, %rdi
nop
nop
add %r15, %r15
mov $97, %rcx
rep movsw
dec %rcx
lea addresses_D_ht+0x68fd, %rsi
lea addresses_A_ht+0xae5d, %rdi
clflush (%rdi)
nop
nop
and %r13, %r13
mov $119, %rcx
rep movsw
dec %r13
lea addresses_normal_ht+0x1d87d, %r15
nop
nop
nop
nop
sub $15570, %r10
movb (%r15), %al
nop
nop
nop
xor $43670, %r10
lea addresses_UC_ht+0x1055d, %rdi
nop
nop
nop
nop
nop
sub %r10, %r10
vmovups (%rdi), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $1, %xmm4, %r13
nop
nop
nop
dec %rdi
lea addresses_D_ht+0x12256, %rcx
nop
nop
nop
nop
nop
inc %r13
movl $0x61626364, (%rcx)
nop
nop
nop
sub $46339, %r10
lea addresses_WC_ht+0x7dfd, %rsi
lea addresses_A_ht+0x1cf3d, %rdi
clflush (%rsi)
nop
nop
nop
add %r9, %r9
mov $53, %rcx
rep movsb
nop
nop
and $62387, %rcx
lea addresses_normal_ht+0x14b21, %rcx
nop
inc %r15
mov $0x6162636465666768, %r13
movq %r13, %xmm4
vmovups %ymm4, (%rcx)
add $54744, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r13
push %rbp
push %rcx
push %rdi
// Store
lea addresses_D+0x8efd, %r10
nop
nop
nop
nop
and %r13, %r13
movw $0x5152, (%r10)
nop
nop
nop
inc %rdi
// Store
lea addresses_RW+0xc4b5, %rcx
nop
nop
nop
nop
sub %rbp, %rbp
movl $0x51525354, (%rcx)
xor $47630, %rcx
// Faulty Load
lea addresses_RW+0xe0fd, %rbp
clflush (%rbp)
nop
nop
nop
nop
nop
inc %r11
vmovups (%rbp), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $0, %xmm0, %r12
lea oracles, %rbp
and $0xff, %r12
shlq $12, %r12
mov (%rbp,%r12,1), %r12
pop %rdi
pop %rcx
pop %rbp
pop %r13
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D'}}
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_RW'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_normal_ht'}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
; A256818: Number of length n+3 0..1 arrays with at most two downsteps in every n consecutive neighbor pairs.
; 16,32,64,128,245,442,753,1220,1894,2836,4118,5824,8051,10910,14527,19044,24620,31432,39676,49568,61345,75266,91613,110692,132834,158396,187762,221344,259583,302950,351947,407108,469000,538224,615416,701248,796429,901706,1017865,1145732,1286174,1440100,1608462,1792256,1992523,2210350,2446871,2703268,2980772,3280664,3604276,3952992,4328249,4731538,5164405,5628452,6125338,6656780,7224554,7830496,8476503,9164534,9896611,10674820,11501312,12378304,13308080,14292992,15335461,16437978,17603105,18833476,20131798,21500852,22943494,24462656,26061347,27742654,29509743,31365860,33314332,35358568,37502060,39748384,42101201,44564258,47141389,49836516,52653650,55596892,58670434,61878560,65225647,68716166,72354683,76145860,80094456,84205328,88483432,92933824
mov $2,$0
add $2,5
bin $2,$0
mov $4,$0
mul $0,10
add $0,$2
add $0,6
mov $5,11
add $5,$0
mov $1,$5
sub $1,2
mov $3,$4
mul $3,$4
mul $3,$4
add $1,$3
mov $0,$1
|
; A047391: Numbers that are congruent to {1, 3, 5} mod 7.
; 1,3,5,8,10,12,15,17,19,22,24,26,29,31,33,36,38,40,43,45,47,50,52,54,57,59,61,64,66,68,71,73,75,78,80,82,85,87,89,92,94,96,99,101,103,106,108,110,113,115,117,120,122,124,127,129,131,134,136,138,141,143,145,148,150,152,155,157,159,162,164,166,169,171,173,176,178,180,183,185,187,190,192,194,197,199,201,204,206,208,211,213,215,218,220,222,225,227,229,232
mul $0,7
div $0,3
add $0,1
|
; A190957: a(n) = 10*a(n-1) + 8*a(n-2), with a(0)=0, a(1)=1.
; Submitted by Jamie Morken(s4)
; 0,1,10,108,1160,12464,133920,1438912,15460480,166116096,1784844800,19177376768,206052526080,2213944274944,23787862958080,255590183780352,2746204741468160,29506768884924416,317037326780989440,3406427418889289728,36600572803140812800,393257147382522445824,4225376056250350960640,45399817741563689172992,487801185865639699415040,5241210400588906507534336,56314513492814182670663680,605074818132853078766911488,6501264289271044249034424320,69853241437773267120479535104,750542528691901025197070745600
mov $1,1
lpb $0
sub $0,1
mov $2,$3
mul $2,8
mul $3,10
add $3,$1
mov $1,$2
lpe
mov $0,$3
|
; A206687: Number of n X 2 0..3 arrays with no element equal to another within two positions in the same row or column, and new values 0..3 introduced in row major order.
; 1,4,11,36,116,376,1216,3936,12736,41216,133376,431616,1396736,4519936,14626816,47333376,153174016,495681536,1604059136,5190844416,16797925376,54359228416,175910158336,569257230336,1842155094016,5961339109376,19291298594816,62427953627136,202021101633536,653754017775616,2115592442085376,6846200955273216,22154771678887936,71694347178868736,232007781073289216,750792950862053376,2429617026017263616,7862405855482740736,25443279815034535936,82336183052000034816,266445485364138213376,862235702936276566016,2790253347329105985536,9029449506403318235136,29219912402123060412416,94557622829859393765376,305994895268211029180416,990220281855859633422336,3204420144784563383566336,10369721416992565300822016,33557123413123384135909376,108593132494217029475106816,351414758640927595493851136,1137202047258723308888129536,3680063129081156999751663616,11908934447197207235055845376,38538121410719042469118345216,124711980610226913878460071936,403576446863329997633393524736,1306000816167567650780627337216,4226307419788455292094828773376,13676618104247181187312166895616,44258465887648183543003648884736,143223404192285091835255965351936,463480671935162917842526526242816,1499854960639466203026076913893376,4853632609019584077422259932758016,15706685060597032966948827521089536,50827900557272402243586694773211136,164482541356932936354968699630780416,532276684942955481684284178354405376
seq $0,162770 ; a(n) = ((2+sqrt(5))*(1+sqrt(5))^n + (2-sqrt(5))*(1-sqrt(5))^n)/2.
mov $1,$0
div $1,2
sub $0,$1
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
%>
<%docstring>sigpending(set) -> str
Invokes the syscall sigpending.
See 'man 2 sigpending' for more information.
Arguments:
set(sigset_t*): set
Returns:
int
</%docstring>
<%page args="set=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['set']
argument_values = [set]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, str):
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_sigpending']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* sigpending(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtimer.h"
#include "qabstracteventdispatcher.h"
#include "qcoreapplication.h"
#include "qobject_p.h"
QT_BEGIN_NAMESPACE
/*!
\class QTimer
\inmodule QtCore
\brief The QTimer class provides repetitive and single-shot timers.
\ingroup events
The QTimer class provides a high-level programming interface for
timers. To use it, create a QTimer, connect its timeout() signal
to the appropriate slots, and call start(). From then on, it will
emit the timeout() signal at constant intervals.
Example for a one second (1000 millisecond) timer (from the
\l{widgets/analogclock}{Analog Clock} example):
\snippet ../widgets/widgets/analogclock/analogclock.cpp 4
\snippet ../widgets/widgets/analogclock/analogclock.cpp 5
\snippet ../widgets/widgets/analogclock/analogclock.cpp 6
From then on, the \c update() slot is called every second.
You can set a timer to time out only once by calling
setSingleShot(true). You can also use the static
QTimer::singleShot() function to call a slot after a specified
interval:
\snippet timers/timers.cpp 3
In multithreaded applications, you can use QTimer in any thread
that has an event loop. To start an event loop from a non-GUI
thread, use QThread::exec(). Qt uses the timer's
\l{QObject::thread()}{thread affinity} to determine which thread
will emit the \l{QTimer::}{timeout()} signal. Because of this, you
must start and stop the timer in its thread; it is not possible to
start a timer from another thread.
As a special case, a QTimer with a timeout of 0 will time out as
soon as all the events in the window system's event queue have
been processed. This can be used to do heavy work while providing
a snappy user interface:
\snippet timers/timers.cpp 4
\snippet timers/timers.cpp 5
\snippet timers/timers.cpp 6
From then on, \c processOneThing() will be called repeatedly. It
should be written in such a way that it always returns quickly
(typically after processing one data item) so that Qt can deliver
events to the user interface and stop the timer as soon as it has done all
its work. This is the traditional way of implementing heavy work
in GUI applications, but as multithreading is nowadays becoming available on
more and more platforms, we expect that zero-millisecond
QTimers will gradually be replaced by \l{QThread}s.
\section1 Accuracy and Timer Resolution
The accuracy of timers depends on the underlying operating system
and hardware. Most platforms support a resolution of 1 millisecond,
though the accuracy of the timer will not equal this resolution
in many real-world situations.
The accuracy also depends on the \l{Qt::TimerType}{timer type}. For
Qt::PreciseTimer, QTimer will try to keep the accurance at 1 millisecond.
Precise timers will also never time out earlier than expected.
For Qt::CoarseTimer and Qt::VeryCoarseTimer types, QTimer may wake up
earlier than expected, within the margins for those types: 5% of the
interval for Qt::CoarseTimer and 500 ms for Qt::VeryCoarseTimer.
All timer types may time out later than expected if the system is busy or
unable to provide the requested accuracy. In such a case of timeout
overrun, Qt will emit activated() only once, even if multiple timeouts have
expired, and then will resume the original interval.
\section1 Alternatives to QTimer
An alternative to using QTimer is to call QObject::startTimer()
for your object and reimplement the QObject::timerEvent() event
handler in your class (which must inherit QObject). The
disadvantage is that timerEvent() does not support such
high-level features as single-shot timers or signals.
Another alternative is QBasicTimer. It is typically less
cumbersome than using QObject::startTimer()
directly. See \l{Timers} for an overview of all three approaches.
Some operating systems limit the number of timers that may be
used; Qt tries to work around these limitations.
\sa QBasicTimer, QTimerEvent, QObject::timerEvent(), Timers,
{Analog Clock Example}, {Wiggly Example}
*/
static const int INV_TIMER = -1; // invalid timer id
/*!
Constructs a timer with the given \a parent.
*/
QTimer::QTimer(QObject *parent)
: QObject(parent), id(INV_TIMER), inter(0), del(0), single(0), nulltimer(0), type(Qt::CoarseTimer)
{
}
/*!
Destroys the timer.
*/
QTimer::~QTimer()
{
if (id != INV_TIMER) // stop running timer
stop();
}
/*!
\fn void QTimer::timeout()
This signal is emitted when the timer times out.
\sa interval, start(), stop()
*/
/*!
\property QTimer::active
\since 4.3
This boolean property is \c true if the timer is running; otherwise
false.
*/
/*!
\fn bool QTimer::isActive() const
Returns \c true if the timer is running (pending); otherwise returns
false.
*/
/*!
\fn int QTimer::timerId() const
Returns the ID of the timer if the timer is running; otherwise returns
-1.
*/
/*! \overload start()
Starts or restarts the timer with the timeout specified in \l interval.
If the timer is already running, it will be
\l{QTimer::stop()}{stopped} and restarted.
If \l singleShot is true, the timer will be activated only once.
*/
void QTimer::start()
{
if (id != INV_TIMER) // stop running timer
stop();
nulltimer = (!inter && single);
id = QObject::startTimer(inter, Qt::TimerType(type));
}
/*!
Starts or restarts the timer with a timeout interval of \a msec
milliseconds.
If the timer is already running, it will be
\l{QTimer::stop()}{stopped} and restarted.
If \l singleShot is true, the timer will be activated only once.
*/
void QTimer::start(int msec)
{
inter = msec;
start();
}
/*!
Stops the timer.
\sa start()
*/
void QTimer::stop()
{
if (id != INV_TIMER) {
QObject::killTimer(id);
id = INV_TIMER;
}
}
/*!
\reimp
*/
void QTimer::timerEvent(QTimerEvent *e)
{
if (e->timerId() == id) {
if (single)
stop();
emit timeout(QPrivateSignal());
}
}
class QSingleShotTimer : public QObject
{
Q_OBJECT
int timerId;
bool hasValidReceiver;
QPointer<const QObject> receiver;
QtPrivate::QSlotObjectBase *slotObj;
public:
~QSingleShotTimer();
QSingleShotTimer(int msec, Qt::TimerType timerType, const QObject *r, const char * m);
QSingleShotTimer(int msec, Qt::TimerType timerType, const QObject *r, QtPrivate::QSlotObjectBase *slotObj);
Q_SIGNALS:
void timeout();
protected:
void timerEvent(QTimerEvent *);
};
QSingleShotTimer::QSingleShotTimer(int msec, Qt::TimerType timerType, const QObject *r, const char *member)
: QObject(QAbstractEventDispatcher::instance()), hasValidReceiver(true), slotObj(0)
{
timerId = startTimer(msec, timerType);
connect(this, SIGNAL(timeout()), r, member);
}
QSingleShotTimer::QSingleShotTimer(int msec, Qt::TimerType timerType, const QObject *r, QtPrivate::QSlotObjectBase *slotObj)
: QObject(QAbstractEventDispatcher::instance()), hasValidReceiver(r), receiver(r), slotObj(slotObj)
{
timerId = startTimer(msec, timerType);
if (r && thread() != r->thread()) {
// We need the invocation to happen in the receiver object's thread.
// So, move QSingleShotTimer to the correct thread. Before that occurs, we
// shall remove the parent from the object.
setParent(0);
moveToThread(r->thread());
// Given we're also parentless now, we should take defence against leaks
// in case the application quits before we expire.
connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &QObject::deleteLater);
}
}
QSingleShotTimer::~QSingleShotTimer()
{
if (timerId > 0)
killTimer(timerId);
if (slotObj)
slotObj->destroyIfLastRef();
}
void QSingleShotTimer::timerEvent(QTimerEvent *)
{
// need to kill the timer _before_ we emit timeout() in case the
// slot connected to timeout calls processEvents()
if (timerId > 0)
killTimer(timerId);
timerId = -1;
if (slotObj) {
// If the receiver was destroyed, skip this part
if (Q_LIKELY(!receiver.isNull() || !hasValidReceiver)) {
// We allocate only the return type - we previously checked the function had
// no arguments.
void *args[1] = { 0 };
slotObj->call(const_cast<QObject*>(receiver.data()), args);
}
} else {
emit timeout();
}
// we would like to use delete later here, but it feels like a
// waste to post a new event to handle this event, so we just unset the flag
// and explicitly delete...
qDeleteInEventHandler(this);
}
/*!
\internal
Implementation of the template version of singleShot
\a msec is the timer interval
\a timerType is the timer type
\a receiver is the receiver object, can be null. In such a case, it will be the same
as the final sender class.
\a slot a pointer only used when using Qt::UniqueConnection
\a slotObj the slot object
*/
void QTimer::singleShotImpl(int msec, Qt::TimerType timerType,
const QObject *receiver,
QtPrivate::QSlotObjectBase *slotObj)
{
new QSingleShotTimer(msec, timerType, receiver, slotObj);
}
/*!
\reentrant
This static function calls a slot after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
Example:
\snippet code/src_corelib_kernel_qtimer.cpp 0
This sample program automatically terminates after 10 minutes
(600,000 milliseconds).
The \a receiver is the receiving object and the \a member is the
slot. The time interval is \a msec milliseconds.
\sa start()
*/
void QTimer::singleShot(int msec, const QObject *receiver, const char *member)
{
// coarse timers are worst in their first firing
// so we prefer a high precision timer for something that happens only once
// unless the timeout is too big, in which case we go for coarse anyway
singleShot(msec, msec >= 2000 ? Qt::CoarseTimer : Qt::PreciseTimer, receiver, member);
}
/*! \overload
\reentrant
This static function calls a slot after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The \a receiver is the receiving object and the \a member is the slot. The
time interval is \a msec milliseconds. The \a timerType affects the
accuracy of the timer.
\sa start()
*/
void QTimer::singleShot(int msec, Qt::TimerType timerType, const QObject *receiver, const char *member)
{
if (Q_UNLIKELY(msec < 0)) {
qWarning("QTimer::singleShot: Timers cannot have negative timeouts");
return;
}
if (receiver && member) {
if (msec == 0) {
// special code shortpath for 0-timers
const char* bracketPosition = strchr(member, '(');
if (!bracketPosition || !(member[0] >= '0' && member[0] <= '2')) {
qWarning("QTimer::singleShot: Invalid slot specification");
return;
}
QByteArray methodName(member+1, bracketPosition - 1 - member); // extract method name
QMetaObject::invokeMethod(const_cast<QObject *>(receiver), methodName.constData(), Qt::QueuedConnection);
return;
}
(void) new QSingleShotTimer(msec, timerType, receiver, member);
}
}
/*!\fn void QTimer::singleShot(int msec, const QObject *receiver, PointerToMemberFunction method)
\since 5.4
\overload
\reentrant
This static function calls a member function of a QObject after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The \a receiver is the receiving object and the \a method is the member function. The
time interval is \a msec milliseconds.
If \a receiver is destroyed before the interval occurs, the method will not be called.
The function will be run in the thread of \a receiver. The receiver's thread must have
a running Qt event loop.
\sa start()
*/
/*!\fn void QTimer::singleShot(int msec, Qt::TimerType timerType, const QObject *receiver, PointerToMemberFunction method)
\since 5.4
\overload
\reentrant
This static function calls a member function of a QObject after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The \a receiver is the receiving object and the \a method is the member function. The
time interval is \a msec milliseconds. The \a timerType affects the
accuracy of the timer.
If \a receiver is destroyed before the interval occurs, the method will not be called.
The function will be run in the thread of \a receiver. The receiver's thread must have
a running Qt event loop.
\sa start()
*/
/*!\fn void QTimer::singleShot(int msec, Functor functor)
\since 5.4
\overload
\reentrant
This static function calls \a functor after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The time interval is \a msec milliseconds.
\sa start()
*/
/*!\fn void QTimer::singleShot(int msec, Qt::TimerType timerType, Functor functor)
\since 5.4
\overload
\reentrant
This static function calls \a functor after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The time interval is \a msec milliseconds. The \a timerType affects the
accuracy of the timer.
\sa start()
*/
/*!\fn void QTimer::singleShot(int msec, const QObject *context, Functor functor)
\since 5.4
\overload
\reentrant
This static function calls \a functor after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The time interval is \a msec milliseconds.
If \a context is destroyed before the interval occurs, the method will not be called.
The function will be run in the thread of \a context. The context's thread must have
a running Qt event loop.
\sa start()
*/
/*!\fn void QTimer::singleShot(int msec, Qt::TimerType timerType, const QObject *context, Functor functor)
\since 5.4
\overload
\reentrant
This static function calls \a functor after a given time interval.
It is very convenient to use this function because you do not need
to bother with a \l{QObject::timerEvent()}{timerEvent} or
create a local QTimer object.
The time interval is \a msec milliseconds. The \a timerType affects the
accuracy of the timer.
If \a context is destroyed before the interval occurs, the method will not be called.
The function will be run in the thread of \a context. The context's thread must have
a running Qt event loop.
\sa start()
*/
/*!
\property QTimer::singleShot
\brief whether the timer is a single-shot timer
A single-shot timer fires only once, non-single-shot timers fire
every \l interval milliseconds.
\sa interval, singleShot()
*/
/*!
\property QTimer::interval
\brief the timeout interval in milliseconds
The default value for this property is 0. A QTimer with a timeout
interval of 0 will time out as soon as all the events in the window
system's event queue have been processed.
Setting the interval of an active timer changes its timerId().
\sa singleShot
*/
void QTimer::setInterval(int msec)
{
inter = msec;
if (id != INV_TIMER) { // create new timer
QObject::killTimer(id); // restart timer
id = QObject::startTimer(msec, Qt::TimerType(type));
}
}
/*!
\property QTimer::remainingTime
\since 5.0
\brief the remaining time in milliseconds
Returns the timer's remaining value in milliseconds left until the timeout.
If the timer is inactive, the returned value will be -1. If the timer is
overdue, the returned value will be 0.
\sa interval
*/
int QTimer::remainingTime() const
{
if (id != INV_TIMER) {
return QAbstractEventDispatcher::instance()->remainingTime(id);
}
return -1;
}
/*!
\property QTimer::timerType
\brief controls the accuracy of the timer
The default value for this property is \c Qt::CoarseTimer.
\sa Qt::TimerType
*/
QT_END_NAMESPACE
#include "qtimer.moc"
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>symlinkat(from_, tofd, to) -> str
Invokes the syscall symlinkat.
See 'man 2 symlinkat' for more information.
Arguments:
from(char*): from
tofd(int): tofd
to(char*): to
Returns:
int
</%docstring>
<%page args="from_=0, tofd=0, to=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['from', 'to']
can_pushstr_array = []
argument_names = ['from_', 'tofd', 'to']
argument_values = [from_, tofd, to]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_symlinkat']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* symlinkat(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
Name: kart-data-j.asm
Type: file
Size: 12297
Last-Modified: '1992-07-30T08:29:43Z'
SHA-1: 9B98BC80BF39377C20605E2F9827D3F33DE58581
Description: null
|
; A199214: 3*5^n+1.
; 4,16,76,376,1876,9376,46876,234376,1171876,5859376,29296876,146484376,732421876,3662109376,18310546876,91552734376,457763671876,2288818359376,11444091796876,57220458984376,286102294921876,1430511474609376,7152557373046876,35762786865234376,178813934326171876,894069671630859376,4470348358154296876,22351741790771484376,111758708953857421876,558793544769287109376,2793967723846435546876,13969838619232177734376,69849193096160888671876,349245965480804443359376,1746229827404022216796876,8731149137020111083984376,43655745685100555419921876,218278728425502777099609376,1091393642127513885498046876,5456968210637569427490234376,27284841053187847137451171876,136424205265939235687255859376,682121026329696178436279296876,3410605131648480892181396484376,17053025658242404460906982421876,85265128291212022304534912109376,426325641456060111522674560546876,2131628207280300557613372802734376,10658141036401502788066864013671876,53290705182007513940334320068359376,266453525910037569701671600341796876
mov $1,5
pow $1,$0
mul $1,3
add $1,1
mov $0,$1
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>get_kernel_syms(table) -> str
Invokes the syscall get_kernel_syms.
See 'man 2 get_kernel_syms' for more information.
Arguments:
table(kernel_sym*): table
Returns:
int
</%docstring>
<%page args="table=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['table']
argument_values = [table]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_get_kernel_syms']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* get_kernel_syms(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
.global s_prepare_buffers
s_prepare_buffers:
push %r8
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x17a9d, %rbx
nop
nop
nop
nop
nop
sub $40835, %rdx
mov $0x6162636465666768, %rax
movq %rax, (%rbx)
inc %rcx
lea addresses_WT_ht+0xce3d, %rdx
nop
nop
nop
nop
add %r8, %r8
mov (%rdx), %ax
nop
nop
nop
nop
sub $30115, %rdx
lea addresses_UC_ht+0xe83d, %rdi
nop
nop
nop
nop
nop
cmp %rbp, %rbp
movups (%rdi), %xmm4
vpextrq $1, %xmm4, %rcx
nop
sub $1031, %r8
lea addresses_WT_ht+0xbc3d, %rbp
nop
add %r8, %r8
mov (%rbp), %rdi
nop
nop
nop
and $54745, %rcx
lea addresses_WT_ht+0xd5bd, %rsi
lea addresses_normal_ht+0x1153d, %rdi
clflush (%rsi)
nop
nop
dec %rdx
mov $78, %rcx
rep movsb
nop
nop
nop
nop
nop
add $13648, %r8
lea addresses_normal_ht+0x3dbd, %rbp
nop
nop
nop
nop
nop
sub $53169, %rax
vmovups (%rbp), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rdi
nop
xor $49549, %rsi
lea addresses_A_ht+0x3d95, %rbx
add $22325, %r8
mov (%rbx), %ax
xor $26203, %rbp
lea addresses_UC_ht+0x383d, %rsi
lea addresses_normal_ht+0xf83d, %rdi
nop
nop
nop
nop
nop
sub $49202, %rbp
mov $62, %rcx
rep movsq
and %r8, %r8
lea addresses_UC_ht+0x141fd, %rbx
nop
nop
nop
nop
inc %rdx
mov $0x6162636465666768, %rcx
movq %rcx, %xmm5
movups %xmm5, (%rbx)
nop
sub $64802, %r8
lea addresses_normal_ht+0xe1b5, %r8
nop
nop
nop
nop
nop
and $37379, %rsi
mov (%r8), %ax
nop
cmp $17170, %rdx
lea addresses_WC_ht+0x1949d, %rdi
nop
nop
nop
inc %rcx
mov (%rdi), %r8d
nop
nop
nop
nop
add $32186, %rsi
lea addresses_A_ht+0x1b03d, %rsi
lea addresses_WC_ht+0x703d, %rdi
nop
nop
nop
nop
nop
add %r8, %r8
mov $106, %rcx
rep movsq
nop
nop
nop
nop
nop
xor %rax, %rax
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r8
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r14
push %r9
push %rbp
push %rcx
push %rsi
// Load
lea addresses_normal+0x146fd, %rsi
nop
add %r11, %r11
mov (%rsi), %r9
nop
nop
nop
nop
nop
add %r11, %r11
// Faulty Load
lea addresses_WT+0x1183d, %rbp
cmp $25082, %r13
movb (%rbp), %r11b
lea oracles, %r13
and $0xff, %r11
shlq $12, %r11
mov (%r13,%r11,1), %r11
pop %rsi
pop %rcx
pop %rbp
pop %r9
pop %r14
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 6, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 4, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 11, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
; A071246: a(n) = n*(n - 1)*(2*n^2 + n + 2)/6.
; 0,0,4,23,76,190,400,749,1288,2076,3180,4675,6644,9178,12376,16345,21200,27064,34068,42351,52060,63350,76384,91333,108376,127700,149500,173979,201348,231826,265640,303025,344224,389488,439076,493255,552300,616494,686128,761501,842920,930700,1025164,1126643,1235476,1352010,1476600,1609609,1751408,1902376,2062900,2233375,2414204,2605798,2808576,3022965,3249400,3488324,3740188,4005451,4284580,4578050,4886344,5209953,5549376,5905120,6277700,6667639,7075468,7501726,7946960,8411725,8896584,9402108,9928876,10477475,11048500,11642554,12260248,12902201,13569040,14261400,14979924,15725263,16498076,17299030,18128800,18988069,19877528,20797876,21749820,22734075,23751364,24802418,25887976,27008785,28165600,29359184,30590308,31859751,33168300,34516750,35905904,37336573,38809576,40325740,41885900,43490899,45141588,46838826,48583480,50376425,52218544,54110728,56053876,58048895,60096700,62198214,64354368,66566101,68834360,71160100,73544284,75987883,78491876,81057250,83685000,86376129,89131648,91952576,94839940,97794775,100818124,103911038,107074576,110309805,113617800,116999644,120456428,123989251,127599220,131287450,135055064,138903193,142832976,146845560,150942100,155123759,159391708,163747126,168191200,172725125,177350104,182067348,186878076,191783515,196784900,201883474,207080488,212377201,217774880,223274800,228878244,234586503,240400876,246322670,252353200,258493789,264745768,271110476,277589260,284183475,290894484,297723658,304672376,311742025,318934000,326249704,333690548,341257951,348953340,356778150,364733824,372821813,381043576,389400580,397894300,406526219,415297828,424210626,433266120,442465825,451811264,461303968,470945476,480737335,490681100,500778334,511030608,521439501,532006600,542733500,553621804,564673123,575889076,587271290,598821400,610541049,622431888,634495576,646733780,659148175,671740444,684512278,697465376,710601445,723922200,737429364,751124668,765009851,779086660,793356850,807822184,822484433,837345376,852406800,867670500,883138279,898811948,914693326,930784240,947086525,963602024,980332588,997280076,1014446355,1031833300,1049442794,1067276728,1085337001,1103625520,1122144200,1140894964,1159879743,1179100476,1198559110,1218257600,1238197909,1258382008,1278811876
lpb $0
add $4,$0
sub $0,1
add $2,$4
sub $2,1
add $3,$0
add $4,$3
add $5,5
add $3,$5
lpe
add $1,$2
|
/**
* \copyright
* Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
* \file CreateLiquidFlowMaterialProperties.cpp
*
* Created on December 14, 2016, 1:20 PM
*/
#include "CreateLiquidFlowMaterialProperties.h"
#include "BaseLib/Algorithm.h"
#include "BaseLib/ConfigTree.h"
#include "MeshLib/PropertyVector.h"
#include "MaterialLib/Fluid/FluidProperty.h"
#include "MaterialLib/PorousMedium/Permeability/Permeability.h"
#include "MaterialLib/PorousMedium/Porosity/Porosity.h"
#include "MaterialLib/PorousMedium/Storage/Storage.h"
#include "MaterialLib/Fluid/FluidProperties/CreateFluidProperties.h"
#include "MaterialLib/Fluid/FluidPropertyHeaders.h"
#include "MaterialLib/PorousMedium/PorousPropertyHeaders.h"
#include "ProcessLib/Utils/ProcessUtils.h"
#include "LiquidFlowMaterialProperties.h"
namespace ProcessLib
{
namespace LiquidFlow
{
class LiquidFlowMaterialProperties;
std::unique_ptr<LiquidFlowMaterialProperties>
createLiquidFlowMaterialProperties(
BaseLib::ConfigTree const& config,
std::vector<std::unique_ptr<ParameterBase>> const& parameters,
MeshLib::PropertyVector<int> const* const material_ids)
{
DBUG("Reading material properties of liquid flow process.");
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__fluid}
auto const& fluid_config = config.getConfigSubtree("fluid");
auto fluid_properties =
MaterialLib::Fluid::createFluidProperties(fluid_config);
// Get porous properties
std::vector<std::unique_ptr<MaterialLib::PorousMedium::Permeability>>
intrinsic_permeability_models;
std::vector<std::unique_ptr<MaterialLib::PorousMedium::Porosity>>
porosity_models;
std::vector<std::unique_ptr<MaterialLib::PorousMedium::Storage>>
storage_models;
std::vector<int> mat_ids;
auto const& porous_medium_configs =
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium}
config.getConfigSubtree("porous_medium");
for (
auto const& porous_medium_config :
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium}
porous_medium_configs.getConfigSubtreeList("porous_medium"))
{
//! \ogs_file_attr{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__id}
auto const id = porous_medium_config.getConfigAttribute<int>("id");
mat_ids.push_back(id);
auto const& permeability_config =
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__permeability}
porous_medium_config.getConfigSubtree("permeability");
intrinsic_permeability_models.emplace_back(
MaterialLib::PorousMedium::createPermeabilityModel(
permeability_config, parameters));
auto const& porosity_config =
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__porosity}
porous_medium_config.getConfigSubtree("porosity");
auto n = MaterialLib::PorousMedium::createPorosityModel(porosity_config,
parameters);
porosity_models.emplace_back(std::move(n));
auto const& storage_config =
//! \ogs_file_param{prj__processes__process__LIQUID_FLOW__material_property__porous_medium__porous_medium__storage}
porous_medium_config.getConfigSubtree("storage");
auto beta =
MaterialLib::PorousMedium::createStorageModel(storage_config);
storage_models.emplace_back(std::move(beta));
}
BaseLib::reorderVector(intrinsic_permeability_models, mat_ids);
BaseLib::reorderVector(porosity_models, mat_ids);
BaseLib::reorderVector(storage_models, mat_ids);
return std::make_unique<LiquidFlowMaterialProperties>(
std::move(fluid_properties), std::move(intrinsic_permeability_models),
std::move(porosity_models), std::move(storage_models), material_ids);
}
} // namespace LiquidFlow
} // namespace ProcessLib
|
; A158684: a(n) = 64*n^2 - 1.
; Submitted by Christian Krause
; 63,255,575,1023,1599,2303,3135,4095,5183,6399,7743,9215,10815,12543,14399,16383,18495,20735,23103,25599,28223,30975,33855,36863,39999,43263,46655,50175,53823,57599,61503,65535,69695,73983,78399,82943,87615,92415,97343,102399,107583,112895,118335,123903,129599,135423,141375,147455,153663,159999,166463,173055,179775,186623,193599,200703,207935,215295,222783,230399,238143,246015,254015,262143,270399,278783,287295,295935,304703,313599,322623,331775,341055,350463,359999,369663,379455,389375,399423
add $0,1
pow $0,2
mul $0,64
sub $0,1
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld b, 91
call lwaitly_b
ld a, b1
ldff(40), a
ld a, 0f
ldff(4b), a
ld c, 41
ld b, 03
lbegin_waitm3:
ldff a, (c)
and a, b
cmp a, b
jrnz lbegin_waitm3
ld a, 20
ldff(c), a
xor a, a
ldff(0f), a
ld a, 02
ldff(ff), a
ei
ld a, 03
ldff(43), a
.text@1000
lstatint:
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ld a, 91
ldff(40), a
.text@1036
ldff a, (c)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
; A335756: A cup filling problem starting with 2 empty cups of sizes 3 and n, where a(n) is the number of unreachable states (see details in comments).
; 2,0,2,12,6,8,22,12,14,32,18,20,42,24,26,52,30,32,62,36,38,72,42,44,82,48,50,92,54,56,102,60,62,112,66,68,122,72,74,132,78,80,142,84,86,152,90,92,162,96,98,172,102,104,182,108,110,192,114,116,202,120,122,212,126,128,222
mov $1,$0
gcd $1,3
add $1,2
mov $2,3
add $2,$0
mul $1,$2
sub $1,12
div $1,3
mul $1,2
|
; A159288: Expansion of (1+x+x^2)/(1-x^2-2*x^3).
; Submitted by Jamie Morken(s2)
; 1,1,2,3,4,7,10,15,24,35,54,83,124,191,290,439,672,1019,1550,2363,3588,5463,8314,12639,19240,29267,44518,67747,103052,156783,238546,362887,552112,839979,1277886,1944203,2957844,4499975,6846250,10415663,15846200,24108163,36677526,55800563,84893852,129155615,196494978,298943319,454806208,691933275,1052692846,1601545691,2436559396,3706931383,5639650778,8580050175,13053513544,19859351731,30213613894,45966378819,69932317356,106393606607,161865074994,246258241319,374652288208,569988391307,867168770846
mov $1,1
mov $2,2
lpb $0
sub $0,1
mov $3,$4
mov $4,$1
mov $1,$2
mul $3,2
add $2,$3
sub $4,$3
add $1,$4
lpe
mov $0,$2
div $0,2
|
; A141980: Primes congruent to 4 mod 29.
; Submitted by Jon Maiga
; 149,439,613,787,1019,1193,1367,1483,1657,1831,1889,2063,2179,2237,2411,3049,3571,3803,3919,4093,4441,4673,4789,5021,5659,5717,6007,6529,6703,6761,7109,7283,7457,7573,8269,8443,8501,8849,9371,9661,9719,10009,10067,10357,10531,10589,10937,11633,11807,11923,11981,12097,12329,12503,12619,12967,13721,14011,14243,14533,14591,14939,15287,15461,15809,16273,16447,17027,17317,17491,17839,18013,18593,19231,19289,19463,19753,19927,20101,20333,20507,20681,21319,21377,21493,21841,22073,22189,22247,22769
mov $2,$0
add $2,2
pow $2,2
lpb $2
mul $1,$4
mov $3,$1
sub $1,5
add $3,32
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,63
sub $2,1
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
sub $0,25
|
%include "TiberianSun.inc"
%include "macros/patch.inc"
%include "macros/datatypes.inc"
;;; When Charges=Yes, this patch allows the structure to shoot even on low power
@CLEAR 0x00435271, 0x90, 0x00435287
|
$include 'maxr$'
$include 'tgpdef/asm'
$ascii
$info 1 3 . quarter-word sensitive
. Version 1
. Just print qual*filenames and DAD counts.
. No selection, no sorting.
. I assume the MFD extact file is assigned,
. because MFDEDT should have just run.
. (We'll polish this later.)
$(2) $lit
thestack stackgen 50
idpkt i$dpkt 'IDBUFF' 'MFRAGS 1R1'
mindads $res 1
$(1)
start
lx x4,(1,thestack) . load stack pointer
la a15,a5 . save program options
i$d idpkt
er err$
er aprint$
call getparam . Get parameter from call line
sa a0,mindads . minimum DADs we care about
call openextract . return file count, or 0 on error
jz a0,err1
lr r4,a0 . r4 = file count
jgd r4,$+1
loop1
call dofile . process next file
jgd r4,loop1
. call summary
er exit$
err1 . Failed to file a good, readable MFD extract.
aprint 'open failed'
er err$
/
$(2)
inforbuf res 50
param res 2
$(1)
. getparam: Read INFOR table and return the binary value of field 010106
getparam
beginsub
i$nfor 'RINF$',50,inforbuf
j badinfor
i$nfor 'SINF$',010106
j usage
. ds a0,param
. e$dit edpkt
. e$msg ($cfs('PARAM: &'ld))
. e$fd2 param
. e$print
. a0,a1 = field 010106
. a3 = char count
call fdbin . a0 = parameter
endsub
badinfor
aprint 'MFRAGS must be called as a processor.'
er exit$
usage
aprint 'usage: @MFRAGS <mindads>'
er exit$
/
$(2)
iopkt i$od '$MFDB$',r$ 1792,iobuff 0
iobuff $res 1792
cursect $res 1 . next mfd sector we need to look at
curbuff $res 1 . sector addr of loaded track
$(1)
mflabl $equf 0 . fields in MFD extract header
mfflct $equf 1
mfflad $equf 4
mfqual $equf 0 . fields in MFD file record
mffile $equf 2
mftype $equf 12,,s6
mmtape $equ 1
mfcycl $equf 19,,h2
. Read the file header, verify that the label is good.
. Save the sector address of the first file record.
. Return the file count.
openextract
beginsub
pushregs x5
call openmfd . open and read first track
lx x5,a0 . x5 -> sector 0
la a0,mflabl,x5
te a0,($cfs('*MFDB*')) . look like an MFD extract?
j openerr2
la a0,mfflad,x5
sa a0,cursect . remember where to start files
top a15,(option('D')) . if debug on
j open01
a$edit aedpkt
a$emsg msgfilect
a$edecv mfflct,x5
a$eprint
open01
la a0,iobuff+1 . return file count
popregs
endsub
openerr2
aprint 'ERROR: Invalid MFD extract header'
l$snap 'a0',2
er err$
/
$(1)
. dofile: Return a pointer to a packet that describes the next file
. in the MFD extract. At entry, a call to 'readcur' should fetch
. what should be a file record. DAD records should immediately
. follow it.
. Packet to hold file information:
fqual $equf 0
fname $equf 2
fcyc $equf 4,,h1
fdads $equf 4,,h2
fholes $equf 5,,h1 . we don't count holes yet
ftape $equf 5,,h2
$(2)
filenum + 0 . not used any more
dofilepkt $res 6
. Read current record. It must be a file record.
. Read next record until you find another file record.
$(1)
dofile
beginsub
pushregs x5,x6
inc filenum . bump file number for msg
nop
call readcur . a0 -> record
tnz,h1 fqual,a0 . error if not a file record
er err$
lx,u x5,dofilepkt . save file info for processing
sz ftape,x5 . assume not a tape
sz fdads,x5 . dads = 0
sz fholes,x5 . holes = 0
la a2,mftype,a0
tep,u a2,mmtape . is this a tape file?
sp1 ftape,x5 . yes, remember that
dl a2,mfqual,a0
tne a2,($cfs('*EOF**')) . should never find the EOF
er err$
ds a2,fqual,x5 . save qual
dl a2,mffile,a0
ds a2,fname,x5 . save filename
la a2,mfcycl,a0
sa a2,fcyc,x5 . save f-cycle
dofile01 . loop over DAD tables
call readnext . a0 -> following record
tz,h1 fqual,a0 . if zero, it's a DAD table
j dofile10 . it's another file record. Stop
tz ftape,x5 . was this a tape file?
j dofilerr . that's not good
. a0 -> DAD table
call countdads . returns dad count in this table
aa a0,fdads,x5
sa a0,fdads,x5 . update total dad count
. aprint 'got DAD table' . debug
j dofile01
dofile10 . finished reading DAD tables
tz ftape,x5 . is this a tape file?
j dofile20 . yes, don't print anything
la a0,fdads,x5
tle a0,mindads . enough DADs to show?
j dofile20 . no -> dofile20
e$dit edpkt . print file, cycle, dad count
e$decf 3,fdads,x5
e$char $cfs(' ')
e$fd2 fqual,x5
e$char $cfs('*')
e$fd2 fname,x5
e$char $cfs('(')
e$decv fcyc,x5
e$char $cfs(')')
e$print
dofile20
popregs
endsub
dofilerr
aprint 'ERROR: Tape file has DAD tables.'
er err$
. countdads: return a0 = count of DADs in the DAD table a0 points to
. We don't count holes as DADs.
countdads
beginsub
pushregs x5
lx x5,a0 . x5 -> DAD table
tep a15,(option('D'))
call printdadt
la a0,x5
aa,u a0,4 . point to first DAD
lr,u r1,8-1 . max 8 DADs per table
la,u a2,0 . DADs so far
dadloop
la,h2 a1,2,a0 . get LDAT
top,u a1,0400000 . is this a hole?
aa,u a2,1 . no, bump DAD count
la,h1 a1,2,a0 . DAD flags
tep,u a1,4 . last DAD in this table?
j daddone . yes -> daddone
aa,u a0,3 . a0 -> next DAD
jgd r1,dadloop
daddone
la a0,a2 . return DAD count
popregs
endsub
. printdadt: print contents of DAD table
. a0 -> DAD table
printdadt
beginsub
pushregs x5,r5
lx x5,a0
ax,u x5,4 . x5 -> first DAD
lr,u r5,8-1
printd01
a$edit aedpkt
la,h2 a0,2,x5
tep,u a0,0400000
j printd03
a$efd1 ('FRAG')
j printd04
printd03
a$efd1 ('HOLE')
printd04
a$echar ' '
a$edecv 1,x5
a$eprint
la,h1 a0,2,x5
tep,u a0,4 . last DAD?
j printd02 . yes
ax,u x5,3
jgd r5,printd01
printd02
popregs
endsub
/
$(1)
summary
beginsub
aprint 'do we have any'
endsub
/
. I/O functions to read the MFD extract file.
. Three functions:
. 1. openmfd - opens file and sets 'cursect' to 0.
. 2. readcur - returns a pointer to sector 'cursect'
. 3. readnext - increments 'cursect' and return ptr to that sector.
.
. We read in track-size chunks, and fetch another one when necessary
openmfd
beginsub
la,u a0,iopkt
er iow$ . read track 0
tz,s1 iopkt+3 . good I/O?
j openerr1
sz cursect . sector 0 is current
sz curbuff . track 0 is loaded
call readcur . a0 -> sector 0
endsub
openerr1
aprint 'ERROR: I/O error reading header'
er err$
. Just increment cursect and call readcur
readnext
beginsub
inc cursect . Make cursect get the next one
nop
call readcur . a0 -> record
endsub
. If the 'cursect' is not loaded, fetch the track that contains it.
. Then return a pointer to the requested sector.
readcur
beginsub
. top a15,(option('D'))
j readc01
a$edit aedpkt
a$emsg ('read &/&'ld)
a$edecv cursect
a$emsgr
a$edecv curbuff
a$eprint
readc01
la a0,cursect . needed track = (cursect//64)*64
ssl a0,6
lssl a0,6
tne a0,curbuff . do we have that one?
j readgotit . yes, no I/O necessary
. a0 = sector address we want to read
sa a0,iopkt+5 . set I/O address
sa a0,curbuff . remember what track we loaded
. top a15,(option('D'))
j readc03
a$edit aedpkt . debug msg
a$emsg ('I/O :&'ld)
a$edecv iopkt+5
a$eprint
readc03
la,u a0,iopkt
er iow$ . read the track
tz,s1 iopkt+5 . check I/O status
er err$
readgotit . return a0 -> current sector
la a0,cursect
ana a0,curbuff . a0 = sector offset into buffer
msi,u a0,28 . times words/sector
aa,u a0,iobuff . a0 -> current sector
endsub
/
$(1)
. I stole this code from MFDEDT. I couldn't bear doing it from scratch.
. a0,a1 = Fieldata representation of a number, LJSF
. a3 = character count
fdbin
beginsub
ANA,U A3,1 . FIND - DECR CHAR COUNT FOR LOOP
LA,U A5,0 . INIT ACCUMULATOR = 0
DE052
LDSC A0,6 . NEXT CHAR TO A1 LOWER
AND,U A1,077 . ISOLATE CHAR IN A2
ANA,U A2,$cfs('0') . CONVERT TO BINARY
TG,U A2,0 . CHECK FOR LEGAL RANGE, 0-9
TG,U A2,9+1 .
J usage
MSI,U A5,10 . MULT ACCUMULATOR BY TEN
AA,U A5,,A2 . AND ADD IN NEXT DIGIT
JGD A3,DE052 . BACK FOR NEXT DIGIT
la a0,a5
endsub
/
$(2) . Global data
aedpkt a$editpkt 33,edline
edpkt e$ditpkt 22,edline
edline $res 33
msgfilect 'File count = &'
end start
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ie_preprocess_gapi_kernels.hpp"
#include "ie_preprocess_gapi_kernels_impl.hpp"
#if CPU_SIMD
#include "ie_system_conf.h"
#ifdef HAVE_AVX512
#include "cpu_x86_avx512/ie_preprocess_gapi_kernels_avx512.hpp"
#endif
#ifdef HAVE_AVX2
#include "cpu_x86_avx2/ie_preprocess_gapi_kernels_avx2.hpp"
#endif
#ifdef HAVE_SSE
#include "cpu_x86_sse42/ie_preprocess_gapi_kernels_sse42.hpp"
#endif
#endif
#ifdef HAVE_NEON
#include "arm_neon/ie_preprocess_gapi_kernels_neon.hpp"
#endif
#include <opencv2/gapi/opencv_includes.hpp>
#include <opencv2/gapi/fluid/gfluidkernel.hpp>
#include <opencv2/gapi/gcompoundkernel.hpp>
#include <algorithm>
#include <type_traits>
#include <utility>
#include <vector>
#include <functional>
#if defined(__GNUC__) && (__GNUC__ <= 5)
#include <cmath>
#endif
namespace InferenceEngine {
namespace gapi {
//using namespace kernels;
namespace kernels {
namespace {
struct fp_16_t {
int16_t v;
};
template<typename type>
struct cv_type_to_depth;
template<> struct cv_type_to_depth<std::uint8_t> { enum { depth = CV_8U }; };
template<> struct cv_type_to_depth<std::int8_t> { enum { depth = CV_8S }; };
template<> struct cv_type_to_depth<std::uint16_t> { enum { depth = CV_16U }; };
template<> struct cv_type_to_depth<std::int16_t> { enum { depth = CV_16S }; };
template<> struct cv_type_to_depth<std::int32_t> { enum { depth = CV_32S }; };
template<> struct cv_type_to_depth<float> { enum { depth = CV_32F }; };
template<> struct cv_type_to_depth<fp_16_t> { enum { depth = CV_16F }; };
template<typename ... types>
struct typelist {};
template<typename type_list>
struct head;
template<template<typename ...> class list, typename head_t, typename ... types>
struct head<list<head_t, types...>> { using type = head_t;};
template<typename typelist>
using head_t = typename head<typelist>::type;
template<typename type>
struct type_to_type {};
template <typename typelist>
struct type_dispatch_impl;
//FIXME: add test for type_dispatch
template <template<typename ...> class typelist, typename... type>
struct type_dispatch_impl<typelist<type...>> {
template <typename result_t, typename default_t, typename type_id_t, typename type_to_id_t, typename type_to_value_t>
static result_t dispatch(type_id_t type_id, type_to_id_t&& type_to_id, type_to_value_t&& type_to_value, default_t default_value) {
result_t res = default_value;
bool matched = false;
std::initializer_list<int> ({
!matched && (type_id == type_to_id(type_to_type<type>{})) ?
(matched = true, res = type_to_value(type_to_type<type>{})), 0
: 0
...
});
return res;
}
template <typename result_t, typename default_t, typename pred_t, typename type_to_value_t>
static result_t dispatch(pred_t&& pred, type_to_value_t&& type_to_value, default_t default_value) {
result_t res = default_value;
bool matched = false;
std::initializer_list<int> ({
!matched && pred(type_to_type<type>{}) ?
(matched = true, res = type_to_value(type_to_type<type>{})), 0
: 0
...
});
return res;
}
};
template<typename left_typelsist, typename right_typelsist>
struct concat;
template<typename left_typelsist, typename right_typelsist>
using concat_t = typename concat<left_typelsist, right_typelsist>::type;
template<template<typename ...> class left_list, typename ... left_types, template<typename ...> class right_list, typename ... right_types>
struct concat<left_list<left_types...>, right_list<right_types...>>{
using type = left_list<left_types... , right_types...>;
};
template< class T, class U >
using is_same_t = typename std::is_same<T, U>::type;
template<bool C, class T, class E> struct if_c_impl;
template<class T, class E> struct if_c_impl<true, T, E> {
using type = T;
};
template<class T, class E> struct if_c_impl<false, T, E> {
using type = E;
};
template<bool C, class T, class E>
using if_c = typename if_c_impl<C, T, E>::type;
template<class C, class T, class E>
using if_ = typename if_c_impl<C::value != 0, T, E>::type;
template<typename typelist, typename type>
struct remove;
template<typename typelist, typename type>
using remove_t = typename remove<typelist, type>::type;
template<template<typename ...> class list, typename head_t, typename ... types, typename t>
struct remove<list<head_t, types...>, t> {
using type = concat_t<
if_<is_same_t<head_t, t>, list<>, list<head_t>>,
remove_t<list<types...>, t>
>;
};
template<template<typename ...> class list, typename t>
struct remove<list<>, t> {
using type = list<>;
};
} // namespace
template <typename typelist, typename default_t, typename type_id_t, typename type_to_id_t, typename type_to_value_t,
typename result_t = decltype(std::declval<type_to_value_t>()(type_to_type<head_t<typelist>> {}))>
result_t type_dispatch(type_id_t type_id, type_to_id_t&& type_to_id, type_to_value_t&& type_to_value, default_t default_value = {}) {
return type_dispatch_impl<typelist>::template dispatch<result_t>(std::forward<type_id_t>(type_id),
std::forward<type_to_id_t>(type_to_id),
std::forward<type_to_value_t>(type_to_value),
std::forward<default_t>(default_value));
}
template <typename typelist, typename default_t, typename pred_t, typename type_to_value_t,
typename result_t = decltype(std::declval<type_to_value_t>()(type_to_type<head_t<typelist>> {}))>
result_t type_dispatch(pred_t&& pred, type_to_value_t&& type_to_value, default_t default_value = {}) {
return type_dispatch_impl<typelist>::template dispatch<result_t>(std::forward<pred_t>(pred),
std::forward<type_to_value_t>(type_to_value),
std::forward<default_t>(default_value));
}
namespace {
struct cv_type_id {
template <typename type>
const int operator()(type_to_type<type> ) { return cv_type_to_depth<type>::depth;}
};
} // namespace
template <typename typelist>
bool is_cv_type_in_list(const int type_id) {
return type_dispatch<typelist>(type_id, cv_type_id{}, [](...){ return true;}, false);
}
namespace {
using merge_supported_types = typelist<uint8_t, int8_t, uint16_t, int16_t, int32_t, float, fp_16_t>;
template<typename T, int chs>
void mergeRowImpl(scalar_tag, const std::array<const T*, chs>& ins, T* out, const int length) {
for (int x = 0; x < length; ++x) {
for (int c = 0; c < chs; ++c) {
out[chs * x + c] = ins[c][x];
}
}
}
template<typename isa_tag_t, int chs>
struct typed_merge_row {
using p_f = void (*)(const std::array<const uint8_t*, chs>& ins, uint8_t* out, const int length);
template <typename type>
typename std::enable_if<std::is_same<isa_tag_t, scalar_tag>::value ||
(!std::is_same<isa_tag_t, scalar_tag>::value && !std::is_same<type, uint8_t>::value &&
!std::is_same<type, float>::value), p_f>::type
operator()(type_to_type<type> ) {
return [](const std::array<const uint8_t*, chs>& ins, uint8_t* out, const int length) {
const auto inT = reinterpret_cast<const std::array<const type*, chs>&>(ins);
auto outT = reinterpret_cast<type*>(out);
scalar_tag t;
mergeRowImpl<type, chs>(t, inT, outT, length);
};
}
template<typename tag = isa_tag_t>
typename std::enable_if<!std::is_same<tag, scalar_tag>::value, p_f>::type
operator()(type_to_type<uint8_t>) {
return [](const std::array<const uint8_t*, chs>& ins, uint8_t* out, const int length) {
tag t;
mergeRowImpl<tag, uint8_t, chs>(t, ins, out, length);
};
}
template<typename tag = isa_tag_t>
typename std::enable_if<!std::is_same<tag, scalar_tag>::value, p_f>::type
operator()(type_to_type<float>) {
return [](const std::array<const uint8_t*, chs>& ins, uint8_t* out, const int length) {
const auto inT = reinterpret_cast<const std::array<const float*, chs>&>(ins);
auto outT = reinterpret_cast<float*>(out);
tag t;
mergeRowImpl<tag, float, chs>(t, inT, outT, length);
};
}
};
} // namespace
namespace {
using split_supported_types = typelist<uint8_t, int8_t, uint16_t, int16_t, int32_t, float, fp_16_t>;
template<typename T, int chs>
void splitRowImpl(scalar_tag, const T* in, std::array<T*, chs>& outs, const int length) {
for (int x = 0; x < length; ++x) {
for (int c = 0; c < chs; ++c) {
outs[c][x] = in[chs * x + c];
}
}
}
template<typename isa_tag_t, int chs>
struct typed_split_row {
using p_f = void (*)(const uint8_t* in, std::array<uint8_t*, chs>& outs, const int length);
template <typename type>
typename std::enable_if<std::is_same<isa_tag_t, scalar_tag>::value ||
(!std::is_same<isa_tag_t, scalar_tag>::value && !std::is_same<type, uint8_t>::value &&
!std::is_same<type, float>::value), p_f>::type
operator()(type_to_type<type> ) {
return [](const uint8_t* in, std::array<uint8_t*, chs>& outs, const int length) {
const auto inT = reinterpret_cast<const type*>(in);
auto outT = reinterpret_cast<std::array<type*, chs>&>(outs);
scalar_tag t;
splitRowImpl<type, chs>(t, inT, outT, length);
};
}
template<typename tag = isa_tag_t>
typename std::enable_if<!std::is_same<tag, scalar_tag>::value, p_f>::type
operator()(type_to_type<uint8_t>) {
return [](const uint8_t* in, std::array<uint8_t*, chs>& outs, const int length) {
tag t;
splitRowImpl<tag, uint8_t, chs>(t, in, outs, length);
};
}
template<typename tag = isa_tag_t>
typename std::enable_if<!std::is_same<tag, scalar_tag>::value, p_f>::type
operator()(type_to_type<float>) {
return [](const uint8_t* in, std::array<uint8_t*, chs>& outs, const int length) {
const auto inT = reinterpret_cast<const float*>(in);
auto outT = reinterpret_cast<std::array<float*, chs>&>(outs);
tag t;
splitRowImpl<tag, float, chs>(t, inT, outT, length);
};
}
};
} // namespace
//----------------------------------------------------------------------
using isas_set = typelist<
#ifdef HAVE_AVX512
avx512_tag,
#endif
#ifdef HAVE_AVX2
avx2_tag,
#endif
#ifdef HAVE_SSE
sse42_tag,
#endif
#ifdef HAVE_NEON
neon_tag,
#endif
//scalar "ISA" have to be the last one in the list,
//as the search for supported ISA is performed until first match
scalar_tag>;
#ifdef HAVE_AVX512
bool is_present(avx512_tag) { return with_cpu_x86_avx512f(); }
#endif // HAVE_AVX512
#ifdef HAVE_AVX2
bool is_present(avx2_tag) { return with_cpu_x86_avx2(); }
#endif // HAVE_AVX2
#ifdef HAVE_SSE
bool is_present(sse42_tag) { return with_cpu_x86_sse42(); }
#endif // HAVE_SSE
#ifdef HAVE_NEON
bool is_present(neon_tag) { return true; }
#endif // HAVE_NEON
//scalar version of kernels is always available
bool is_present(scalar_tag) { return true; }
struct is_isa_present {
template< typename isa_tag_t>
bool operator()(type_to_type<isa_tag_t>) {
return is_present(isa_tag_t{});
}
};
// GAPI_OCV_KERNEL(OCVChanToPlane, ChanToPlane) {
// static void run(const cv::Mat &in, int chan, cv::Mat &out) {
// out.create(in.rows, in.cols, in.depth());
// const auto rowFunc = (in.depth() == CV_8U) ? &chanToPlaneRow<uint8_t> : &chanToPlaneRow<float>;
// for (int y = 0; y < out.rows; y++)
// {
// rowFunc(in.data + y*in.step, chan, in.channels(), out.data + y*out.step, in.cols);
// }
// }
// };
// GAPI_OCV_KERNEL(OCVScalePlane, ScalePlane) {
// static void run(const cv::Mat &in, int /*type*/, const Size &sz, int interp, cv::Mat &out) {
// cv::resize(in, out, sz, 0, 0, interp);
// }
// };
// GAPI_OCV_KERNEL(OCVMerge2, Merge2) {
// static void run(const cv::Mat &a, const cv::Mat &b, cv::Mat out) {
// out.create(a.rows, a.cols, CV_MAKETYPE(a.depth(), 2));
// const auto rowFunc = (a.depth() == CV_8U) ? &mergeRow<uint8_t, 2> : &mergeRow<float, 2>;
// for (int y = 0; y < out.rows; y++)
// {
// rowFunc({a.data + y*a.step, b.data + y*b.step}, out.data + out.step, a.cols);
// }
// }
// };
namespace {
using chan_to_plane_supported_types = typelist<uint8_t, float>;
template<typename T>
void chanToPlaneRowImpl(scalar_tag, const T* in, int chan, int chs, T* out, int length) {
for (int x = 0; x < length; x++) {
out[x] = in[x*chs + chan];
}
}
template<typename isa_tag_t>
struct typed_chan_to_plane_row {
using p_f = void (*)(const uint8_t* in, int chan, int chs, uint8_t* out, int length);
template <typename type>
p_f operator()(type_to_type<type> ) {
return [](const uint8_t* in, int chan, int chs, uint8_t* out, int length){
const auto inT = reinterpret_cast<const type*>(in);
auto outT = reinterpret_cast< type*>(out);
chanToPlaneRowImpl(isa_tag_t{}, inT, chan, chs, outT, length);
};
}
};
} //namespace
namespace {
using nv12_to_rgb_supported_types = typelist<uint8_t>;
void nv12ToRgbRowImpl(scalar_tag, const uint8_t** y_rows, const uint8_t* uv_row,
uint8_t** out_rows, const int buf_width) {
for (int i = 0; i < buf_width; i += 2) {
uint8_t u = uv_row[i];
uint8_t v = uv_row[i + 1];
int ruv, guv, buv;
uvToRGBuv(u, v, ruv, guv, buv);
for (int y = 0; y < 2; y++) {
for (int x = 0; x < 2; x++) {
uint8_t vy = y_rows[y][i + x];
uint8_t r, g, b;
yRGBuvToRGB(vy, ruv, guv, buv, r, g, b);
out_rows[y][3 * (i + x)] = r;
out_rows[y][3 * (i + x) + 1] = g;
out_rows[y][3 * (i + x) + 2] = b;
}
}
}
}
template<typename isa_tag_t>
struct typed_nv12_to_rgb_row {
using p_f = void (*)(const uint8_t** y_rows, const uint8_t* uv_row,
uint8_t** out_rows, const int buf_width);
template <typename type>
p_f operator()(type_to_type<type>) {
return [](const uint8_t** y_rows, const uint8_t* uv_row,
uint8_t** out_rows, const int buf_width) {
const auto inT1 = reinterpret_cast<const type**>(y_rows);
const auto inT2 = reinterpret_cast<const type*>(uv_row);
auto outT = reinterpret_cast<type**>(out_rows);
nv12ToRgbRowImpl(isa_tag_t{}, inT1, inT2, outT, buf_width);
};
}
};
} // namespace
namespace {
using i420_to_rgb_supported_types = typelist<uint8_t>;
static void i420ToRgbRowImpl(scalar_tag, const uint8_t** y_rows,
const uint8_t* u_row,
const uint8_t* v_row,
uint8_t** out_rows,
const int buf_width) {
for (int i = 0; i < buf_width; i += 2) {
uchar u = u_row[i / 2];
uchar v = v_row[i / 2];
int ruv, guv, buv;
uvToRGBuv(u, v, ruv, guv, buv);
for (int y = 0; y < 2; y++) {
for (int x = 0; x < 2; x++) {
uchar vy = y_rows[y][i + x];
uchar r, g, b;
yRGBuvToRGB(vy, ruv, guv, buv, r, g, b);
out_rows[y][3 * (i + x)] = r;
out_rows[y][3 * (i + x) + 1] = g;
out_rows[y][3 * (i + x) + 2] = b;
}
}
}
}
template<typename isa_tag_t>
struct typed_i420_to_rgb_row {
using p_f = void (*)(const uint8_t** y_rows, const uint8_t* u_row, const uint8_t* v_row,
uint8_t** out_rows, const int buf_width);
template <typename type>
p_f operator()(type_to_type<type>) {
return [](const uint8_t** y_rows, const uint8_t* u_row, const uint8_t* v_row,
uint8_t** out_rows, const int buf_width) {
const auto inT1 = reinterpret_cast<const type**>(y_rows);
const auto inT2 = reinterpret_cast<const type*>(u_row);
const auto inT3 = reinterpret_cast<const type*>(v_row);
auto outT = reinterpret_cast<type**>(out_rows);
i420ToRgbRowImpl(isa_tag_t{}, inT1, inT2, inT3, outT, buf_width);
};
}
};
} // namespace
template <typename isa_tag_t>
struct choose_impl {
GAPI_FLUID_KERNEL(FChanToPlane, ChanToPlane, false) {
static const int Window = 1;
static void run(const cv::gapi::fluid::View& in, int chan,
cv::gapi::fluid::Buffer& out) {
GAPI_DbgAssert(is_cv_type_in_list<chan_to_plane_supported_types>(out.meta().depth));
const auto rowFunc = type_dispatch<chan_to_plane_supported_types>(out.meta().depth, cv_type_id{}, typed_chan_to_plane_row<isa_tag_t>{}, nullptr);
GAPI_DbgAssert(rowFunc);
rowFunc(in.InLineB(0), chan, in.meta().chan, out.OutLineB(), in.length());
}
};
GAPI_FLUID_KERNEL(FNV12toRGB, NV12toRGB, false) {
static const int Window = 1;
static const int LPI = 2;
static const auto Kind = cv::GFluidKernel::Kind::YUV420toRGB;
static void run(const cv::gapi::fluid::View & in_y,
const cv::gapi::fluid::View & in_uv,
cv::gapi::fluid::Buffer & out) {
GAPI_DbgAssert(is_cv_type_in_list<nv12_to_rgb_supported_types>(out.meta().depth));
const uchar* uv_row = in_uv.InLineB(0);
const uchar* y_rows[2] = { in_y.InLineB(0), in_y.InLineB(1) };
uchar* out_rows[2] = { out.OutLineB(0), out.OutLineB(1) };
int buf_width = out.length();
const auto rowFunc = type_dispatch<nv12_to_rgb_supported_types>(out.meta().depth, cv_type_id{}, typed_nv12_to_rgb_row<isa_tag_t>{}, nullptr);
GAPI_DbgAssert(rowFunc);
rowFunc(y_rows, uv_row, out_rows, buf_width);
}
};
GAPI_FLUID_KERNEL(FI420toRGB, I420toRGB, false) {
static const int Window = 1;
static const int LPI = 2;
static const auto Kind = cv::GFluidKernel::Kind::YUV420toRGB;
static void run(const cv::gapi::fluid::View & in_y,
const cv::gapi::fluid::View & in_u,
const cv::gapi::fluid::View & in_v,
cv::gapi::fluid::Buffer & out) {
GAPI_DbgAssert(is_cv_type_in_list<i420_to_rgb_supported_types>(out.meta().depth));
const uchar* u_row = in_u.InLineB(0);
const uchar* v_row = in_v.InLineB(0);
const uchar* y_rows[2] = { in_y.InLineB(0), in_y.InLineB(1) };
uchar* out_rows[2] = { out.OutLineB(0), out.OutLineB(1) };
int buf_width = out.length();
GAPI_DbgAssert(in_u.length() == in_v.length());
const auto rowFunc = type_dispatch<i420_to_rgb_supported_types>(out.meta().depth, cv_type_id{}, typed_i420_to_rgb_row<isa_tag_t>{}, nullptr);
GAPI_DbgAssert(rowFunc);
rowFunc(y_rows, u_row, v_row, out_rows, buf_width);
}
};
GAPI_FLUID_KERNEL(FSplit2, Split2, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & in,
cv::gapi::fluid::Buffer & out1,
cv::gapi::fluid::Buffer & out2) {
GAPI_DbgAssert(2 == in.meta().chan);
GAPI_DbgAssert(1 == out1.meta().chan);
GAPI_DbgAssert(1 == out2.meta().chan);
GAPI_DbgAssert(in.meta().depth == out1.meta().depth);
GAPI_DbgAssert(in.meta().depth == out2.meta().depth);
GAPI_DbgAssert(is_cv_type_in_list<split_supported_types>(in.meta().depth));
const auto rowFunc = type_dispatch<split_supported_types>(in.meta().depth, cv_type_id{}, typed_split_row<isa_tag_t, 2>{}, nullptr);
for (int i = 0, lpi = out1.lpi(); i < lpi; i++) {
std::array<uint8_t*, 2> outs = { out1.OutLineB(i), out2.OutLineB(i) };
rowFunc(in.InLineB(i), outs, in.length());
}
}
};
GAPI_FLUID_KERNEL(FSplit3, Split3, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & in,
cv::gapi::fluid::Buffer & out1,
cv::gapi::fluid::Buffer & out2,
cv::gapi::fluid::Buffer & out3) {
GAPI_DbgAssert(3 == in.meta().chan);
GAPI_DbgAssert(1 == out1.meta().chan);
GAPI_DbgAssert(1 == out2.meta().chan);
GAPI_DbgAssert(1 == out3.meta().chan);
GAPI_DbgAssert(in.meta().depth == out1.meta().depth);
GAPI_DbgAssert(in.meta().depth == out2.meta().depth);
GAPI_DbgAssert(in.meta().depth == out3.meta().depth);
GAPI_DbgAssert(is_cv_type_in_list<split_supported_types>(in.meta().depth));
const auto rowFunc = type_dispatch<split_supported_types>(in.meta().depth, cv_type_id{}, typed_split_row<isa_tag_t, 3>{}, nullptr);
for (int i = 0, lpi = out1.lpi(); i < lpi; i++) {
std::array<uint8_t*, 3> outs = { out1.OutLineB(i), out2.OutLineB(i),
out3.OutLineB(i) };
rowFunc(in.InLineB(i), outs, in.length());
}
}
};
GAPI_FLUID_KERNEL(FSplit4, Split4, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & in,
cv::gapi::fluid::Buffer & out1,
cv::gapi::fluid::Buffer & out2,
cv::gapi::fluid::Buffer & out3,
cv::gapi::fluid::Buffer & out4) {
GAPI_DbgAssert(4 == in.meta().chan);
GAPI_DbgAssert(1 == out1.meta().chan);
GAPI_DbgAssert(1 == out2.meta().chan);
GAPI_DbgAssert(1 == out3.meta().chan);
GAPI_DbgAssert(1 == out4.meta().chan);
GAPI_DbgAssert(in.meta().depth == out1.meta().depth);
GAPI_DbgAssert(in.meta().depth == out2.meta().depth);
GAPI_DbgAssert(in.meta().depth == out3.meta().depth);
GAPI_DbgAssert(in.meta().depth == out4.meta().depth);
GAPI_DbgAssert(is_cv_type_in_list<split_supported_types>(in.meta().depth));
const auto rowFunc = type_dispatch<split_supported_types>(in.meta().depth, cv_type_id{}, typed_split_row<isa_tag_t, 4>{}, nullptr);
for (int i = 0, lpi = out1.lpi(); i < lpi; i++) {
std::array<uint8_t*, 4> outs = { out1.OutLineB(i), out2.OutLineB(i),
out3.OutLineB(i), out4.OutLineB(i) };
rowFunc(in.InLineB(i), outs, in.length());
}
}
};
GAPI_FLUID_KERNEL(FMerge2, Merge2, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & a,
const cv::gapi::fluid::View & b,
cv::gapi::fluid::Buffer & out) {
GAPI_DbgAssert(is_cv_type_in_list<merge_supported_types>(out.meta().depth));
const auto rowFunc = type_dispatch<merge_supported_types>(out.meta().depth, cv_type_id{}, typed_merge_row<isa_tag_t, 2>{}, nullptr);
for (int l = 0; l < out.lpi(); l++) {
rowFunc({ a.InLineB(l), b.InLineB(l) }, out.OutLineB(l), a.length());
}
}
};
GAPI_FLUID_KERNEL(FMerge3, Merge3, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & a,
const cv::gapi::fluid::View & b,
const cv::gapi::fluid::View & c,
cv::gapi::fluid::Buffer & out) {
GAPI_DbgAssert(is_cv_type_in_list<merge_supported_types>(out.meta().depth));
const auto rowFunc = type_dispatch<merge_supported_types>(out.meta().depth, cv_type_id{}, typed_merge_row<isa_tag_t, 3>{}, nullptr);
for (int l = 0; l < out.lpi(); l++) {
rowFunc({ a.InLineB(l), b.InLineB(l), c.InLineB(l) }, out.OutLineB(l), a.length());
}
}
};
GAPI_FLUID_KERNEL(FMerge4, Merge4, false) {
static const int LPI = 4;
static const int Window = 1;
static void run(const cv::gapi::fluid::View & a,
const cv::gapi::fluid::View & b,
const cv::gapi::fluid::View & c,
const cv::gapi::fluid::View & d,
cv::gapi::fluid::Buffer & out) {
GAPI_DbgAssert(is_cv_type_in_list<merge_supported_types>(out.meta().depth));
const auto rowFunc = type_dispatch<merge_supported_types>(out.meta().depth, cv_type_id{}, typed_merge_row<isa_tag_t, 4>{}, nullptr);
for (int l = 0; l < out.lpi(); l++) {
rowFunc({ a.InLineB(l), b.InLineB(l), c.InLineB(l), d.InLineB(l) }, out.OutLineB(l), a.length());
}
}
};
};
namespace {
struct CC_and_MergeISA {
cv::gapi::GKernelPackage& pckg;
CC_and_MergeISA(cv::gapi::GKernelPackage& _pckg) : pckg(_pckg) {}
template<typename isa_tag_t>
bool operator()(type_to_type<isa_tag_t>) {
pckg.include<typename choose_impl<isa_tag_t>::FI420toRGB>();
pckg.include<typename choose_impl<isa_tag_t>::FNV12toRGB>();
pckg.include<typename choose_impl<isa_tag_t>::FChanToPlane>();
pckg.include<typename choose_impl<isa_tag_t>::FMerge2>();
pckg.include<typename choose_impl<isa_tag_t>::FMerge3>();
pckg.include<typename choose_impl<isa_tag_t>::FMerge4>();
//at the moment type_dispatch requires something to be returned by the lambda
return true;
}
};
struct SplitISA {
cv::gapi::GKernelPackage& pckg;
SplitISA(cv::gapi::GKernelPackage& _pckg) : pckg(_pckg) {}
template<typename isa_tag_t>
bool operator()(type_to_type<isa_tag_t>) {
pckg.include<typename choose_impl<isa_tag_t>::FSplit2>();
pckg.include<typename choose_impl<isa_tag_t>::FSplit3>();
pckg.include<typename choose_impl<isa_tag_t>::FSplit4>();
//at the moment type_dispatch requires something to be returned by the lambda
return true;
}
};
} //namespace
cv::gapi::GKernelPackage FKernelsChooseISA() {
// At the moment AVX512 implementation of wide universal intrinsics is slower than AVX2.
// So, disable it for now.
using isas = remove_t<isas_set, avx512_tag>;
cv::gapi::GKernelPackage pckg1, pckg2;
CC_and_MergeISA ccISA{ pckg1 };
SplitISA sISA{ pckg2 };
type_dispatch<isas>(is_isa_present{}, ccISA, false);
type_dispatch<isas_set>(is_isa_present{}, sISA, false);
return combine(pckg1, pckg2);
}
//----------------------------------------------------------------------
G_TYPED_KERNEL(ScalePlane8u, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.scale_plane_8u") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_8U && in.chan == 1);
return in.withSize(sz);
}
};
G_TYPED_KERNEL(ScalePlane32f, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.scale_plane_32f") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_32F && in.chan == 1);
return in.withSize(sz);
}
};
G_TYPED_KERNEL(UpscalePlaneArea8u, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.upscale_plane_area_8u") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_8U && in.chan == 1);
GAPI_DbgAssert(in.size.width < sz.width || in.size.height < sz.height);
return in.withSize(sz);
}
};
G_TYPED_KERNEL(UpscalePlaneArea32f, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.upscale_plane_area_32f") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_32F && in.chan == 1);
GAPI_DbgAssert(in.size.width < sz.width || in.size.height < sz.height);
return in.withSize(sz);
}
};
G_TYPED_KERNEL(ScalePlaneArea8u, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.scale_plane_area_8u") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_8U && in.chan == 1);
GAPI_DbgAssert(in.size.width >= sz.width && in.size.height >= sz.height);
return in.withSize(sz);
}
};
G_TYPED_KERNEL(ScalePlaneArea32f, <cv::GMat(cv::GMat, Size, int)>, "com.intel.ie.scale_plane_area_32f") {
static cv::GMatDesc outMeta(const cv::GMatDesc &in, const Size &sz, int) {
GAPI_DbgAssert(in.depth == CV_32F && in.chan == 1);
GAPI_DbgAssert(in.size.width >= sz.width && in.size.height >= sz.height);
return in.withSize(sz);
}
};
GAPI_COMPOUND_KERNEL(FScalePlane, ScalePlane) {
static cv::GMat expand(cv::GMat in, int type, const Size& szIn, const Size& szOut, int interp) {
GAPI_DbgAssert(CV_8UC1 == type || CV_32FC1 == type);
GAPI_DbgAssert(cv::INTER_AREA == interp || cv::INTER_LINEAR == interp);
if (cv::INTER_AREA == interp) {
bool upscale = szIn.width < szOut.width || szIn.height < szOut.height;
if (CV_8UC1 == type) {
if (upscale)
return UpscalePlaneArea8u::on(in, szOut, interp);
else
return ScalePlaneArea8u::on(in, szOut, interp);
}
if (CV_32FC1 == type) {
if (upscale)
return UpscalePlaneArea32f::on(in, szOut, interp);
else
return ScalePlaneArea32f::on(in, szOut, interp);
}
}
if (cv::INTER_LINEAR == interp) {
if (CV_8UC1 == type) {
return ScalePlane8u::on(in, szOut, interp);
}
if (CV_32FC1 == type) {
return ScalePlane32f::on(in, szOut, interp);
}
}
GAPI_Assert(!"unsupported parameters");
return {};
}
};
static inline double invRatio(int inSz, int outSz) {
return static_cast<double>(outSz) / inSz;
}
static inline double ratio(int inSz, int outSz) {
return 1 / invRatio(inSz, outSz);
}
template<typename T, typename Mapper, int chanNum>
struct linearScratchDesc {
using alpha_t = typename Mapper::alpha_type;
using index_t = typename Mapper::index_type;
alpha_t* alpha;
alpha_t* clone;
index_t* mapsx;
alpha_t* beta;
index_t* mapsy;
T* tmp;
linearScratchDesc(int /*inW*/, int /*inH*/, int outW, int outH, void* data) {
alpha = reinterpret_cast<alpha_t*>(data);
clone = reinterpret_cast<alpha_t*>(alpha + outW);
mapsx = reinterpret_cast<index_t*>(clone + outW*4);
beta = reinterpret_cast<alpha_t*>(mapsx + outW);
mapsy = reinterpret_cast<index_t*>(beta + outH);
tmp = reinterpret_cast<T*> (mapsy + outH*2);
}
static int bufSize(int inW, int /*inH*/, int outW, int outH, int lpi) {
auto size = outW * sizeof(alpha_t) +
outW * sizeof(alpha_t) * 4 + // alpha clones // previous alpha is redundant?
outW * sizeof(index_t) +
outH * sizeof(alpha_t) +
outH * sizeof(index_t) * 2 +
inW * sizeof(T) * lpi * chanNum;
return static_cast<int>(size);
}
};
template<typename T, typename Mapper, int chanNum = 1>
static void initScratchLinear(const cv::GMatDesc& in,
const Size& outSz,
cv::gapi::fluid::Buffer& scratch,
int lpi) {
using alpha_type = typename Mapper::alpha_type;
static const auto unity = Mapper::unity;
auto inSz = in.size;
auto sbufsize = linearScratchDesc<T, Mapper, chanNum>::bufSize(inSz.width, inSz.height, outSz.width, outSz.height, lpi);
Size scratch_size{sbufsize, 1};
cv::GMatDesc desc;
desc.chan = 1;
desc.depth = CV_8UC1;
desc.size = scratch_size;
cv::gapi::fluid::Buffer buffer(desc);
scratch = std::move(buffer);
double hRatio = ratio(in.size.width, outSz.width);
double vRatio = ratio(in.size.height, outSz.height);
linearScratchDesc<T, Mapper, chanNum> scr(inSz.width, inSz.height, outSz.width, outSz.height, scratch.OutLineB());
auto *alpha = scr.alpha;
auto *clone = scr.clone;
auto *index = scr.mapsx;
for (int x = 0; x < outSz.width; x++) {
auto map = Mapper::map(hRatio, 0, in.size.width, x);
auto alpha0 = map.alpha0;
auto index0 = map.index0;
// TRICK:
// Algorithm takes pair of input pixels, sx0'th and sx1'th,
// and compute result as alpha0*src[sx0] + alpha1*src[sx1].
// By definition: sx1 == sx0 + 1 either sx1 == sx0, and
// alpha0 + alpha1 == unity (scaled appropriately).
// Here we modify formulas for alpha0 and sx1: by assuming
// that sx1 == sx0 + 1 always, and patching alpha0 so that
// result remains intact.
// Note that we need in.size.width >= 2, for both sx0 and
// sx0+1 were indexing pixels inside the input's width.
if (map.index1 != map.index0 + 1) {
GAPI_DbgAssert(map.index1 == map.index0);
GAPI_DbgAssert(in.size.width >= 2);
if (map.index0 < in.size.width-1) {
// sx1=sx0+1 fits inside row,
// make sure alpha0=unity and alpha1=0,
// so that result equals src[sx0]*unity
alpha0 = saturate_cast<alpha_type>(unity);
} else {
// shift sx0 to left by 1 pixel,
// and make sure that alpha0=0 and alpha1==1,
// so that result equals to src[sx0+1]*unity
alpha0 = 0;
index0--;
}
}
alpha[x] = alpha0;
index[x] = index0;
for (int l = 0; l < 4; l++) {
clone[4*x + l] = alpha0;
}
}
auto *beta = scr.beta;
auto *index_y = scr.mapsy;
for (int y = 0; y < outSz.height; y++) {
auto mapY = Mapper::map(vRatio, 0, in.size.height, y);
beta[y] = mapY.alpha0;
index_y[y] = mapY.index0;
index_y[outSz.height + y] = mapY.index1;
}
}
template<typename T, class Mapper>
static void calcRowLinear(const cv::gapi::fluid::View & in,
cv::gapi::fluid::Buffer& out,
cv::gapi::fluid::Buffer& scratch) {
using alpha_type = typename Mapper::alpha_type;
auto inSz = in.meta().size;
auto outSz = out.meta().size;
auto inY = in.y();
int length = out.length();
int outY = out.y();
int lpi = out.lpi();
GAPI_DbgAssert(outY + lpi <= outSz.height);
GAPI_DbgAssert(lpi <= 4);
linearScratchDesc<T, Mapper, 1> scr(inSz.width, inSz.height, outSz.width, outSz.height, scratch.OutLineB());
const auto *alpha = scr.alpha;
const auto *clone = scr.clone;
const auto *mapsx = scr.mapsx;
const auto *beta0 = scr.beta;
const auto *mapsy = scr.mapsy;
auto *tmp = scr.tmp;
const auto *beta = beta0 + outY;
const T *src0[4];
const T *src1[4];
T *dst[4];
for (int l = 0; l < lpi; l++) {
auto index0 = mapsy[outY + l] - inY;
auto index1 = mapsy[outSz.height + outY + l] - inY;
src0[l] = in.InLine<const T>(index0);
src1[l] = in.InLine<const T>(index1);
dst[l] = out.OutLine<T>(l);
}
#ifdef HAVE_AVX512
if (with_cpu_x86_avx512_core()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 64 && outSz.width >= 32) {
avx512::calcRowLinear_8UC1(reinterpret_cast<uint8_t**>(dst),
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
if (std::is_same<T, float>::value) {
avx512::calcRowLinear_32F(reinterpret_cast<float**>(dst),
reinterpret_cast<const float**>(src0),
reinterpret_cast<const float**>(src1),
reinterpret_cast<const float*>(alpha),
reinterpret_cast<const int*>(mapsx),
reinterpret_cast<const float*>(beta),
inSz, outSz, lpi);
return;
}
}
#else
(void)tmp;
(void)clone;
#endif
#ifdef HAVE_AVX2
if (with_cpu_x86_avx2()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 32 && outSz.width >= 16) {
avx::calcRowLinear_8UC1(reinterpret_cast<uint8_t**>(dst),
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
if (std::is_same<T, float>::value) {
avx::calcRowLinear_32F(reinterpret_cast<float**>(dst),
reinterpret_cast<const float**>(src0),
reinterpret_cast<const float**>(src1),
reinterpret_cast<const float*>(alpha),
reinterpret_cast<const int*>(mapsx),
reinterpret_cast<const float*>(beta),
inSz, outSz, lpi);
return;
}
}
#endif
#ifdef HAVE_SSE
if (with_cpu_x86_sse42()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 16 && outSz.width >= 8) {
calcRowLinear_8UC1(reinterpret_cast<uint8_t**>(dst),
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
if (std::is_same<T, float>::value) {
calcRowLinear_32F(reinterpret_cast<float**>(dst),
reinterpret_cast<const float**>(src0),
reinterpret_cast<const float**>(src1),
reinterpret_cast<const float*>(alpha),
reinterpret_cast<const int*>(mapsx),
reinterpret_cast<const float*>(beta),
inSz, outSz, lpi);
return;
}
}
#endif // HAVE_SSE
#ifdef HAVE_NEON
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 16 && outSz.width >= 8) {
neon::calcRowLinear_8UC1(reinterpret_cast<uint8_t**>(dst),
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
if (std::is_same<T, float>::value) {
neon::calcRowLinear_32F(reinterpret_cast<float**>(dst),
reinterpret_cast<const float**>(src0),
reinterpret_cast<const float**>(src1),
reinterpret_cast<const float*>(alpha),
reinterpret_cast<const int*>(mapsx),
reinterpret_cast<const float*>(beta),
inSz, outSz, lpi);
return;
}
#endif
for (int l = 0; l < lpi; l++) {
constexpr static const auto unity = Mapper::unity;
auto beta0 = beta[l];
auto beta1 = saturate_cast<alpha_type>(unity - beta[l]);
for (int x = 0; x < length; x++) {
auto alpha0 = alpha[x];
auto alpha1 = saturate_cast<alpha_type>(unity - alpha[x]);
auto sx0 = mapsx[x];
auto sx1 = sx0 + 1;
T tmp0 = calc(beta0, src0[l][sx0], beta1, src1[l][sx0]);
T tmp1 = calc(beta0, src0[l][sx1], beta1, src1[l][sx1]);
dst[l][x] = calc(alpha0, tmp0, alpha1, tmp1);
}
}
}
template<typename T, class Mapper, int numChan>
static void calcRowLinearC(const cv::gapi::fluid::View & in,
std::array<std::reference_wrapper<cv::gapi::fluid::Buffer>, numChan>& out,
cv::gapi::fluid::Buffer& scratch) {
using alpha_type = typename Mapper::alpha_type;
auto inSz = in.meta().size;
auto outSz = out[0].get().meta().size;
auto inY = in.y();
auto outY = out[0].get().y();
auto lpi = out[0].get().lpi();
GAPI_DbgAssert(outY + lpi <= outSz.height);
GAPI_DbgAssert(lpi <= 4);
linearScratchDesc<T, Mapper, numChan> scr(inSz.width, inSz.height, outSz.width, outSz.height, scratch.OutLineB());
const auto *alpha = scr.alpha;
const auto *clone = scr.clone;
const auto *mapsx = scr.mapsx;
const auto *beta0 = scr.beta;
const auto *mapsy = scr.mapsy;
auto *tmp = scr.tmp;
const auto *beta = beta0 + outY;
const T *src0[4];
const T *src1[4];
std::array<std::array<T*, 4>, numChan> dst;
for (int l = 0; l < lpi; l++) {
auto index0 = mapsy[outY + l] - inY;
auto index1 = mapsy[outSz.height + outY + l] - inY;
src0[l] = in.InLine<const T>(index0);
src1[l] = in.InLine<const T>(index1);
for (int c=0; c < numChan; c++) {
dst[c][l] = out[c].get().template OutLine<T>(l);
}
}
#ifdef HAVE_AVX512
if (with_cpu_x86_avx512_core()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 64 && outSz.width >= 32) {
avx512::calcRowLinear_8UC<numChan>(dst,
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
}
#else
(void)tmp;
(void)clone;
#endif
#ifdef HAVE_AVX2
if (with_cpu_x86_avx2()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 32 && outSz.width >= 16) {
avx::calcRowLinear_8UC<numChan>(dst,
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
}
#endif
#ifdef HAVE_SSE
if (with_cpu_x86_sse42()) {
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 16 && outSz.width >= 8) {
calcRowLinear_8UC<numChan>(dst,
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
}
#endif // HAVE_SSE
#ifdef HAVE_NEON
if (std::is_same<T, uint8_t>::value) {
if (inSz.width >= 16 && outSz.width >= 8) {
neon::calcRowLinear_8UC<numChan>(dst,
reinterpret_cast<const uint8_t**>(src0),
reinterpret_cast<const uint8_t**>(src1),
reinterpret_cast<const short*>(alpha),
reinterpret_cast<const short*>(clone),
reinterpret_cast<const short*>(mapsx),
reinterpret_cast<const short*>(beta),
reinterpret_cast<uint8_t*>(tmp),
inSz, outSz, lpi);
return;
}
}
#endif // HAVE_NEON
auto length = out[0].get().length();
for (int l = 0; l < lpi; l++) {
constexpr static const auto unity = Mapper::unity;
auto beta0 = beta[l];
auto beta1 = saturate_cast<alpha_type>(unity - beta[l]);
for (int x = 0; x < length; x++) {
auto alpha0 = alpha[x];
auto alpha1 = saturate_cast<alpha_type>(unity - alpha[x]);
auto sx0 = mapsx[x];
auto sx1 = sx0 + 1;
for (int c = 0; c < numChan; c++) {
auto idx0 = numChan*sx0 + c;
auto idx1 = numChan*sx1 + c;
T tmp0 = calc(beta0, src0[l][idx0], beta1, src1[l][idx0]);
T tmp1 = calc(beta0, src0[l][idx1], beta1, src1[l][idx1]);
dst[c][l][x] = calc(alpha0, tmp0, alpha1, tmp1);
}
}
}
}
//------------------------------------------------------------------------------
namespace linear {
struct Mapper {
typedef short alpha_type;
typedef short index_type;
constexpr static const int unity = ONE;
typedef MapperUnit<short, short> Unit;
static inline Unit map(double ratio, int start, int max, int outCoord) {
float f = static_cast<float>((outCoord + 0.5) * ratio - 0.5);
int s = cvFloor(f);
f -= s;
Unit u;
u.index0 = std::max(s - start, 0);
u.index1 = ((f == 0.0) || s + 1 >= max) ? s - start : s - start + 1;
u.alpha0 = saturate_cast<short>(ONE * (1.0f - f));
u.alpha1 = saturate_cast<short>(ONE * f);
return u;
}
};
} // namespace linear
namespace linear32f {
struct Mapper {
typedef float alpha_type;
typedef int index_type;
constexpr static const float unity = 1;
typedef MapperUnit<float, int> Unit;
static inline Unit map(double ratio, int start, int max, int outCoord) {
float f = static_cast<float>((outCoord + 0.5) * ratio - 0.5);
int s = cvFloor(f);
f -= s;
Unit u;
u.index0 = std::max(s - start, 0);
u.index1 = ((f == 0.0) || s + 1 >= max) ? s - start : s - start + 1;
u.alpha0 = 1.f - f;
u.alpha1 = f;
return u;
}
};
} // namespace linear32f
namespace areaUpscale {
struct Mapper {
typedef short alpha_type;
typedef short index_type;
constexpr static const int unity = ONE;
typedef MapperUnit<short, short> Unit;
static inline Unit map(double ratio, int start, int max, int outCoord) {
int s = cvFloor(outCoord*ratio);
float f = static_cast<float>((outCoord+1) - (s+1)/ratio);
f = f <= 0 ? 0.f : f - cvFloor(f);
Unit u;
u.index0 = std::max(s - start, 0);
u.index1 = ((f == 0.0) || s + 1 >= max) ? s - start : s - start + 1;
u.alpha0 = saturate_cast<short>(ONE * (1.0f - f));
u.alpha1 = saturate_cast<short>(ONE * f);
return u;
}
};
} // namespace areaUpscale
namespace areaUpscale32f {
struct Mapper {
typedef float alpha_type;
typedef int index_type;
constexpr static const float unity = 1;
typedef MapperUnit<float, int> Unit;
static inline Unit map(double ratio, int start, int max, int outCoord) {
int s = cvFloor(outCoord*ratio);
float f = static_cast<float>((outCoord+1) - (s+1)/ratio);
f = f <= 0 ? 0.f : f - cvFloor(f);
Unit u;
u.index0 = std::max(s - start, 0);
u.index1 = ((f == 0.0) || s + 1 >= max) ? s - start : s - start + 1;
u.alpha0 = 1.0f - f;
u.alpha1 = f;
return u;
}
};
} // namespace areaUpscale32f
//------------------------------------------------------------------------------
template<typename A, typename I, typename W>
struct AreaDownMapper {
typedef A alpha_type;
typedef I index_type;
typedef W work_type;
typedef MapperUnit<alpha_type, index_type> Unit;
inline Unit map(int outCoord) {
double inCoord0 = outCoord * ratio;
double inCoord1 = (outCoord + 1) * ratio;
double index0 = std::floor(inCoord0 + 0.001);
double index1 = std::ceil(inCoord1 - 0.001);
double alpha0 = (index0 + 1 - inCoord0) * inv_ratio;
double alpha1 = - (index1 - 1 - inCoord1) * inv_ratio;
GAPI_Assert(0 <= outCoord && outCoord <= outSz-1);
GAPI_Assert(0 <= index0 && index0 < index1 && index1 <= inSz);
Unit unit;
unit.index0 = checked_cast<index_type>(index0);
unit.index1 = checked_cast<index_type>(index1);
unit.alpha0 = convert_cast<alpha_type>(alpha0);
unit.alpha1 = convert_cast<alpha_type>(alpha1);
return unit;
}
int inSz, outSz;
double ratio, inv_ratio;
alpha_type alpha; // == inv_ratio, rounded
void init(int _inSz, int _outSz) {
inSz = _inSz;
outSz = _outSz;
inv_ratio = invRatio(inSz, outSz);
ratio = 1.0 / inv_ratio;
alpha = convert_cast<alpha_type>(inv_ratio);
}
};
namespace areaDownscale32f {
struct Mapper: public AreaDownMapper<float, int, float> {
Mapper(int _inSz, int _outSz) {
init(_inSz, _outSz);
}
};
}
namespace areaDownscale8u {
struct Mapper: public AreaDownMapper<Q0_16, short, Q8_8> {
Mapper(int _inSz, int _outSz) {
init(_inSz, _outSz);
}
};
}
template<typename Mapper>
static void initScratchArea(const cv::GMatDesc& in, const Size& outSz,
cv::gapi::fluid::Buffer &scratch) {
using Unit = typename Mapper::Unit;
using alpha_type = typename Mapper::alpha_type;
using index_type = typename Mapper::index_type;
// compute the chunk of input pixels for each output pixel,
// along with the coefficients for taking the weigthed sum
Size inSz = in.size;
Mapper mapper(inSz.width, outSz.width);
std::vector<Unit> xmaps(outSz.width);
int maxdif = 0;
for (int w = 0; w < outSz.width; w++) {
Unit map = mapper.map(w);
xmaps[w] = map;
int dif = map.index1 - map.index0;
if (dif > maxdif)
maxdif = dif;
}
// This assertion is critical for our trick with chunk sizes:
// we would expand a chunk it is is smaller than maximal size
GAPI_Assert(inSz.width >= maxdif);
// pack the input chunks positions and coefficients into scratch-buffer,
// along with the maximal size of chunk (note that chunk size may vary)
size_t scratch_bytes = sizeof(int)
+ outSz.width * sizeof(index_type)
+ outSz.width * sizeof(alpha_type) * maxdif
+ inSz.width * sizeof(alpha_type);
Size scratch_size{static_cast<int>(scratch_bytes), 1};
cv::GMatDesc desc;
desc.chan = 1;
desc.depth = CV_8UC1;
desc.size = scratch_size;
cv::gapi::fluid::Buffer buffer(desc);
scratch = std::move(buffer);
auto *maxdf = scratch.OutLine<int>();
auto *index = reinterpret_cast<index_type*>(maxdf + 1);
auto *alpha = reinterpret_cast<alpha_type*>(index + outSz.width);
// auto *vbuf = reinterpret_cast<work_type *>(alpha + outSz.width * maxdif);
for (int w = 0; w < outSz.width; w++) {
// adjust input indices so that:
// - data chunk is exactly maxdif pixels
// - data chunk fits inside input width
int index0 = xmaps[w].index0;
int index1 = xmaps[w].index1;
int i0 = index0, i1 = index1;
i1 = (std::min)(i0 + maxdif, in.size.width);
i0 = i1 - maxdif;
GAPI_DbgAssert(i0 >= 0);
// fulfill coefficients for the data chunk,
// extending with zeros if any extra pixels
alpha_type *alphaw = &alpha[w * maxdif];
for (int i = 0; i < maxdif; i++) {
if (i + i0 == index0) {
alphaw[i] = xmaps[w].alpha0;
} else if (i + i0 == index1 - 1) {
alphaw[i] = xmaps[w].alpha1;
} else if (i + i0 > index0 && i + i0 < index1 - 1) {
alphaw[i] = mapper.alpha;
} else {
alphaw[i] = 0;
}
}
// start input chunk with adjusted position
index[w] = i0;
}
*maxdf = maxdif;
}
#if defined __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
template<typename T, typename Mapper>
static void calcAreaRow(const cv::gapi::fluid::View& in, cv::gapi::fluid::Buffer& out,
cv::gapi::fluid::Buffer& scratch) {
using Unit = typename Mapper::Unit;
using alpha_type = typename Mapper::alpha_type;
using index_type = typename Mapper::index_type;
using work_type = typename Mapper::work_type;
Size inSz = in.meta().size;
Size outSz = out.meta().size;
// this method is valid only for down-scale
GAPI_DbgAssert(inSz.width >= outSz.width);
GAPI_DbgAssert(inSz.height >= outSz.height);
// Mapper xmapper(inSz.width, outSz.width);
Mapper ymapper(inSz.height, outSz.height);
auto *xmaxdf = scratch.OutLine<const int>();
auto maxdif = xmaxdf[0];
auto *xindex = reinterpret_cast<const index_type*>(xmaxdf + 1);
auto *xalpha = reinterpret_cast<const alpha_type*>(xindex + outSz.width);
auto *vbuf_c = reinterpret_cast<const work_type*>(xalpha + outSz.width * maxdif);
auto *vbuf = const_cast<work_type*>(vbuf_c);
int iny = in.y();
int y = out.y();
int lpi = out.lpi();
GAPI_DbgAssert(y + lpi <= outSz.height);
for (int l = 0; l < lpi; l++) {
Unit ymap = ymapper.map(y + l);
GAPI_Assert(ymap.index1 - ymap.index0 <= 32);
GAPI_Assert(ymap.index1 - ymap.index0 > 0);
const T *src[32] = {};
for (int yin = ymap.index0; yin < ymap.index1; yin++) {
src[yin - ymap.index0] = in.InLine<const T>(yin - iny);
}
auto dst = out.OutLine<T>(l);
#ifdef HAVE_AVX512
if (with_cpu_x86_avx512f()) {
if (std::is_same<T, uchar>::value) {
avx512::calcRowArea_8U(reinterpret_cast<uchar*>(dst),
reinterpret_cast<const uchar**>(src),
inSz, outSz,
static_cast<Q0_16>(ymapper.alpha),
reinterpret_cast<const MapperUnit8U&>(ymap),
xmaxdf[0],
reinterpret_cast<const short*>(xindex),
reinterpret_cast<const Q0_16*>(xalpha),
reinterpret_cast<Q8_8*>(vbuf));
continue; // next l = 0, ..., lpi-1
}
if (std::is_same<T, float>::value) {
avx512::calcRowArea_32F(reinterpret_cast<float*>(dst),
reinterpret_cast<const float**>(src),
inSz, outSz,
static_cast<float>(ymapper.alpha),
reinterpret_cast<const MapperUnit32F&>(ymap),
xmaxdf[0],
reinterpret_cast<const int*>(xindex),
reinterpret_cast<const float*>(xalpha),
reinterpret_cast<float*>(vbuf));
continue;
}
}
#endif // HAVE_AVX512
#ifdef HAVE_AVX2
if (with_cpu_x86_avx2()) {
if (std::is_same<T, uchar>::value) {
avx::calcRowArea_8U(reinterpret_cast<uchar*>(dst),
reinterpret_cast<const uchar**>(src),
inSz, outSz,
static_cast<Q0_16>(ymapper.alpha),
reinterpret_cast<const MapperUnit8U&>(ymap),
xmaxdf[0],
reinterpret_cast<const short*>(xindex),
reinterpret_cast<const Q0_16*>(xalpha),
reinterpret_cast<Q8_8*>(vbuf));
continue; // next l = 0, ..., lpi-1
}
if (std::is_same<T, float>::value) {
avx::calcRowArea_32F(reinterpret_cast<float*>(dst),
reinterpret_cast<const float**>(src),
inSz, outSz,
static_cast<float>(ymapper.alpha),
reinterpret_cast<const MapperUnit32F&>(ymap),
xmaxdf[0],
reinterpret_cast<const int*>(xindex),
reinterpret_cast<const float*>(xalpha),
reinterpret_cast<float*>(vbuf));
continue;
}
}
#endif // HAVE_AVX2
#ifdef HAVE_SSE
if (with_cpu_x86_sse42()) {
if (std::is_same<T, uchar>::value) {
calcRowArea_8U(reinterpret_cast<uchar*>(dst),
reinterpret_cast<const uchar**>(src),
inSz, outSz,
static_cast<Q0_16>(ymapper.alpha),
reinterpret_cast<const MapperUnit8U&>(ymap),
xmaxdf[0],
reinterpret_cast<const short*>(xindex),
reinterpret_cast<const Q0_16*>(xalpha),
reinterpret_cast<Q8_8*>(vbuf));
continue; // next l = 0, ..., lpi-1
}
if (std::is_same<T, float>::value) {
calcRowArea_32F(reinterpret_cast<float*>(dst),
reinterpret_cast<const float**>(src),
inSz, outSz,
static_cast<float>(ymapper.alpha),
reinterpret_cast<const MapperUnit32F&>(ymap),
xmaxdf[0],
reinterpret_cast<const int*>(xindex),
reinterpret_cast<const float*>(xalpha),
reinterpret_cast<float*>(vbuf));
continue;
}
}
#endif // HAVE_SSE
// vertical pass
int y_1st = ymap.index0;
int ylast = ymap.index1 - 1;
if (y_1st < ylast) {
for (int w = 0; w < inSz.width; w++) {
vbuf[w] = mulas(ymap.alpha0, src[0][w]) // Q8_8 = Q0_16 * U8
+ mulas(ymap.alpha1, src[ylast - y_1st][w]);
}
for (int i = 1; i < ylast - y_1st; i++) {
for (int w = 0; w < inSz.width; w++) {
vbuf[w] += mulas(ymapper.alpha, src[i][w]);
}
}
} else {
for (int w = 0; w < inSz.width; w++) {
vbuf[w] = convert_cast<work_type>(src[0][w]); // Q8_8 = U8
}
}
// horizontal pass
for (int x = 0; x < outSz.width; x++) {
work_type sum = 0;
auto index = xindex[x];
const auto *alpha = &xalpha[x * maxdif];
for (int i = 0; i < maxdif; i++) {
sum += mulaw(alpha[i], vbuf[index + i]); // Q8_8 = Q0_16 * Q8_8
}
dst[x] = convert_cast<T>(sum); // U8 = Q8_8
}
}
}
#if defined __GNUC__
# pragma GCC diagnostic pop
#endif
//----------------------------------------------------------------------
#if USE_CVKL
// taken from: ie_preprocess_data.cpp
static int getResizeAreaTabSize(int dst_go, int ssize, int dsize, float scale) {
static const float threshold = 1e-3f;
int max_count = 0;
for (int col = dst_go; col < dst_go + dsize; col++) {
int count = 0;
float fsx1 = col * scale;
float fsx2 = fsx1 + scale;
int sx1 = static_cast<int>(ceil(fsx1));
int sx2 = static_cast<int>(floor(fsx2));
sx2 = (std::min)(sx2, ssize - 1);
sx1 = (std::min)(sx1, sx2);
if (sx1 - fsx1 > threshold) {
count++;
}
for (int sx = sx1; sx < sx2; sx++) {
count++;
}
if (fsx2 - sx2 > threshold) {
count++;
}
max_count = (std::max)(max_count, count);
}
return max_count;
}
// taken from: ie_preprocess_data.cpp
static void computeResizeAreaTab(int src_go, int dst_go, int ssize, int dsize, float scale,
uint16_t* si, uint16_t* alpha, int max_count) {
static const float threshold = 1e-3f;
int k = 0;
for (int col = dst_go; col < dst_go + dsize; col++) {
int count = 0;
float fsx1 = col * scale;
float fsx2 = fsx1 + scale;
float cellWidth = (std::min)(scale, ssize - fsx1);
int sx1 = static_cast<int>(ceil(fsx1));
int sx2 = static_cast<int>(floor(fsx2));
sx2 = (std::min)(sx2, ssize - 1);
sx1 = (std::min)(sx1, sx2);
si[col - dst_go] = (uint16_t)(sx1 - src_go);
if (sx1 - fsx1 > threshold) {
si[col - dst_go] = (uint16_t)(sx1 - src_go - 1);
alpha[k++] = (uint16_t)((1 << 16) * ((sx1 - fsx1) / cellWidth));
count++;
}
for (int sx = sx1; sx < sx2; sx++) {
alpha[k++] = (uint16_t)((1 << 16) * (1.0f / cellWidth));
count++;
}
if (fsx2 - sx2 > threshold) {
alpha[k++] = (uint16_t)((1 << 16) * ((std::min)((std::min)(fsx2 - sx2, 1.f), cellWidth) / cellWidth));
count++;
}
if (count != max_count) {
alpha[k++] = 0;
}
}
}
// teken from: ie_preprocess_data.cpp
static void generate_alpha_and_id_arrays(int x_max_count, int dcols, const uint16_t* xalpha, uint16_t* xsi,
uint16_t** alpha, uint16_t** sxid) {
if (x_max_count <= 4) {
for (int col = 0; col < dcols; col++) {
for (int x = 0; x < x_max_count; x++) {
alpha[x][col] = xalpha[col*x_max_count + x];
}
}
}
if (x_max_count <= 4) {
for (int col = 0; col <= dcols - 8; col += 8) {
for (int chunk_num_h = 0; chunk_num_h < x_max_count; chunk_num_h++) {
for (int i = 0; i < 128 / 16; i++) {
int id_diff = xsi[col + i] - xsi[col];
for (int chunk_num_v = 0; chunk_num_v < x_max_count; chunk_num_v++) {
uint16_t* sxidp = sxid[chunk_num_v] + col * x_max_count + chunk_num_h * 8;
int id0 = (id_diff + chunk_num_v) * 2 + 0;
int id1 = (id_diff + chunk_num_v) * 2 + 1;
(reinterpret_cast<int8_t*>(sxidp + i))[0] = static_cast<int8_t>(id0 >= (chunk_num_h * 16) && id0 < (chunk_num_h + 1) * 16 ? id0 : -1);
(reinterpret_cast<int8_t*>(sxidp + i))[1] = static_cast<int8_t>(id1 >= (chunk_num_h * 16) && id1 < (chunk_num_h + 1) * 16 ? id1 : -1);
}
}
}
}
}
}
// taken from: ie_preprocess_data.cpp
// (and simplified for specifically downscale area 8u)
static size_t resize_get_buffer_size(const Size& inSz, const Size& outSz) {
int dst_full_width = outSz.width;
int dst_full_height = outSz.height;
int src_full_width = inSz.width;
int src_full_height = inSz.height;
auto resize_area_u8_downscale_sse_buffer_size = [&]() {
const int dwidth = outSz.width;
const int dheight = outSz.height;
const int swidth = inSz.width;
const int dst_go_x = 0;
const int dst_go_y = 0;
int x_max_count = getResizeAreaTabSize(dst_go_x, src_full_width, dwidth, static_cast<float>(src_full_width) / dst_full_width) + 1;
int y_max_count = getResizeAreaTabSize(dst_go_y, src_full_height, dheight, static_cast<float>(src_full_height) / dst_full_height) + 1;
size_t si_buf_size = sizeof(uint16_t) * dwidth + sizeof(uint16_t) * dheight;
size_t alpha_buf_size =
sizeof(uint16_t) * (dwidth * x_max_count + 8 * 16) + sizeof(uint16_t) * dheight * y_max_count;
size_t vert_sum_buf_size = sizeof(uint16_t) * (swidth * 2);
size_t alpha_array_buf_size = sizeof(uint16_t) * 4 * dwidth;
size_t sxid_array_buf_size = sizeof(uint16_t) * 4 * 4 * dwidth;
size_t buffer_size = si_buf_size +
alpha_buf_size +
vert_sum_buf_size +
alpha_array_buf_size +
sxid_array_buf_size;
return buffer_size;
};
return resize_area_u8_downscale_sse_buffer_size();
}
// buffer-fulfill is taken from: ie_preprocess_data_sse42.cpp
static void initScratchArea_CVKL_U8(const cv::GMatDesc & in,
const Size & outSz,
cv::gapi::fluid::Buffer & scratch) {
const Size& inSz = in.size;
// estimate buffer size
size_t scratch_bytes = resize_get_buffer_size(inSz, outSz);
// allocate buffer
Size scratch_size{static_cast<int>(scratch_bytes), 1};
cv::GMatDesc desc;
desc.chan = 1;
desc.depth = CV_8UC1;
desc.size = scratch_size;
cv::gapi::fluid::Buffer buffer(desc);
scratch = std::move(buffer);
// fulfil buffer
{
// this code is taken from: ie_preprocess_data_sse42.cpp
// (and simplified for 1-channel cv::Mat instead of blob)
auto dwidth = outSz.width;
auto dheight = outSz.height;
auto swidth = inSz.width;
auto sheight = inSz.height;
const int src_go_x = 0;
const int src_go_y = 0;
const int dst_go_x = 0;
const int dst_go_y = 0;
auto src_full_width = swidth;
auto src_full_height = sheight;
auto dst_full_width = dwidth;
auto dst_full_height = dheight;
float scale_x = static_cast<float>(src_full_width) / dst_full_width;
float scale_y = static_cast<float>(src_full_height) / dst_full_height;
int x_max_count = getResizeAreaTabSize(dst_go_x, src_full_width, dwidth, scale_x);
int y_max_count = getResizeAreaTabSize(dst_go_y, src_full_height, dheight, scale_y);
auto* maxdif = scratch.OutLine<int>();
auto* xsi = reinterpret_cast<uint16_t*>(maxdif + 2);
auto* ysi = xsi + dwidth;
auto* xalpha = ysi + dheight;
auto* yalpha = xalpha + dwidth*x_max_count + 8*16;
// auto* vert_sum = yalpha + dheight*y_max_count;
maxdif[0] = x_max_count;
maxdif[1] = y_max_count;
computeResizeAreaTab(src_go_x, dst_go_x, src_full_width, dwidth, scale_x, xsi, xalpha, x_max_count);
computeResizeAreaTab(src_go_y, dst_go_y, src_full_height, dheight, scale_y, ysi, yalpha, y_max_count);
int vest_sum_size = 2*swidth;
uint16_t* vert_sum = yalpha + dheight*y_max_count;
uint16_t* alpha0 = vert_sum + vest_sum_size;
uint16_t* alpha1 = alpha0 + dwidth;
uint16_t* alpha2 = alpha1 + dwidth;
uint16_t* alpha3 = alpha2 + dwidth;
uint16_t* sxid0 = alpha3 + dwidth;
uint16_t* sxid1 = sxid0 + 4*dwidth;
uint16_t* sxid2 = sxid1 + 4*dwidth;
uint16_t* sxid3 = sxid2 + 4*dwidth;
uint16_t* alpha[] = {alpha0, alpha1, alpha2, alpha3};
uint16_t* sxid[] = {sxid0, sxid1, sxid2, sxid3};
generate_alpha_and_id_arrays(x_max_count, dwidth, xalpha, xsi, alpha, sxid);
}
}
static void calcAreaRow_CVKL_U8(const cv::gapi::fluid::View & in,
cv::gapi::fluid::Buffer & out,
cv::gapi::fluid::Buffer & scratch) {
Size inSz = in.meta().size;
Size outSz = out.meta().size;
// this method is valid only for down-scale
GAPI_DbgAssert(inSz.width >= outSz.width);
GAPI_DbgAssert(inSz.height >= outSz.height);
int dwidth = outSz.width;
int dheight = outSz.height;
auto* maxdif = scratch.OutLine<int>();
int x_max_count = maxdif[0];
int y_max_count = maxdif[1];
auto* xsi = reinterpret_cast<uint16_t*>(maxdif + 2);
auto* ysi = xsi + dwidth;
auto* xalpha = ysi + dheight;
auto* yalpha = xalpha + dwidth*x_max_count + 8*16;
auto* vert_sum = yalpha + dheight*y_max_count;
int iny = in.y();
int y = out.y();
int lpi = out.lpi();
GAPI_DbgAssert(y + lpi <= outSz.height);
for (int l = 0; l < lpi; l++) {
int yin0 = ysi[y + l];
int yin1 = yin0 + y_max_count;
GAPI_Assert(yin1 - yin0 <= 32);
const uint8_t *src[32] = {};
for (int yin = yin0; yin < yin1 && yin < inSz.height; yin++) {
if (yalpha[(y+l)*y_max_count + yin - yin0] == 0) {
src[yin - yin0] = in.InLine<const uint8_t>(yin - iny - 1);
} else {
src[yin - yin0] = in.InLine<const uint8_t>(yin - iny);
}
}
uint8_t *dst = out.OutLine<uint8_t>(l);
calcRowArea_CVKL_U8_SSE42(src, dst, inSz, outSz, y + l, xsi, ysi,
xalpha, yalpha, x_max_count, y_max_count, vert_sum);
}
}
#endif // CVKL
//----------------------------------------------------------------------
GAPI_FLUID_KERNEL(FScalePlane8u, ScalePlane8u, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchLinear<uchar, linear::Mapper>(in, outSz, scratch, LPI);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
calcRowLinear<uint8_t, linear::Mapper>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FScalePlanes, ScalePlanes, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in, int, Size,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchLinear<uchar, linear::Mapper, 3>(in, outSz, scratch, LPI);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, int, Size, Size/*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out1,
cv::gapi::fluid::Buffer& out2,
cv::gapi::fluid::Buffer& out3,
cv::gapi::fluid::Buffer& scratch) {
constexpr int numChan = 3;
std::array<std::reference_wrapper<cv::gapi::fluid::Buffer>, numChan> out = {out1, out2, out3};
calcRowLinearC<uint8_t, linear::Mapper, numChan>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FScalePlanes4, ScalePlanes4, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in, int, Size,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchLinear<uchar, linear::Mapper, 4>(in, outSz, scratch, LPI);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, int, Size, Size/*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out1,
cv::gapi::fluid::Buffer& out2,
cv::gapi::fluid::Buffer& out3,
cv::gapi::fluid::Buffer& out4,
cv::gapi::fluid::Buffer& scratch) {
constexpr int numChan = 4;
std::array<std::reference_wrapper<cv::gapi::fluid::Buffer>, numChan> out = {out1, out2, out3, out4};
calcRowLinearC<uint8_t, linear::Mapper, numChan>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FUpscalePlaneArea8u, UpscalePlaneArea8u, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchLinear<uchar, areaUpscale::Mapper>(in, outSz, scratch, LPI);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
calcRowLinear<uint8_t, areaUpscale::Mapper>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FUpscalePlaneArea32f, UpscalePlaneArea32f, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchLinear<float, areaUpscale32f::Mapper>(in, outSz, scratch, 0);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
calcRowLinear<float, areaUpscale32f::Mapper>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FScalePlane32f, ScalePlane32f, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
GAPI_DbgAssert(in.depth == CV_32F && in.chan == 1);
initScratchLinear<float, linear32f::Mapper>(in, outSz, scratch, 0);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
calcRowLinear<float, linear32f::Mapper>(in, out, scratch);
}
};
//----------------------------------------------------------------------
GAPI_FLUID_KERNEL(FScalePlaneArea32f, ScalePlaneArea32f, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
initScratchArea<areaDownscale32f::Mapper>(in, outSz, scratch);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
calcAreaRow<float, areaDownscale32f::Mapper>(in, out, scratch);
}
};
GAPI_FLUID_KERNEL(FScalePlaneArea8u, ScalePlaneArea8u, true) {
static const int Window = 1;
static const int LPI = 4;
static const auto Kind = cv::GFluidKernel::Kind::Resize;
static void initScratch(const cv::GMatDesc& in,
Size outSz, int /*interp*/,
cv::gapi::fluid::Buffer &scratch) {
#if USE_CVKL
#ifdef HAVE_SSE
if (with_cpu_x86_sse42()) {
const Size& inSz = in.size;
if (inSz.width > outSz.width && inSz.height > outSz.height) {
// CVKL code we use supports only downscale
initScratchArea_CVKL_U8(in, outSz, scratch);
return;
}
}
#endif // HAVE_SSE
#endif
initScratchArea<areaDownscale8u::Mapper>(in, outSz, scratch);
}
static void resetScratch(cv::gapi::fluid::Buffer& /*scratch*/) {
}
static void run(const cv::gapi::fluid::View& in, Size /*sz*/, int /*interp*/,
cv::gapi::fluid::Buffer& out, cv::gapi::fluid::Buffer &scratch) {
#if USE_CVKL
#ifdef HAVE_SSE
if (with_cpu_x86_sse42()) {
auto inSz = in.meta().size;
auto outSz = out.meta().size;
if (inSz.width > outSz.width && inSz.height > outSz.height) {
// CVKL's code supports only downscale
calcAreaRow_CVKL_U8(in, out, scratch);
return;
}
}
#endif // HAVE_SSE
#endif
calcAreaRow<uint8_t, areaDownscale8u::Mapper>(in, out, scratch);
}
};
namespace {
template <typename src_t, typename dst_t>
void convert_precision(const uint8_t* src, uint8_t* dst, const int width) {
const auto *in = reinterpret_cast<const src_t *>(src);
auto *out = reinterpret_cast<dst_t *>(dst);
for (int i = 0; i < width; i++) {
out[i] = saturate_cast<dst_t>(in[i]);
}
}
} // namespace
GAPI_FLUID_KERNEL(FConvertDepth, ConvertDepth, false) {
static const int Window = 1;
static void run(const cv::gapi::fluid::View& src, int depth, cv::gapi::fluid::Buffer& dst) {
GAPI_Assert(src.meta().depth == CV_8U || src.meta().depth == CV_32F || src.meta().depth == CV_16U);
GAPI_Assert(dst.meta().depth == CV_8U || dst.meta().depth == CV_32F || dst.meta().depth == CV_16U);
GAPI_Assert(src.meta().chan == 1);
GAPI_Assert(dst.meta().chan == 1);
GAPI_Assert(src.length() == dst.length());
constexpr unsigned supported_types_n = 3;
using p_f = void (*)( const uint8_t* src, uint8_t* dst, const int width);
using table_string_t = std::array<p_f, supported_types_n>;
constexpr std::array<table_string_t, supported_types_n> func_table = {
table_string_t{convert_precision<uint16_t, uint16_t>, convert_precision<uint16_t, float>, convert_precision<uint16_t, uint8_t>},
table_string_t{convert_precision<float, uint16_t>, convert_precision<float, float>, convert_precision<float, uint8_t>},
table_string_t{convert_precision<uint8_t, uint16_t>, convert_precision<uint8_t, float>, convert_precision<uint8_t, uint8_t>}
};
auto depth_to_index = [](int depth){
switch (depth) {
case CV_16U: return 0;
case CV_32F: return 1;
case CV_8U: return 2;
default: GAPI_Assert(!"not supported depth"); return -1;
}
};
const auto *in = src.InLineB(0);
auto *out = dst.OutLineB();
auto const width = dst.length();
auto const src_index = depth_to_index(src.meta().depth);
auto const dst_index = depth_to_index(dst.meta().depth);
(func_table[src_index][dst_index])(in, out, width);
}
};
namespace {
template <typename src_t, typename dst_t>
void sub(const uint8_t* src, uint8_t* dst, const int width, double c) {
const auto *in = reinterpret_cast<const src_t *>(src);
auto *out = reinterpret_cast<dst_t *>(dst);
for (int i = 0; i < width; i++) {
out[i] = saturate_cast<dst_t>(in[i] - c);
}
}
template <typename src_t, typename dst_t>
void div(const uint8_t* src, uint8_t* dst, const int width, double c) {
const auto *in = reinterpret_cast<const src_t *>(src);
auto *out = reinterpret_cast<dst_t *>(dst);
for (int i = 0; i < width; i++) {
out[i] = saturate_cast<dst_t>(in[i] / c);
}
}
} // namespace
GAPI_FLUID_KERNEL(FSubC, GSubC, false) {
static const int Window = 1;
static void run(const cv::gapi::fluid::View& src, const cv::Scalar &scalar, int depth, cv::gapi::fluid::Buffer& dst) {
GAPI_Assert(src.meta().depth == CV_32F && src.meta().chan == 1);
const auto *in = src.InLineB(0);
auto *out = dst.OutLineB();
auto const width = dst.length();
sub<float, float>(in, out, width, scalar[0]);
}
};
GAPI_FLUID_KERNEL(FDivC, GDivC, false) {
static const int Window = 1;
static void run(const cv::gapi::fluid::View &src, const cv::Scalar &scalar, double _scale, int /*dtype*/,
cv::gapi::fluid::Buffer &dst) {
GAPI_Assert(src.meta().depth == CV_32F && src.meta().chan == 1);
const auto *in = src.InLineB(0);
auto *out = dst.OutLineB();
auto const width = dst.length();
div<float, float>(in, out, width, scalar[0]);
}
};
} // namespace kernels
//----------------------------------------------------------------------
using namespace kernels;
cv::gapi::GKernelPackage preprocKernels() {
return combine(
FKernelsChooseISA(),
cv::gapi::kernels
<FScalePlanes
, FScalePlanes4
, FScalePlane
, FScalePlane32f
, FScalePlane8u
, FUpscalePlaneArea8u
, FUpscalePlaneArea32f
, FScalePlaneArea8u
, FScalePlaneArea32f
, FConvertDepth
, FSubC
, FDivC
>());
}
} // namespace gapi
} // namespace InferenceEngine
|
/*
* Copyright (C) 2015, Nils Moehrle
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <math/vector.h>
#include "debug.h"
TEX_NAMESPACE_BEGIN
const bool font[] = {
0,1,0, 0,1,0, 1,1,0, 1,1,0, 1,0,0, 1,1,1, 0,1,0, 1,1,1, 0,1,0 ,0,1,0,
1,0,1, 1,1,0, 0,0,1, 0,0,1, 1,0,1, 1,0,0, 1,0,0, 0,0,1, 1,0,1, 1,0,1,
1,0,1, 0,1,0, 0,1,0, 0,1,0, 1,1,1, 1,1,0, 1,1,0, 0,0,1, 0,1,0, 0,1,1,
1,0,1, 0,1,0, 1,0,0, 0,0,1, 0,0,1, 0,0,1, 1,0,1, 0,1,0, 1,0,1, 0,0,1,
0,1,0, 1,1,1, 1,1,1, 1,1,0, 0,0,1, 1,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0
};
void print_number(mve::ByteImage::Ptr image, int x, int y, int digit, math::Vec3uc color) {
assert(0 <= x && x < image->width() - 3);
assert(0 <= y && y < image->height() - 5);
assert(0 <= digit && digit <= 9);
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 5; ++j) {
if(font[30 * j + digit * 3 + i]) {
for(int c = 0; c < image->channels(); ++c) {
image->at(x+i, y+j, c) = color[c];
}
}
}
}
}
void
generate_debug_colors(std::vector<math::Vec4f> & colors) {
for (float s = 1.0f; s > 0.0f; s -= 0.4) {
for (float v = 1.0f; v > 0.0f; v -= 0.3) {
for (float h = 0.0f; h < 360.0f; h += 30.0f) {
float c = v * s;
float x = c * (1.0f - fabs(fmod(h / 60.0f, 2.0f) - 1.0f));
float m = v - c;
math::Vec4f color;
if (0 <= h && h < 60)
color = math::Vec4f(c, x, 0.0f, 1.0f);
if (60 <= h && h < 120)
color = math::Vec4f(x, c, 0.0f, 1.0f);
if (120 <= h && h < 180)
color = math::Vec4f(0.0f, c, x, 1.0f);
if (180 <= h && h < 240)
color = math::Vec4f(0.0f, x, c, 1.0f);
if (240 <= h && h < 300)
color = math::Vec4f(x, 0.0f, c, 1.0f);
if (300 <= h && h < 360)
color = math::Vec4f(c, 0.0f, x, 1.0f);
color = color + math::Vec4f(m, m, m, 0.0f);
colors.push_back(color);
}
}
}
}
void
generate_debug_embeddings(std::vector<TextureView> * texture_views) {
std::vector<math::Vec4f> colors;
generate_debug_colors(colors);
#pragma omp parallel for
for (std::size_t i = 0; i < texture_views->size(); ++i) {
math::Vec4f float_color = colors[i % colors.size()];
TextureView * texture_view = &(texture_views->at(i));
/* Determine font color depending on luminance of background. */
float luminance = math::interpolate(float_color[0], float_color[1], float_color[2], 0.30f, 0.59f, 0.11f);
math::Vec3uc font_color = luminance > 0.5f ? math::Vec3uc(0,0,0) : math::Vec3uc(255,255,255);
math::Vec3uc color;
color[0] = float_color[0] * 255.0f;
color[1] = float_color[1] * 255.0f;
color[2] = float_color[2] * 255.0f;
mve::ByteImage::Ptr image = mve::ByteImage::create(texture_view->get_width(), texture_view->get_height(), 3);
image->fill_color(*color);
for(int ox=0; ox < image->width() - 13; ox += 13) {
for(int oy=0; oy < image->height() - 6; oy += 6) {
std::size_t id = texture_view->get_id();
int d0 = id / 100;
int d1 = (id % 100) / 10;
int d2 = id % 10;
print_number(image, ox, oy, d0, font_color);
print_number(image, ox + 4, oy, d1, font_color);
print_number(image, ox + 8, oy, d2, font_color);
}
}
texture_view->bind_image(image);
}
}
TEX_NAMESPACE_END
|
/*Copyright (c) 2019 The Paradox Game Converters 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 "TechGroupsMapper.h"
#include "TechGroups.h"
#include "Log.h"
mappers::TechGroupsMapper::TechGroupsMapper(std::istream& theStream)
{
registerKeyword(std::regex("[a-zA-Z0-9_]+"), [this](const std::string& techGroup, std::istream& theStream) {
TechGroups techGroups(theStream);
westernizations[techGroup] = techGroups.getWesternization();
literacies[techGroup] = techGroups.getLiteracyBoost();
});
LOG(LogLevel::Info) << "getting tech groups";
parseStream(theStream);
}
int mappers::TechGroupsMapper::getWesternizationFromTechGroup(const std::string& techGroupName) const
{
auto techGroup = westernizations.find(techGroupName);
return techGroup->second;
}
int mappers::TechGroupsMapper::getLiteracyFromTechGroup(const std::string& techGroupName) const
{
auto techGroup = literacies.find(techGroupName);
return techGroup->second;
}
|
data segment
port dw 290h
mes0 db 'Start.',0dh,0ah,'$'
mes db 'Exit!$'
data ends
code segment
assume cs:code,ds:data
start:
mov ax,data
mov ds,ax
lea dx,mes0
mov ah,09h
int 21h
mov cl,0
mov dx,port
lp:
mov al,cl
out dx,al
add cl,1
call key
jz lp
lea dx,mes
mov ah,09h
int 21h
mov ah,4ch
int 21h
key proc near
push dx
mov ah,06h
mov dl,0ffh
int 21h
pop dx
ret
key endp
code ends
end start |
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r14
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x13b0c, %rsi
lea addresses_WC_ht+0x1d26c, %rdi
sub %r14, %r14
mov $10, %rcx
rep movsl
nop
nop
nop
nop
xor $50844, %r13
lea addresses_D_ht+0x1bbfb, %rsi
lea addresses_UC_ht+0xecec, %rdi
nop
nop
nop
nop
nop
sub %r11, %r11
mov $100, %rcx
rep movsw
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_D_ht+0x16d89, %rsi
nop
nop
nop
cmp %r10, %r10
movw $0x6162, (%rsi)
cmp $61041, %r14
lea addresses_WC_ht+0x1d954, %rsi
lea addresses_UC_ht+0x14142, %rdi
nop
nop
nop
xor $35020, %r9
mov $17, %rcx
rep movsb
nop
nop
nop
nop
nop
xor %rdi, %rdi
lea addresses_normal_ht+0x3b0c, %r14
nop
nop
nop
sub $15825, %r13
mov (%r14), %r10w
nop
add $35338, %r9
lea addresses_normal_ht+0x19b0c, %rsi
lea addresses_normal_ht+0x16b05, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
dec %r13
mov $97, %rcx
rep movsq
nop
xor %r14, %r14
lea addresses_normal_ht+0x1c92c, %rsi
lea addresses_normal_ht+0x18b0c, %rdi
clflush (%rsi)
nop
nop
nop
nop
inc %r13
mov $60, %rcx
rep movsb
nop
nop
cmp %r14, %r14
lea addresses_A_ht+0x1710c, %rsi
lea addresses_UC_ht+0x710c, %rdi
add %r11, %r11
mov $28, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp $42979, %rsi
lea addresses_WT_ht+0x430c, %rsi
lea addresses_WC_ht+0xbd0c, %rdi
nop
nop
nop
nop
cmp %r9, %r9
mov $120, %rcx
rep movsq
and $3396, %r11
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r14
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r14
push %r9
push %rbp
push %rbx
push %rdi
// Store
lea addresses_WT+0xe30c, %r13
nop
add $56536, %r14
mov $0x5152535455565758, %rbp
movq %rbp, (%r13)
nop
xor %r14, %r14
// Load
lea addresses_D+0x3bac, %rbx
nop
nop
sub $55519, %r9
vmovups (%rbx), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $0, %xmm7, %r13
nop
nop
nop
nop
cmp %rbp, %rbp
// Store
lea addresses_WT+0xe30c, %r9
nop
nop
nop
cmp %r12, %r12
mov $0x5152535455565758, %rbp
movq %rbp, %xmm4
vmovups %ymm4, (%r9)
nop
nop
nop
nop
nop
sub $11399, %rbx
// Store
lea addresses_UC+0x6a0c, %rdi
nop
xor $16157, %r13
mov $0x5152535455565758, %rbx
movq %rbx, %xmm3
movups %xmm3, (%rdi)
nop
nop
and %r13, %r13
// Store
lea addresses_UC+0x830c, %r14
nop
nop
nop
nop
and $29591, %rbx
mov $0x5152535455565758, %r9
movq %r9, %xmm6
movups %xmm6, (%r14)
nop
nop
nop
nop
nop
inc %r9
// Faulty Load
lea addresses_WT+0xe30c, %r9
nop
nop
nop
dec %rdi
movb (%r9), %bl
lea oracles, %r13
and $0xff, %rbx
shlq $12, %rbx
mov (%r13,%rbx,1), %rbx
pop %rdi
pop %rbx
pop %rbp
pop %r9
pop %r14
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WT', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT', 'same': True, 'size': 8, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_WT', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 2, 'congruent': 8, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; Startup for VZ200/300
;
; Stefano Bodrato - Apr. 2000
;
; If an error occurs eg break we just drop back to BASIC
;
; $Id: vz_crt0.asm,v 1.17 2015/01/26 16:50:29 stefano Exp $
;
MODULE vz_crt0
;--------
; Include zcc_opt.def to find out some info
;--------
INCLUDE "zcc_opt.def"
;--------
; Some scope definitions
;--------
EXTERN _main ;main() is always external to crt0 code
PUBLIC cleanup ;jp'd to by exit()
PUBLIC l_dcal ;jp(hl)
PUBLIC _vfprintf ;jp to the printf() core
PUBLIC exitsp ;atexit() variables
PUBLIC exitcount
PUBLIC heaplast ;Near malloc heap variables
PUBLIC heapblocks
PUBLIC __sgoioblk ;stdio info block
;Graphic function PUBLICS..
PUBLIC coords ;Current xy position
PUBLIC base_graphics ;GFX memory related variables
PUBLIC gfx_bank
PUBLIC snd_tick ; Sound variable
PUBLIC bit_irqstatus ; current irq status when DI is necessary
IF !myzorg
IF (startup=3)
defc myzorg = 32768 ; clean binary block
ELSE
IF (startup=2)
defc myzorg = $7ae9 ; BASIC startup mode
ELSE
defc myzorg = $7b00 ; Direct M/C mode
ENDIF
ENDIF
ENDIF
; Now, getting to the real stuff now!
org myzorg-24
IF (startup=3)
; STARTUP=3 -> plain binary block
ELSE
defb $20,$20,0,0
defm "z80.mc"
defb 0,0,0,0,0,0,0,0,0,0,0
IF (startup=2)
; BASIC startup mode
defb $f0
ELSE
; native M/C startup mode
defb $f1
ENDIF
defw myzorg
IF (startup=2)
defw $7b04
defw 1
defb $B1 ;POKE
defm " 30862,18:"
defb $B1 ;POKE
defm " 30863,123"
defb 0 ; this block is 27 bytes long
defw $7b0f
defw 2
defb $b2 ; PRINT
defb ' '
defb $c1 ; USR
defm "(0)"
defb 0 ; this block is 11 bytes long
defw 0
defb 4
; Header ends here: 65 bytes
ENDIF
ENDIF
start:
ld hl,-64 ; 32 pointers (ANSI standard)
add hl,sp
ld sp,hl
ld (exitsp),sp
; 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_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
call _main
cleanup:
;
; Deallocate memory which has been allocated here!
;
push hl
IF !DEFINED_nostreams
IF DEFINED_ANSIstdio
EXTERN closeall
call closeall
ENDIF
ENDIF
pop bc
start1:
ld sp,0
jp 1A19h
l_dcal:
jp (hl)
;-----------
; Define the stdin/out/err area. For the z88 we have two models - the
; classic (kludgey) one and "ANSI" model
;-----------
__sgoioblk:
IF DEFINED_ANSIstdio
INCLUDE "stdio_fp.asm"
ELSE
defw -11,-12,-10
ENDIF
;---------------------------------
; Select which printf core we want
;---------------------------------
_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
;-----------
; Now some variables
;-----------
coords: defw 0 ; Current graphics xy coordinates
base_graphics: defw 7000h ; Address of the Graphics map
gfx_bank: defb 0
IF !DEFINED_HAVESEED
PUBLIC _std_seed ;Integer rand() seed
_std_seed: defw 0 ; Seed for integer rand() routines
ENDIF
exitsp: defw 0 ; Address of where the atexit() stack is
exitcount: defb 0 ; How many routines on the atexit() stack
heaplast: defw 0 ; Address of last block on heap
heapblocks: defw 0 ; Number of blocks
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
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
IF DEFINED_NEED1bitsound
snd_tick: defb 0 ; Sound variable
bit_irqstatus: defw 0
ENDIF
defm "Small C+ VZ"
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
|
/*
* LCD_CDM-16100 Display Driver - 4 bit interface
*
* org: 9/29/2014
* auth: Nels "Chip" Pearson
*
* Target: LCD_CDM-116100 Demo Board w/ LCD display and keypad I/O, 8MHz
* LCD control: ST7066U
*
* Resources
* SRAM
*
* IO
*
*/
.equ LC_CLEAR_DISPLAY = 0x01 ; Write 0x20 to DDRAM and reset AC to 00. [1.52ms]
.equ LC_RETURN_HOME = 0x02 ; Reset AC to 00 and return cursor to home. [1.52ms]
.equ LC_SET_ENTRY_MODE = 0x04 ; b1: I/D, b0: S Set cursor move and display shift. [37us]
.equ LC_DISPLAY_ONOFF = 0x08 ; b2: Display, b1: Cursor, b0: Cursor position. [37us]
.equ LC_CURSOR_DISPLAY_SHIFT = 0x10 ; b3: Select, b2: R/L. [37us]
.equ LC_SET_FUNCTION = 0x20 ; b4: Interface, b3: Lines, b2: Font. [37us]
.equ LC_SET_CGRAM_ADRS = 0x40 ; b5:0 CGRAM Address. [37us]
.equ LC_SET_DDRAM_ADRS = 0x80 ; b6:0 DDRAM Address. [37us]
.equ LCD_SHIFT_CURSOR_LEFT = 0b00000000
.equ LCD_SHIFT_CURSOR_RIGHT = 0b00000100
.equ LCD_SHIFT_DISPLAY_LEFT = 0b00001000
.equ LCD_SHIFT_DISPLAY_RIGHT = 0b00001100
; PORTC bits
.equ LCD_RS = 3
.equ LCD_RW = 2
.equ LCD_E = 1
/*
* lcd_delay_40us()
* Tweak delay loop based on CPU clock
* Call twice for 80us and 39 times for 1.52ms
*
* For 8MHz
*
*/
lcd_delay_40us:
push R16
;
ldi R16, 40 ; 8 * 40 cycles
; 8 cycle loop = 1us
ld1_loop1:
nop
nop
nop
nop
nop
dec R16
brne ld1_loop1
;
pop R16
ret
/*
* lcd_delay_1ms(n)
* Tweak delay loop based on CPU clock
*
* input: R17 - n ms
* For 8MHz
*
*/
lcd_delay_1ms:
push R16
;
ld1m_loop2:
ldi R16, 25
ld1m_loop1:
call lcd_delay_40us
dec R16
brne ld1m_loop1
dec R17
brne ld1m_loop2
;
pop R16
ret
/*
* lcd_init()
* Set up I/O and LDC module for 8 bit access.
*
* PortD.7:0 - Data 7:0 in/out
* PortC.3 - RS out
* PortC.2 - R/W out
* PortC.1 - E out
*
*/
lcd_init:
; Set up I/O
sbi DDRC, LCD_RS
sbi DDRC, LCD_RW
sbi DDRC, LCD_E
cbi PORTC, LCD_RS
cbi PORTC, LCD_RW
cbi PORTC, LCD_E
; Wait 40ms after power up.
ldi R17, 40
call lcd_delay_1ms
; Interface starts as 8 bit access
ldi R17, 0x20 ; Function set..chenage from 8bit to 4bit
call lcd_write_ins_once
ldi R17, 40
call lcd_delay_1ms
; Set interface for 4 bit access
ldi R17, 0x2C ; Function set..MUST write TWICE
call lcd_write_ins_nochk
call lcd_delay_40us
ldi R17, 40
call lcd_delay_1ms
;
; Set interface for 4 bit access
ldi R17, 0x2C ; Function set..MUST write TWICE
call lcd_write_ins_nochk
call lcd_delay_40us
ldi R17, 40
call lcd_delay_1ms
;
call lcd_clear_display
;
ldi R17, 0b00001110 ; Display ON, Cursor ON, Blink OFF
call lcd_write_ins_nochk
ldi R17, 1
call lcd_delay_1ms
;
ldi R18, 1
ldi R19, 1
call lcd_set_entry_mode
;
ret
/*
* Instruction Access
* input: R17 - Data
*/
lcd_write_ins_chk:
call lcd_ckeck_busy ; Blocking call while Busy
lcd_write_ins_nochk:
cbi PORTC, LCD_RS
cbi PORTC, LCD_RW
call lcd_raw_write
swap R17
lcd_write_ins_once:
call lcd_raw_write
ret
/* Blocking call while Busy */
lcd_ckeck_busy:
push R17
lcb_loop00:
call lcd_delay_40us ; wait 80us
call lcd_delay_40us
;
cbi PORTC, LCD_RS
sbi PORTC, LCD_RW
call lcd_raw_read ; read upper 4 bits
push R17
call lcd_raw_read ; read upper 4 bits
pop R17
lsl R17 ; test Busy bit..D7
brcs lcb_loop00 ; BS=1..Busy
;
cbi PORTC, LCD_RS
cbi PORTC, LCD_RW
;
pop R17
ret
/*
* output: R17 - Data in
*/
lcd_raw_read:
push R16
clr R16
out DDRD, R16 ; set for input
ser R16
out PORTD, R16 ; turn on pull-ups
;
sbi PORTC, LCD_E ; min PW = 500ns..4 cycles @ 8MHz
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
in R17, PORTD
nop
cbi PORTC, LCD_E
;
pop R16
ret
/*
* output: R17 - Data out
*/
lcd_raw_write:
push R16
ldi R16, 0xF0
out DDRD, R16 ; set for output
nop
nop
;
out PORTD, R17
nop
nop
;
sbi PORTC, LCD_E ; min PW = 500ns..4 cycles @ 8MHz
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
cbi PORTC, LCD_E
;
pop R16
ret
/*
* lcd_clear_display()
*/
lcd_clear_display:
ldi R17, LC_CLEAR_DISPLAY
call lcd_write_ins_nochk
ldi R17, 10 ; 1.52ms delay
call lcd_delay_1ms
ret
/*
* lcd_return_home()
*/
lcd_return_home:
ldi R17, LC_RETURN_HOME
call lcd_write_ins_nochk
ldi R17, 10 ; 1.52ms delay
call lcd_delay_1ms
ret
/*
* lcd_set_entry_mode( direction, shift_enable )
*
* input R18 Adrs Direction. 0: Left (Dec), 1:Right (Inc)
* R19 Enable display shift. 0:False, 1:True
*/
lcd_set_entry_mode:
ldi R17, LC_SET_ENTRY_MODE
tst R18
breq lse_skip00
ori R17, 0x02 ; Inc and move cursor right
;
lse_skip00:
tst R19
breq lse_skip01
ori R17, 0x01 ; Display shift with cursor
;
lse_skip01:
call lcd_write_ins_nochk
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
;
ret
/*
* lcd_display_on_off( display, cursor, blink )
*/
lcd_display_on_off:
ret
/*
* lcd_cursor_display_shift( LCD_SHIFT_XXXX )
* Shifts the cursor position one step.
*
* input: R17 - Control
*
* LCD_SHIFT_CURSOR_LEFT
* LCD_SHIFT_CURSOR_RIGHT
* LCD_SHIFT_DISPLAY_LEFT
* LCD_SHIFT_DISPLAY_RIGHT
*/
lcd_cursor_display_shift:
ori R17, LC_CURSOR_DISPLAY_SHIFT
call lcd_write_ins_nochk
call lcd_delay_40us
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
ret
/*
* lcd_set_cgram_adrs( address )
* input: R17 - CGRAM addres
*/
lcd_set_cgram_adrs:
ori R17, 0x40
call lcd_write_ins_nochk
call lcd_delay_40us
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
ret
/*
* lcd_set_ddram_adrs( address )
*/
lcd_set_ddram_adrs:
ori R17, 0x80
call lcd_write_ins_nochk
call lcd_delay_40us
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
ret
/*
* char lcd_get_busy_flag()
* Non-blocking Busy Flag read.
* output: R17 - b7: Busy Flag, b6:0 DDRAM/CGRAM address
*/
lcd_get_busy_flag:
cbi PORTC, LCD_RS
sbi PORTC, LCD_RW
call lcd_raw_read
push R17
call lcd_raw_read
;
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
;
cbi PORTC, LCD_RW
pop R17
ret
/*
* lcd_write_data( data )
* input: R17 - Data
*
*/
lcd_write_data:
sbi PORTC, LCD_RS
cbi PORTC, LCD_RW
call lcd_raw_write
swap R17
call lcd_raw_write
;
call lcd_delay_40us
call lcd_delay_40us
;
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
;
call lcd_get_busy_flag
;
cbi PORTC, LCD_RS
ret
/*
* char lcd_read_data()
* output: R17 - Data
*
*/
lcd_read_data:
sbi PORTC, LCD_RS
sbi PORTC, LCD_RW
call lcd_raw_read
push R17
call lcd_raw_read
swap R17
andi R17, 0x0F
pop R16
andi R16, 0xF0
or R17, R16 ; combine
push R17
;
call lcd_delay_40us
call lcd_delay_40us
;
ldi R17, 1
call lcd_delay_1ms ; HACK until BF check resolved.
;
call lcd_get_busy_flag
;
pop R17
ret
|
; A095122: Fib(n)(2Fib(n)-1).
; 0,1,1,6,15,45,120,325,861,2278,5995,15753,41328,108345,283881,743590,1947351,5099221,13351528,34957341,91523685,239618886,627341331,1642418641,4299936480,11257426225,29472399505,77159865030,202007345631
seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
mul $0,2
bin $0,2
|
; A008346: a(n) = Fibonacci(n) + (-1)^n.
; 1,0,2,1,4,4,9,12,22,33,56,88,145,232,378,609,988,1596,2585,4180,6766,10945,17712,28656,46369,75024,121394,196417,317812,514228,832041,1346268,2178310,3524577,5702888,9227464,14930353,24157816,39088170,63245985,102334156,165580140,267914297,433494436,701408734,1134903169,1836311904,2971215072,4807526977,7778742048,12586269026,20365011073,32951280100,53316291172,86267571273,139583862444,225851433718,365435296161,591286729880,956722026040,1548008755921,2504730781960,4052739537882,6557470319841,10610209857724,17167680177564,27777890035289,44945570212852,72723460248142,117669030460993,190392490709136,308061521170128,498454011879265,806515533049392,1304969544928658,2111485077978049,3416454622906708,5527939700884756,8944394323791465,14472334024676220,23416728348467686,37889062373143905,61305790721611592,99194853094755496,160500643816367089,259695496911122584,420196140727489674,679891637638612257,1100087778366101932,1779979416004714188,2880067194370816121,4660046610375530308,7540113804746346430,12200160415121876737,19740274219868223168,31940434634990099904,51680708854858323073,83621143489848422976,135301852344706746050,218922995834555169025
mov $2,$0
seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
mul $2,2
mod $2,4
sub $0,$2
add $0,1
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* */
/* This file is part of the class library */
/* SoPlex --- the Sequential object-oriented simPlex. */
/* */
/* Copyright (C) 1996-2018 Konrad-Zuse-Zentrum */
/* fuer Informationstechnik Berlin */
/* */
/* SoPlex is distributed under the terms of the ZIB Academic Licence. */
/* */
/* You should have received a copy of the ZIB Academic License */
/* along with SoPlex; see the file COPYING. If not email to soplex@zib.de. */
/* */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* Updating the Basis for Leaving Variables
*/
#include <assert.h>
#include <stdio.h>
#include "spxdefines.h"
#include "spxpricer.h"
#include "spxsolver.h"
#include "spxratiotester.h"
#include "spxout.h"
#include "exceptions.h"
namespace soplex
{
static const Real reject_leave_tol = 1e-10; // = LOWSTAB as defined in spxfastrt.cpp
/*
Vector |fTest| gives the feasibility test of all basic variables. For its
computation |fVec|, |theUBbound| and |theLBbound| must be setup correctly.
Values of |fTest| $<0$ represent infeasible variables, which are eligible
for leaving the basis in the simplex loop.
*/
void SPxSolver::computeFtest()
{
assert(type() == LEAVE);
Real theeps = entertol();
m_pricingViolUpToDate = true;
m_pricingViolCoUpToDate = true;
m_pricingViol = 0;
m_pricingViolCo = 0;
infeasibilities.clear();
int ninfeasibilities = 0;
int sparsitythreshold = (int) (sparsePricingFactor * dim());
for( int i = 0; i < dim(); ++i )
{
theCoTest[i] = ((*theFvec)[i] > theUBbound[i])
? theUBbound[i] - (*theFvec)[i]
: (*theFvec)[i] - theLBbound[i];
if( remainingRoundsLeave == 0 )
{
if( theCoTest[i] < -theeps )
{
m_pricingViol -= theCoTest[i];
infeasibilities.addIdx(i);
isInfeasible[i] = SPxPricer::VIOLATED;
++ninfeasibilities;
}
else
isInfeasible[i] = SPxPricer::NOT_VIOLATED;
if( ninfeasibilities > sparsitythreshold )
{
MSG_INFO2( (*spxout), (*spxout) << " --- using dense pricing"
<< std::endl; )
remainingRoundsLeave = DENSEROUNDS;
sparsePricingLeave = false;
ninfeasibilities = 0;
}
}
else if( theCoTest[i] < -theeps )
m_pricingViol -= theCoTest[i];
}
if( ninfeasibilities == 0 && !sparsePricingLeave )
{
--remainingRoundsLeave;
}
else if( ninfeasibilities <= sparsitythreshold && !sparsePricingLeave )
{
MSG_INFO2( (*spxout),
std::streamsize prec = spxout->precision();
if( hyperPricingLeave )
(*spxout) << " --- using hypersparse pricing, ";
else
(*spxout) << " --- using sparse pricing, ";
(*spxout) << "sparsity: "
<< std::setw(6) << std::fixed << std::setprecision(4)
<< (Real) ninfeasibilities/dim()
<< std::scientific << std::setprecision(int(prec))
<< std::endl;
)
sparsePricingLeave = true;
}
}
void SPxSolver::updateFtest()
{
const IdxSet& idx = theFvec->idx();
Vector& ftest = theCoTest; // |== fTest()|
assert(&ftest == &fTest());
assert(type() == LEAVE);
updateViols.clear();
Real theeps = entertol();
for (int j = idx.size() - 1; j >= 0; --j)
{
int i = idx.index(j);
if( m_pricingViolUpToDate && ftest[i] < -theeps )
m_pricingViol += ftest[i];
ftest[i] = ((*theFvec)[i] > theUBbound[i])
? theUBbound[i] - (*theFvec)[i]
: (*theFvec)[i] - theLBbound[i];
if( sparsePricingLeave && ftest[i] < -theeps )
{
assert(remainingRoundsLeave == 0);
if( m_pricingViolUpToDate )
m_pricingViol -= ftest[i];
if( isInfeasible[i] == SPxPricer::NOT_VIOLATED )
{
// this can cause problems - we cannot keep on adding indeces to infeasibilities,
// because they are not deleted in hyper mode...
// if( !hyperPricingLeave )
infeasibilities.addIdx(i);
isInfeasible[i] = SPxPricer::VIOLATED;
}
if( hyperPricingLeave )
updateViols.addIdx(i);
}
else if( m_pricingViolUpToDate && ftest[i] < -theeps )
m_pricingViol -= ftest[i];
}
// if boundflips were performed, we need to update these indices as well
if( boundflips > 0 )
{
Real eps = epsilon();
for( int j = 0; j < solveVector3->size(); ++j )
{
if( spxAbs(solveVector3->value(j)) > eps )
{
int i = solveVector3->index(j);
if( m_pricingViolUpToDate && ftest[i] < -theeps )
m_pricingViol += ftest[i];
ftest[i] = ((*theFvec)[i] > theUBbound[i]) ? theUBbound[i] - (*theFvec)[i] : (*theFvec)[i] - theLBbound[i];
if( sparsePricingLeave && ftest[i] < -theeps )
{
assert(remainingRoundsLeave == 0);
if( m_pricingViolUpToDate )
m_pricingViol -= ftest[i];
if( !isInfeasible[i] )
{
infeasibilities.addIdx(i);
isInfeasible[i] = true;
}
}
else if( m_pricingViolUpToDate && ftest[i] < -theeps )
m_pricingViol -= ftest[i];
}
}
}
}
/* compute statistics on leaving variable
Compute a set of statistical values on the variable selected for leaving the
basis.
*/
void SPxSolver::getLeaveVals(
int leaveIdx,
SPxBasis::Desc::Status& leaveStat,
SPxId& leaveId,
Real& leaveMax,
Real& leavebound,
int& leaveNum,
Real& objChange)
{
SPxBasis::Desc& ds = desc();
leaveId = baseId(leaveIdx);
if (leaveId.isSPxRowId())
{
leaveNum = number(SPxRowId(leaveId));
leaveStat = ds.rowStatus(leaveNum);
assert(isBasic(leaveStat));
switch (leaveStat)
{
case SPxBasis::Desc::P_ON_UPPER :
assert( rep() == ROW );
ds.rowStatus(leaveNum) = dualRowStatus(leaveNum);
leavebound = 0;
leaveMax = -infinity;
break;
case SPxBasis::Desc::P_ON_LOWER :
assert( rep() == ROW );
ds.rowStatus(leaveNum) = dualRowStatus(leaveNum);
leavebound = 0;
leaveMax = infinity;
break;
case SPxBasis::Desc::P_FREE :
assert( rep() == ROW );
throw SPxInternalCodeException("XLEAVE01 This should never happen.");
case SPxBasis::Desc::D_FREE :
assert( rep() == COLUMN );
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_FIXED;
assert(lhs(leaveNum) == rhs(leaveNum));
leavebound = -rhs(leaveNum);
if ((*theFvec)[leaveIdx] < theLBbound[leaveIdx])
leaveMax = infinity;
else
leaveMax = -infinity;
break;
case SPxBasis::Desc::D_ON_LOWER :
assert( rep() == COLUMN );
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
leavebound = -rhs(leaveNum); // slack !!
leaveMax = infinity;
objChange += theLRbound[leaveNum] * rhs(leaveNum);
break;
case SPxBasis::Desc::D_ON_UPPER :
assert( rep() == COLUMN );
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
leavebound = -lhs(leaveNum); // slack !!
leaveMax = -infinity;
objChange += theURbound[leaveNum] * lhs(leaveNum);
break;
case SPxBasis::Desc::D_ON_BOTH :
assert( rep() == COLUMN );
if ((*theFvec)[leaveIdx] > theLBbound[leaveIdx])
{
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
theLRbound[leaveNum] = -infinity;
leavebound = -lhs(leaveNum); // slack !!
leaveMax = -infinity;
objChange += theURbound[leaveNum] * lhs(leaveNum);
}
else
{
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
theURbound[leaveNum] = infinity;
leavebound = -rhs(leaveNum); // slack !!
leaveMax = infinity;
objChange += theLRbound[leaveNum] * rhs(leaveNum);
}
break;
default:
throw SPxInternalCodeException("XLEAVE02 This should never happen.");
}
MSG_DEBUG( std::cout << "DLEAVE51 SPxSolver::getLeaveVals() : row " << leaveNum
<< ": " << leaveStat
<< " -> " << ds.rowStatus(leaveNum)
<< " objChange: " << objChange
<< std::endl; )
}
else
{
assert(leaveId.isSPxColId());
leaveNum = number(SPxColId(leaveId));
leaveStat = ds.colStatus(leaveNum);
assert(isBasic(leaveStat));
switch (leaveStat)
{
case SPxBasis::Desc::P_ON_UPPER :
assert( rep() == ROW );
ds.colStatus(leaveNum) = dualColStatus(leaveNum);
leavebound = 0;
leaveMax = -infinity;
break;
case SPxBasis::Desc::P_ON_LOWER :
assert( rep() == ROW );
ds.colStatus(leaveNum) = dualColStatus(leaveNum);
leavebound = 0;
leaveMax = infinity;
break;
case SPxBasis::Desc::P_FREE :
assert( rep() == ROW );
ds.colStatus(leaveNum) = dualColStatus(leaveNum);
if ((*theFvec)[leaveIdx] < theLBbound[leaveIdx])
{
leavebound = theLBbound[leaveIdx];
leaveMax = -infinity;
}
else
{
leavebound = theUBbound[leaveIdx];
leaveMax = infinity;
}
break;
case SPxBasis::Desc::D_FREE :
assert( rep() == COLUMN );
assert(SPxLP::upper(leaveNum) == SPxLP::lower(leaveNum));
ds.colStatus(leaveNum) = SPxBasis::Desc::P_FIXED;
leavebound = SPxLP::upper(leaveNum);
objChange += maxObj(leaveNum) * leavebound;
if ((*theFvec)[leaveIdx] < theLBbound[leaveIdx])
leaveMax = infinity;
else
leaveMax = -infinity;
break;
case SPxBasis::Desc::D_ON_LOWER :
assert( rep() == COLUMN );
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
leavebound = SPxLP::upper(leaveNum);
objChange += theUCbound[leaveNum] * leavebound;
leaveMax = -infinity;
break;
case SPxBasis::Desc::D_ON_UPPER :
assert( rep() == COLUMN );
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
leavebound = SPxLP::lower(leaveNum);
objChange += theLCbound[leaveNum] * leavebound;
leaveMax = infinity;
break;
case SPxBasis::Desc::D_ON_BOTH :
assert( rep() == COLUMN );
if ((*theFvec)[leaveIdx] > theUBbound[leaveIdx])
{
leaveMax = -infinity;
leavebound = SPxLP::upper(leaveNum);
objChange += theUCbound[leaveNum] * leavebound;
theLCbound[leaveNum] = -infinity;
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
}
else
{
leaveMax = infinity;
leavebound = SPxLP::lower(leaveNum);
objChange += theLCbound[leaveNum] * leavebound;
theUCbound[leaveNum] = infinity;
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
}
break;
default:
throw SPxInternalCodeException("XLEAVE03 This should never happen.");
}
MSG_DEBUG( std::cout << "DLEAVE52 SPxSolver::getLeaveVals() : col " << leaveNum
<< ": " << leaveStat
<< " -> " << ds.colStatus(leaveNum)
<< " objChange: " << objChange
<< std::endl; )
}
}
void SPxSolver::getLeaveVals2(
Real leaveMax,
SPxId enterId,
Real& enterBound,
Real& newUBbound,
Real& newLBbound,
Real& newCoPrhs,
Real& objChange
)
{
SPxBasis::Desc& ds = desc();
enterBound = 0;
if (enterId.isSPxRowId())
{
int idx = number(SPxRowId(enterId));
SPxBasis::Desc::Status enterStat = ds.rowStatus(idx);
switch (enterStat)
{
case SPxBasis::Desc::D_FREE :
assert(rep() == ROW);
if (thePvec->delta()[idx] * leaveMax < 0)
newCoPrhs = theLRbound[idx];
else
newCoPrhs = theURbound[idx];
newUBbound = infinity;
newLBbound = -infinity;
ds.rowStatus(idx) = SPxBasis::Desc::P_FIXED;
break;
case SPxBasis::Desc::D_ON_UPPER :
assert(rep() == ROW);
newUBbound = 0;
newLBbound = -infinity;
ds.rowStatus(idx) = SPxBasis::Desc::P_ON_LOWER;
newCoPrhs = theLRbound[idx];
break;
case SPxBasis::Desc::D_ON_LOWER :
assert(rep() == ROW);
newUBbound = infinity;
newLBbound = 0;
ds.rowStatus(idx) = SPxBasis::Desc::P_ON_UPPER;
newCoPrhs = theURbound[idx];
break;
case SPxBasis::Desc::D_ON_BOTH :
assert(rep() == ROW);
if (leaveMax * thePvec->delta()[idx] < 0)
{
newUBbound = 0;
newLBbound = -infinity;
ds.rowStatus(idx) = SPxBasis::Desc::P_ON_LOWER;
newCoPrhs = theLRbound[idx];
}
else
{
newUBbound = infinity;
newLBbound = 0;
ds.rowStatus(idx) = SPxBasis::Desc::P_ON_UPPER;
newCoPrhs = theURbound[idx];
}
break;
case SPxBasis::Desc::P_ON_UPPER :
assert(rep() == COLUMN);
ds.rowStatus(idx) = dualRowStatus(idx);
if (lhs(idx) > -infinity)
theURbound[idx] = theLRbound[idx];
newCoPrhs = theLRbound[idx]; // slack !!
newUBbound = -lhs(idx);
newLBbound = -rhs(idx);
enterBound = -rhs(idx);
objChange -= newCoPrhs * rhs(idx);
break;
case SPxBasis::Desc::P_ON_LOWER :
assert(rep() == COLUMN);
ds.rowStatus(idx) = dualRowStatus(idx);
if (rhs(idx) < infinity)
theLRbound[idx] = theURbound[idx];
newCoPrhs = theURbound[idx]; // slack !!
newLBbound = -rhs(idx);
newUBbound = -lhs(idx);
enterBound = -lhs(idx);
objChange -= newCoPrhs * lhs(idx);
break;
case SPxBasis::Desc::P_FREE :
assert(rep() == COLUMN);
#if 1
throw SPxInternalCodeException("XLEAVE04 This should never happen.");
#else
MSG_ERROR( std::cerr << "ELEAVE53 ERROR: not yet debugged!" << std::endl; )
ds.rowStatus(idx) = dualRowStatus(idx);
newCoPrhs = theURbound[idx]; // slack !!
newUBbound = infinity;
newLBbound = -infinity;
enterBound = 0;
#endif
break;
case SPxBasis::Desc::P_FIXED :
assert(rep() == COLUMN);
MSG_ERROR( std::cerr << "ELEAVE54 "
<< "ERROR! Tried to put a fixed row variable into the basis: "
<< "idx=" << idx
<< ", lhs=" << lhs(idx)
<< ", rhs=" << rhs(idx) << std::endl; )
throw SPxInternalCodeException("XLEAVE05 This should never happen.");
default:
throw SPxInternalCodeException("XLEAVE06 This should never happen.");
}
MSG_DEBUG( std::cout << "DLEAVE55 SPxSolver::getLeaveVals2(): row " << idx
<< ": " << enterStat
<< " -> " << ds.rowStatus(idx)
<< " objChange: " << objChange
<< std::endl; )
}
else
{
assert(enterId.isSPxColId());
int idx = number(SPxColId(enterId));
SPxBasis::Desc::Status enterStat = ds.colStatus(idx);
switch (enterStat)
{
case SPxBasis::Desc::D_ON_UPPER :
assert(rep() == ROW);
newUBbound = 0;
newLBbound = -infinity;
ds.colStatus(idx) = SPxBasis::Desc::P_ON_LOWER;
newCoPrhs = theLCbound[idx];
break;
case SPxBasis::Desc::D_ON_LOWER :
assert(rep() == ROW);
newUBbound = infinity;
newLBbound = 0;
ds.colStatus(idx) = SPxBasis::Desc::P_ON_UPPER;
newCoPrhs = theUCbound[idx];
break;
case SPxBasis::Desc::D_FREE :
assert(rep() == ROW);
newUBbound = infinity;
newLBbound = -infinity;
newCoPrhs = theLCbound[idx];
ds.colStatus(idx) = SPxBasis::Desc::P_FIXED;
break;
case SPxBasis::Desc::D_ON_BOTH :
assert(rep() == ROW);
if (leaveMax * theCoPvec->delta()[idx] < 0)
{
newUBbound = 0;
newLBbound = -infinity;
ds.colStatus(idx) = SPxBasis::Desc::P_ON_LOWER;
newCoPrhs = theLCbound[idx];
}
else
{
newUBbound = infinity;
newLBbound = 0;
ds.colStatus(idx) = SPxBasis::Desc::P_ON_UPPER;
newCoPrhs = theUCbound[idx];
}
break;
case SPxBasis::Desc::P_ON_UPPER :
assert(rep() == COLUMN);
ds.colStatus(idx) = dualColStatus(idx);
if (SPxLP::lower(idx) > -infinity)
theLCbound[idx] = theUCbound[idx];
newCoPrhs = theUCbound[idx];
newUBbound = SPxLP::upper(idx);
newLBbound = SPxLP::lower(idx);
enterBound = SPxLP::upper(idx);
objChange -= newCoPrhs * enterBound;
break;
case SPxBasis::Desc::P_ON_LOWER :
assert(rep() == COLUMN);
ds.colStatus(idx) = dualColStatus(idx);
if (SPxLP::upper(idx) < infinity)
theUCbound[idx] = theLCbound[idx];
newCoPrhs = theLCbound[idx];
newUBbound = SPxLP::upper(idx);
newLBbound = SPxLP::lower(idx);
enterBound = SPxLP::lower(idx);
objChange -= newCoPrhs * enterBound;
break;
case SPxBasis::Desc::P_FREE :
assert(rep() == COLUMN);
ds.colStatus(idx) = dualColStatus(idx);
if (thePvec->delta()[idx] * leaveMax > 0)
newCoPrhs = theUCbound[idx];
else
newCoPrhs = theLCbound[idx];
newUBbound = SPxLP::upper(idx);
newLBbound = SPxLP::lower(idx);
enterBound = 0;
break;
case SPxBasis::Desc::P_FIXED :
assert(rep() == COLUMN);
MSG_ERROR( std::cerr << "ELEAVE56 "
<< "ERROR! Tried to put a fixed column variable into the basis. "
<< "idx=" << idx
<< ", lower=" << lower(idx)
<< ", upper=" << upper(idx) << std::endl; )
throw SPxInternalCodeException("XLEAVE07 This should never happen.");
default:
throw SPxInternalCodeException("XLEAVE08 This should never happen.");
}
MSG_DEBUG( std::cout << "DLEAVE57 SPxSolver::getLeaveVals2(): col " << idx
<< ": " << enterStat
<< " -> " << ds.colStatus(idx)
<< " objChange: " << objChange
<< std::endl; )
}
}
void SPxSolver::rejectLeave(
int leaveNum,
SPxId leaveId,
SPxBasis::Desc::Status leaveStat,
const SVector* //newVec
)
{
SPxBasis::Desc& ds = desc();
if (leaveId.isSPxRowId())
{
MSG_DEBUG( std::cout << "DLEAVE58 rejectLeave() : row " << leaveNum
<< ": " << ds.rowStatus(leaveNum)
<< " -> " << leaveStat << std::endl; )
if (leaveStat == SPxBasis::Desc::D_ON_BOTH)
{
if (ds.rowStatus(leaveNum) == SPxBasis::Desc::P_ON_LOWER)
theLRbound[leaveNum] = theURbound[leaveNum];
else
theURbound[leaveNum] = theLRbound[leaveNum];
}
ds.rowStatus(leaveNum) = leaveStat;
}
else
{
MSG_DEBUG( std::cout << "DLEAVE59 rejectLeave() : col " << leaveNum
<< ": " << ds.colStatus(leaveNum)
<< " -> " << leaveStat << std::endl; )
if (leaveStat == SPxBasis::Desc::D_ON_BOTH)
{
if (ds.colStatus(leaveNum) == SPxBasis::Desc::P_ON_UPPER)
theLCbound[leaveNum] = theUCbound[leaveNum];
else
theUCbound[leaveNum] = theLCbound[leaveNum];
}
ds.colStatus(leaveNum) = leaveStat;
}
}
void SPxSolver::computePrimalray4Row(Real direction)
{
Real sign = (direction > 0 ? 1.0 : -1.0);
primalRay.clear();
primalRay.setMax(coPvec().delta().size());
for( int i = 0; i < coPvec().delta().size(); ++i )
primalRay.add(coPvec().delta().index(i), sign * coPvec().delta().value(i));
}
void SPxSolver::computeDualfarkas4Col(Real direction)
{
Real sign = (direction > 0 ? -1.0 : 1.0);
dualFarkas.clear();
dualFarkas.setMax(coPvec().delta().size());
for( int i = 0; i < coPvec().delta().size(); ++i )
dualFarkas.add(coPvec().delta().index(i), sign * coPvec().delta().value(i));
}
bool SPxSolver::leave(int leaveIdx, bool polish)
{
assert(leaveIdx < dim() && leaveIdx >= 0);
assert(type() == LEAVE);
assert(initialized);
bool instable = instableLeave;
assert(!instable || instableLeaveNum >= 0);
/*
Before performing the actual basis update, we must determine, how this
is to be accomplished.
When using steepest edge pricing this solve is already performed by the pricer
*/
if (theCoPvec->delta().isSetup() && theCoPvec->delta().size() == 0)
{
coSolve(theCoPvec->delta(), unitVecs[leaveIdx]);
}
#ifdef ENABLE_ADDITIONAL_CHECKS
else
{
SSVector tmp(dim(), epsilon());
tmp.clear();
coSolve(tmp, unitVecs[leaveIdx]);
tmp -= theCoPvec->delta();
if (tmp.length() > leavetol()) {
// This happens very frequently and does usually not hurt, so print
// these warnings only with verbose level INFO2 and higher.
MSG_INFO2( (*spxout), (*spxout) << "WLEAVE60 iteration=" << basis().iteration()
<< ": coPvec.delta error = " << tmp.length()
<< std::endl; )
}
}
#endif // ENABLE_ADDITIONAL_CHECKS
setupPupdate();
assert(thePvec->isConsistent());
assert(theCoPvec->isConsistent());
SPxBasis::Desc::Status leaveStat; // status of leaving var
SPxId leaveId; // id of leaving var
SPxId none; // invalid id used if leave fails
Real leaveMax; // maximium lambda of leaving var
Real leavebound; // current fVec value of leaving var
int leaveNum; // number of leaveId in bounds
Real objChange = 0.0; // amount of change in the objective function
getLeaveVals(leaveIdx, leaveStat, leaveId, leaveMax, leavebound, leaveNum, objChange);
if (!polish && m_numCycle > m_maxCycle)
{
if (leaveMax > 0)
perturbMaxLeave();
else
perturbMinLeave();
//@ m_numCycle /= 2;
// perturbation invalidates the currently stored nonbasic value
forceRecompNonbasicValue();
}
//@ testBounds();
Real enterVal = leaveMax;
boundflips = 0;
Real oldShift = theShift;
SPxId enterId = theratiotester->selectEnter(enterVal, leaveIdx, polish);
if (NE(theShift, oldShift))
{
MSG_DEBUG( std::cout << "DLEAVE71 trigger recomputation of nonbasic value due to shifts in ratiotest" << std::endl; )
forceRecompNonbasicValue();
}
assert(!enterId.isValid() || !isBasic(enterId));
instableLeaveNum = -1;
instableLeave = false;
/*
No variable could be selected to enter the basis and even the leaving
variable is unbounded.
*/
if (!enterId.isValid())
{
/* the following line originally was below in "rejecting leave" case;
we need it in the unbounded/infeasible case, too, to have the
correct basis size */
rejectLeave(leaveNum, leaveId, leaveStat);
change(-1, none, 0);
objChange = 0.0; // the nonbasicValue is not supposed to be updated in this case
if (polish)
return false;
if (NE(enterVal, leaveMax))
{
MSG_DEBUG( std::cout << "DLEAVE61 rejecting leave A (leaveIdx=" << leaveIdx
<< ", theCoTest=" << theCoTest[leaveIdx] << ")"
<< std::endl; )
/* In the LEAVE algorithm, when for a selected leaving variable we find only
an instable entering variable, then the basis change is not conducted.
Instead, we save the leaving variable's index in instableLeaveNum and scale
theCoTest[leaveIdx] down by some factor, hoping to find a different leaving
variable with a stable entering variable.
If this fails, however, and no more leaving variable is found, we have to
perform the instable basis change using instableLeaveNum. In this (and only
in this) case, the flag instableLeave is set to true.
enterVal != leaveMax is the case that selectEnter has found only an instable entering
variable. We store this leaving variable for later -- if we are not already in the
instable case: then we continue and conclude unboundedness/infeasibility */
if (!instable)
{
instableLeaveNum = leaveIdx;
// Note: These changes do not survive a refactorization
instableLeaveVal = theCoTest[leaveIdx];
theCoTest[leaveIdx] = instableLeaveVal / 10.0;
return true;
}
}
if (lastUpdate() > 1)
{
MSG_INFO3( (*spxout), (*spxout) << "ILEAVE01 factorization triggered in "
<< "leave() for feasibility test" << std::endl; )
try
{
factorize();
}
catch( const SPxStatusException& E )
{
// don't exit immediately but handle the singularity correctly
assert(SPxBasis::status() == SPxBasis::SINGULAR);
MSG_INFO3( (*spxout), (*spxout) << "Caught exception in factorization: " << E.what() << std::endl; )
}
/* after a factorization, the leaving column/row might not be infeasible or suboptimal anymore, hence we do
* not try to call leave(leaveIdx), but rather return to the main solving loop and call the pricer again
*/
return true;
}
/* do not exit with status infeasible or unbounded if there is only a very small violation */
if (spxAbs(enterVal) < leavetol())
{
MSG_INFO3( (*spxout), (*spxout) << "ILEAVE11 clean up step to reduce numerical errors" << std::endl; )
computeFrhs();
SPxBasis::solve(*theFvec, *theFrhs);
computeFtest();
return true;
}
MSG_INFO3( (*spxout), (*spxout) << "ILEAVE02 unboundedness/infeasibility found "
<< "in leave()" << std::endl; )
if (rep() != COLUMN)
{
computePrimalray4Row(enterVal);
setBasisStatus(SPxBasis::UNBOUNDED);
}
else
{
computeDualfarkas4Col(enterVal);
setBasisStatus(SPxBasis::INFEASIBLE);
}
return false;
}
else
{
/*
If an entering variable has been found, a regular basis update is to
be performed.
*/
if (enterId != baseId(leaveIdx))
{
const SVector& newVector = *enterVector(enterId);
// update feasibility vectors
if( solveVector2 != NULL && solveVector3 != NULL )
{
assert(solveVector2->isConsistent());
assert(solveVector2rhs->isSetup());
assert(solveVector3->isConsistent());
assert(solveVector3rhs->isSetup());
assert(boundflips > 0);
SPxBasis::solve4update(theFvec->delta(),
*solveVector2,
*solveVector3,
newVector,
*solveVector2rhs,
*solveVector3rhs);
// perform update of basic solution
primVec -= (*solveVector3);
MSG_DEBUG( std::cout << "ILBFRT02 breakpoints passed / bounds flipped = " << boundflips << std::endl; )
totalboundflips += boundflips;
}
else if( solveVector2 != NULL )
{
assert(solveVector2->isConsistent());
assert(solveVector2rhs->isSetup());
SPxBasis::solve4update(theFvec->delta(),
*solveVector2,
newVector,
*solveVector2rhs);
}
else if( solveVector3 != NULL )
{
assert(solveVector3->isConsistent());
assert(solveVector3rhs->isSetup());
assert(boundflips > 0);
SPxBasis::solve4update(theFvec->delta(),
*solveVector3,
newVector,
*solveVector3rhs);
// perform update of basic solution
primVec -= (*solveVector3);
MSG_DEBUG( std::cout << "ILBFRT02 breakpoints passed / bounds flipped = " << boundflips << std::endl; )
totalboundflips += boundflips;
}
else
SPxBasis::solve4update (theFvec->delta(), newVector);
#ifdef ENABLE_ADDITIONAL_CHECKS
{
SSVector tmp(dim(), epsilon());
SPxBasis::solve(tmp, newVector);
tmp -= fVec().delta();
if (tmp.length() > entertol()) {
// This happens very frequently and does usually not hurt, so print
// these warnings only with verbose level INFO2 and higher.
MSG_INFO2( (*spxout), (*spxout) << "WLEAVE62\t(" << tmp.length() << ")\n"; )
}
}
#endif // ENABLE_ADDITIONAL_CHECKS
if (spxAbs(theFvec->delta()[leaveIdx]) < reject_leave_tol)
{
if (instable)
{
/* We are in the case that for all leaving variables only instable entering
variables were found: Thus, above we already accepted such an instable
entering variable. Now even this seems to be impossible, thus we conclude
unboundedness/infeasibility. */
MSG_INFO3( (*spxout), (*spxout) << "ILEAVE03 unboundedness/infeasibility found "
<< "in leave()" << std::endl; )
rejectLeave(leaveNum, leaveId, leaveStat);
change(-1, none, 0);
objChange = 0.0; // the nonbasicValue is not supposed to be updated in this case
/**@todo if shift() is not zero we must not conclude unboundedness */
if (rep() == ROW)
{
computePrimalray4Row(enterVal);
setBasisStatus(SPxBasis::UNBOUNDED);
}
else
{
computeDualfarkas4Col(enterVal);
setBasisStatus(SPxBasis::INFEASIBLE);
}
return false;
}
else
{
theFvec->delta().clear();
rejectLeave(leaveNum, leaveId, leaveStat, &newVector);
change(-1, none, 0);
objChange = 0.0; // the nonbasicValue is not supposed to be updated in this case
MSG_DEBUG( std::cout << "DLEAVE63 rejecting leave B (leaveIdx=" << leaveIdx
<< ", theCoTest=" << theCoTest[leaveIdx]
<< ")" << std::endl; )
// Note: These changes do not survive a refactorization
theCoTest[leaveIdx] *= 0.01;
return true;
}
}
// process leaving variable
if (leavebound > epsilon() || leavebound < -epsilon())
theFrhs->multAdd(-leavebound, baseVec(leaveIdx));
// process entering variable
Real enterBound;
Real newUBbound;
Real newLBbound;
Real newCoPrhs;
try
{
getLeaveVals2(leaveMax, enterId, enterBound, newUBbound, newLBbound, newCoPrhs, objChange);
}
catch( const SPxException& F )
{
rejectLeave(leaveNum, leaveId, leaveStat);
change(-1, none, 0);
objChange = 0.0; // the nonbasicValue is not supposed to be updated in this case
throw F;
}
theUBbound[leaveIdx] = newUBbound;
theLBbound[leaveIdx] = newLBbound;
(*theCoPrhs)[leaveIdx] = newCoPrhs;
if (enterBound > epsilon() || enterBound < -epsilon())
theFrhs->multAdd(enterBound, newVector);
// update pricing vectors
theCoPvec->value() = enterVal;
thePvec->value() = enterVal;
if (enterVal > epsilon() || enterVal < -epsilon())
doPupdate();
// update feasibility vector
theFvec->value() = -((*theFvec)[leaveIdx] - leavebound)
/ theFvec->delta()[leaveIdx];
theFvec->update();
(*theFvec)[leaveIdx] = enterBound - theFvec->value();
updateFtest();
// update objective funtion value
updateNonbasicValue(objChange);
// change basis matrix
change(leaveIdx, enterId, &newVector, &(theFvec->delta()));
}
/*
No entering vector has been selected from the basis. However, if the
shift amount for |coPvec| is bounded, we are in the case, that the
entering variable is moved from one bound to its other, before any of
the basis feasibility variables reaches their bound. This may only
happen in primal/columnwise case with upper and lower bounds on
variables.
*/
else
{
// @todo update obj function value here!!!
assert(rep() == ROW);
SPxBasis::Desc& ds = desc();
change(leaveIdx, none, 0);
if (leaveStat == SPxBasis::Desc::P_ON_UPPER)
{
if (leaveId.isSPxRowId())
{
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
(*theCoPrhs)[leaveIdx] = theLRbound[leaveNum];
}
else
{
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_LOWER;
(*theCoPrhs)[leaveIdx] = theLCbound[leaveNum];
}
theUBbound[leaveIdx] = 0;
theLBbound[leaveIdx] = -infinity;
}
else
{
assert( leaveStat == SPxBasis::Desc::P_ON_LOWER );
if (leaveId.isSPxRowId())
{
ds.rowStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
(*theCoPrhs)[leaveIdx] = theURbound[leaveNum];
}
else
{
ds.colStatus(leaveNum) = SPxBasis::Desc::P_ON_UPPER;
(*theCoPrhs)[leaveIdx] = theUCbound[leaveNum];
}
theUBbound[leaveIdx] = infinity;
theLBbound[leaveIdx] = 0;
}
// update copricing vector
theCoPvec->value() = enterVal;
thePvec->value() = enterVal;
if (enterVal > epsilon() || enterVal < -epsilon())
doPupdate();
// update feasibility vectors
theFvec->value() = 0;
assert(theCoTest[leaveIdx] < 0.0);
m_pricingViol += theCoTest[leaveIdx];
theCoTest[leaveIdx] *= -1;
}
if ((leaveMax > entertol() && enterVal <= entertol()) || (leaveMax < -entertol() && enterVal >= -entertol()))
{
if ((theUBbound[leaveIdx] < infinity || theLBbound[leaveIdx] > -infinity)
&& leaveStat != SPxBasis::Desc::P_FREE
&& leaveStat != SPxBasis::Desc::D_FREE)
{
m_numCycle++;
leaveCycles++;
}
}
else
m_numCycle /= 2;
#ifdef ENABLE_ADDITIONAL_CHECKS
{
DVector tmp = fVec();
multBaseWith(tmp);
tmp -= fRhs();
if (tmp.length() > entertol())
{
// This happens very frequently and does usually not hurt, so print
// these warnings only with verbose level INFO2 and higher.
MSG_INFO2( (*spxout), (*spxout) << "WLEAVE64\t" << basis().iteration()
<< ": fVec error = " << tmp.length() << std::endl; )
SPxBasis::solve(tmp, fRhs());
tmp -= fVec();
MSG_INFO2( (*spxout), (*spxout) << "WLEAVE65\t(" << tmp.length() << ")\n"; )
}
}
#endif // ENABLE_ADDITIONAL_CHECKS
return true;
}
}
} // namespace soplex
|
; void SMS_VRAMmemset(unsigned int dst,unsigned char value,unsigned int size)
SECTION code_clib
SECTION code_SMSlib
PUBLIC SMS_VRAMmemset
EXTERN asm_SMSlib_VRAMmemset
SMS_VRAMmemset:
pop af
pop bc
pop de
pop hl
push hl
push de
push bc
push af
jp asm_SMSlib_VRAMmemset
|
db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00
db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00
db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00
db #00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00,#00
db #01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01
db #01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01
db #01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01
db #01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01,#01
db #02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02
db #02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02
db #02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02
db #02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02,#02
db #03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03
db #03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03
db #03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03
db #03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03,#03
|
/*!
* \copy
* Copyright (c) 2008-2013, Cisco Systems
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* read_config.h
*
* Abstract
* Class for reading parameter settings in a configure file.
*
* History
* 08/18/2008 Created
*
*****************************************************************************/
#if !defined(WIN32)
#include <string.h>
#include <stdio.h>
#endif
#include "read_config.h"
CReadConfig::CReadConfig (const char* kpConfigFileName)
: m_pCfgFile (0)
, m_strCfgFileName (kpConfigFileName)
, m_ulLines (0) {
if (strlen (kpConfigFileName) > 0) { // FIXME: To check validation in configure file name
m_pCfgFile = fopen (kpConfigFileName, "r");
}
}
CReadConfig::~CReadConfig() {
if (m_pCfgFile) {
fclose (m_pCfgFile);
m_pCfgFile = NULL;
}
}
long CReadConfig::ReadLine (string* pStr, const int kiValSize/* = 4*/) {
if (m_pCfgFile == NULL || pStr == NULL || kiValSize <= 1)
return 0;
string* strTags = &pStr[0];
int iTagNum = 0, iNum = 0;
bool bCommentFlag = false;
while (iNum < kiValSize) {
pStr[iNum] = "";
++ iNum;
}
do {
const char kChar = (char)fgetc (m_pCfgFile);
if (kChar == '\n' || feof (m_pCfgFile)) {
++ m_ulLines;
break;
}
if (kChar == '#')
bCommentFlag = true;
if (!bCommentFlag) {
if (kChar == '\t' || kChar == ' ') {
if (iTagNum >= kiValSize)
break;
if (! (*strTags).empty()) {
++ iTagNum;
strTags = &pStr[iTagNum];
}
} else
*strTags += kChar;
}
} while (true);
return 1 + iTagNum;
}
const bool CReadConfig::EndOfFile() {
if (m_pCfgFile == NULL)
return true;
return feof (m_pCfgFile) ? true : false;
}
const int CReadConfig::GetLines() {
return m_ulLines;
}
const bool CReadConfig::ExistFile() {
return (m_pCfgFile != NULL);
}
const string& CReadConfig::GetFileName() {
return m_strCfgFileName;
}
|
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "operation/shape.h"
#include "driver/intel_openvino/converter/converter.h"
#include "utility/debug.h"
#include "utility/logging.h"
namespace nnadapter {
namespace intel_openvino {
int ConvertShape(Converter* converter, core::Operation* operation) {
SHAPE_OPERATION_EXTRACT_INPUTS_OUTPUTS
auto input_tensor = converter->GetMappedTensor(input_operand);
if (!input_tensor) {
input_tensor = converter->ConvertOperand(input_operand);
}
auto shape_op = std::make_shared<default_opset::ShapeOf>(
*input_tensor, ConvertToOVElementType(dtype));
MAP_OUTPUT(output_operand, shape_op, 0);
return NNADAPTER_NO_ERROR;
}
} // namespace intel_openvino
} // namespace nnadapter
|
;;; am2302.asm
;;- Subroutines for AM2303 (aka DHT22) relative humidity (RH) and temperature sensor
;;- This code is a part of [[../][pAVRlib]].
;;-
;;- * Requirement
;;- - [[../../wait][wait.asm]] (a part of pAVRlib)
;;-
;;- * How to use
;;- Define ~F_CPU~ (frequency of CPU), ~AM_DDR~, ~AM_PORT~, ~AM_PIN~
;;- and ~AM_SDA~ before you call ~AM2302_READ~.
;;-
;;- For example, to use PB0 as SDA for AM2302:
;;-
;;- #+BEGIN_SRC asm
;;- .equ F_CPU = 1000000 ; 1 MHz
;;-
;;- .equ AM_DDR = DDRB
;;- .equ AM_PORT = PORTB
;;- .equ AM_PIN = PINB
;;- .equ AM_SDA = 0
;;- #+END_SRC
;;-
;;- Note that ~F_CPU~ must be > 100000 (100 kHz) (theoretically. But practically > 300 kHz ?).
;;- (This module was tested only at 1 MHz.)
;;-
;;; HIGH_THRESHOLD:
;;; The high time for "0" is 22-30us (typ. 26us) and for "1" is 68-75us (typ. 70us)
;;; (See datasheet of AM2302).
;;; It takes 5 clocks @ 1 MHz to read a "H" in the subroutine `_readHi'.
;;; In this program 50us is chosen as the threshold.
#ifdef __GNUC__
.global AM2302_READ
#define __SFR_OFFSET 0
#include <avr/io.h>
#define HumH r25
#define HumL r24
#define TmpH r23
#define TmpL r22
#define HIGH_THRESHOLD (10 * F_CPU / 1000000)
#else
.def HumH = r25
.def HumL = r24
.def TmpH = r23
.def TmpL = r22
.equ HIGH_THRESHOLD = (10 * F_CPU / 1000000)
#endif
;;- * Subroutine
;;-
;;- ** ~long AM2302_READ()~ (in: (none), out: r25-r22 (HumH, HumL, TmpH, TmpL))
;;- reads data from AM2302.
;;- This returns r25:r24:r23:r22 = ff:ff:ff:ff ($-1$ as long) if parity error occured.
;;- This returns also a raw parity value in r21 if the program is assembled with ~AM2303_DEBUG~.
;;-
AM2302_READ:
push r18 ; parity
push r19 ; loop counter
push r20 ; pulse length
sbi AM_DDR, AM_SDA
sbi AM_PORT, AM_SDA
rcall Wait1sec
rcall Wait1sec
;; start signal
cbi AM_PORT, AM_SDA ; output '0'
rcall Wait1ms
sbi AM_PORT, AM_SDA ; output '1'
cbi AM_DDR, AM_SDA ; set port as input
cbi AM_PORT, AM_SDA ; Hi-Z
;; response signal
;; wait for '0'
_am2303_wait_rel:
sbic AM_PIN, AM_SDA
rjmp _am2303_wait_rel
;; wait for '1'
_am2303_wait_reh:
sbis AM_PIN, AM_SDA
rjmp _am2303_wait_reh
_am2303_wait_low:
sbic AM_PIN, AM_SDA
rjmp _am2303_wait_low
;; main
ldi r19, 40 ; the number of bits to read
_am2302_read_loop1:
_am2302_wait_high:
sbis AM_PIN, AM_SDA
rjmp _am2302_wait_high
rcall _am2302_readHi
cpi r20, HIGH_THRESHOLD
;; C = 1 if r20 < HIGH_THRESHOLD
;; i.e. inverted values are stored in the registers.
rol r18
rol TmpL
rol TmpH
rol HumL
rol HumH
dec r19
brne _am2302_read_loop1
com HumH
com HumL
com TmpH
com TmpL
com r18
.ifdef AM2303_DEBUG
mov r21, r18 ; raw parity value
.endif
;; parity check
sub r18, HumH
sub r18, HumL
sub r18, TmpH
sub r18, TmpL
breq _am2302_read_exit
ldi r18, 0xff
mov HumH, r18
mov HumL, r18
mov TmpH, r18
mov TmpL, r18
_am2302_read_exit:
pop r20
pop r19
pop r18
ret
_am2302_readHi:
ldi r20, 0 ; 1 clock
_am2302_rH_loop1:
sbis AM_PIN, AM_SDA ; 1 clock if not skip / 2 clock if skip
ret
inc r20 ; 1 clock
rjmp _am2302_rH_loop1 ; 2 clock
;;; ------------------------------------------------------------
;;; for debug
;;; (requires usart.asm)
.ifdef AM2303_DEBUG
.ifdef AM2303_DEBUG_USE_USART
AM2302_USART_RAWDATA:
push r16
mov r16, r24 ; save the value of r24
push r31
push r30
clr r31
ldi r30, 26 ; from r25 (to r21)
ldi r24, '['
rcall USART_TRANSMIT
_am2302_rawdata_loop:
mov r24, r16 ; restore r24
ld r24, -Z
rcall USART_PUTHEX
cpi r30, 21
breq _am2302_rawdata_exit
ldi r24, ' '
rcall USART_TRANSMIT
rjmp _am2302_rawdata_loop
_am2302_rawdata_exit:
ldi r24, ']'
rcall USART_TRANSMIT
pop r30
pop r31
mov r24, r16
pop r16
ret
.endif
.endif
;;-
;;- * Examples
;;-
;;- !see ../examples/am2302-test.asm
;;-
;;- !see ../examples-C/am2302-test.c
;;-
|
.size 8000
.text@49
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld b, 90
call lwaitly_b
ld a, 11
ldff(40), a
ld hl, 8000
ld b, 08
lbegin_settile0data:
ld a, 00
ld(hl++), a
ld a, 7e
ld(hl++), a
dec b
jrnz lbegin_settile0data
ld b, 08
lbegin_settile1data:
ld a, 00
ld(hl++), a
ld a, 81
ld(hl++), a
dec b
jrnz lbegin_settile1data
ld b, 08
lbegin_settile2data:
ld a, ff
ld(hl++), a
ld a, 81
ld(hl++), a
dec b
jrnz lbegin_settile2data
ld b, 08
lbegin_settile3data:
ld a, ff
ld(hl++), a
ld a, 7e
ld(hl++), a
dec b
jrnz lbegin_settile3data
ld c, 12
ld hl, 9800
lbegin_set_bgmap:
ld b, 06
ld a, 02
lbegin_set_bgmapline_tilenos0to11:
ld(hl++), a
inc a
ld(hl++), a
dec a
dec b
jrnz lbegin_set_bgmapline_tilenos0to11
ld b, 0a
lbegin_set_bgmapline_tilenos12to31:
xor a, a
ld(hl++), a
inc a
ld(hl++), a
dec b
jrnz lbegin_set_bgmapline_tilenos12to31
dec c
jrnz lbegin_set_bgmap
ld a, e4
ldff(47), a
ld a, 80
ldff(68), a
ld c, 69
xor a, a
ldff(c), a
ldff(c), a
ld a, 94
ldff(c), a
ld a, 52
ldff(c), a
ld a, 08
ldff(c), a
ld a, 21
ldff(c), a
ld a, ff
ldff(c), a
ldff(c), a
ld a, 20
ldff(41), a
ld a, 02
ldff(ff), a
ld c, 43
ld a, 91
ldff(40), a
ei
ld a, 07
.text@1000
lstatint:
ldff(c), a
ld a, 04
.text@1020
ld b, 02
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
sub a, b
ldff(c), a
.text@108d
ldff a, (41)
and a, 07
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
COMMENT @----------------------------------------------------------------------
Copyright (c) GeoWorks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Kernel/Graphics
FILE: graphicsFontC.asm
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
DESCRIPTION:
This file contains C interface routines for the font.h routines
$Id: graphicsFontC.asm,v 1.1 97/04/05 01:13:32 newdeal Exp $
------------------------------------------------------------------------------@
SetGeosConvention
C_Graphics segment resource
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrEnumFonts
C DECLARATION: extern word
_far _pascal GrEnumFonts(FontEnumStruct _far *buffer,
word size, word flags, word family);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRENUMFONTS proc far buffer:fptr.FontEnumStruct, bsize:word,
flags:word, family:word
uses di, es
.enter
les di, buffer
mov cx, bsize
mov dl, flags.low
mov dh, family.low
call GrEnumFonts
mov_trash ax, cx
.leave
ret
GRENUMFONTS endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrCheckFontAvailID
C DECLARATION: extern FontID
_far _pascal GrCheckFontAvailID(word flags, word family,
FontID id);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRCHECKFONTAVAILID proc far
C_GetThreeWordArgs dx, ax, cx, bx ;dx = flags, ax = fam, cx = id
mov dh, al
call GrCheckFontAvail
mov_trash ax, cx
ret
GRCHECKFONTAVAILID endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrCheckFontAvailName
C DECLARATION: extern FontID
_far _pascal GrCheckFontAvailName(word flags, word family,
const char _far *name);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRCHECKFONTAVAILNAME proc far flags:word, family:word,
fname:fptr.char
uses si, ds
.enter
lds si, fname
mov dl, flags.low
mov dh, family.low
call GrCheckFontAvail
mov_trash ax, cx
.leave
ret
GRCHECKFONTAVAILNAME endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrFindNearestPointsize
C DECLARATION: extern Boolean
_far _pascal GrFindNearestPointsize(FontID id,
dword sizeSHL16, word styles,
word _far *styleFound,
dword _far *sizeFoundSHL16);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRFINTNEARESTPOINTSIZE proc far id:word, sizeSHL16:dword, styles:word,
styleFound:fptr, sizeFoundSHL16:fptr
uses si, ds
.enter
mov cx, id
mov dx, sizeSHL16.high
mov ah, (sizeSHL16.low).high
mov al, styles.low
call GrFindNearestPointsize
lds si, styleFound
mov ds:[si], al
lds si, sizeFoundSHL16
mov ds:[si].high, dx
clr al
mov ds:[si].low, ax
clr ax
cmp cx, FID_INVALID
jz done
dec ax
done:
.leave
ret
GRFINTNEARESTPOINTSIZE endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetDefFontID
C DECLARATION: extern FontID
_far _pascal GrGetDefFontID(dword _far *sizeSHL16);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRGETDEFFONTID proc far
C_GetOneDWordArg cx, ax, dx,bx ;cx = seg, ax = offset
push di, es
mov es, cx
mov_trash di, ax
call GrGetDefFontID
clr al
stosw
mov_trash ax, dx
stosw
pop di, es
mov_trash ax, cx
ret
GRGETDEFFONTID endp
C_Graphics ends
;---
C_Common segment resource
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrCharMetrics
C DECLARATION: extern dword
_far _pascal GrCharMetrics(GStateHandle gstate,
GCM_info info, word ch);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRCHARMETRICS proc far
C_GetThreeWordArgs bx, cx, ax, dx ;bx = gstate, cx = info, ax=ch
push si, di
mov di, bx
mov si, cx
call GrCharMetrics
tst al
jz return0
CMetricsCommon label far
test si, GFMI_ROUNDED
jnz rounded
clr al
done:
pop si, di
ret
rounded:
clr ax
xchg ax, dx ;ax = result, dx = 0
tst ax
jns done
dec dx ;sign extend
jmp done
return0:
clr ax
clr dx
jmp done
GRCHARMETRICS endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrFontMetrics
C DECLARATION: extern dword
_far _pascal GrFontMetrics(GStateHandle gstate,
GCM_info info);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 3/91 Initial version
------------------------------------------------------------------------------@
GRFONTMETRICS proc far
C_GetTwoWordArgs bx, ax, cx,dx ;bx = gstate, ax = info
push si, di
mov di, bx
mov_trash si, ax
call GrFontMetrics
jmp CMetricsCommon
GRFONTMETRICS endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetFontName
C DECLARATION: extern word
_pascal GrGetFontName(FontID id,
char *name);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRGETFONTNAME proc far id:word, fname:fptr.char
uses ds, si
.enter
lds si, ss:fname
mov cx, ss:id
call GrGetFontName
mov_trash ax, cx
.leave
ret
GRGETFONTNAME endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrSetFontWeight
C DECLARATION: extern void
_far _pascal GrSetFontWeight(GStateHandle gstate,
FontWeight weight);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRSETFONTWEIGHT proc far
C_GetTwoWordArgs bx, ax, cx,dx ;ax <- FontWeight
xchg bx, di ;di <- handle of GState
call GrSetFontWeight
xchg bx, di ;bx <- saved bx
ret
GRSETFONTWEIGHT endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrSetFontWidth
C DECLARATION: extern void
_far _pascal GrSetFontWidth(GStateHandle gstate,
FontWidth width);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRSETFONTWIDTH proc far
C_GetTwoWordArgs bx, ax, cx,dx ;ax <- FontWidth
xchg bx, di ;di <- handle of GState
call GrSetFontWidth
xchg bx, di ;bx <- saved bx
ret
GRSETFONTWIDTH endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrSetSuperscriptAttr
C DECLARATION: extern void
_far _pascal GrSetSuperscriptAttr(GStateHandle gstate,
SuperscriptAttrs attrs);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRSETSUPERSCRIPTATTR proc far
C_GetTwoWordArgs bx, ax, cx,dx ;al <- position, ah <- size
xchg bx, di ;di <- handle of GState
call GrSetSuperscriptAttr
xchg bx, di ;bx <- saved bx
ret
GRSETSUPERSCRIPTATTR endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrSetSubscriptAttr
C DECLARATION: extern void
_far _pascal GrSetSubscriptAttr(GStateHandle gstate,
SubscriptAttrs attrs);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRSETSUBSCRIPTATTR proc far
C_GetTwoWordArgs bx, ax, cx,dx ;al <- position, ah <- size
xchg bx, di ;di <- handle of GState
call GrSetSubscriptAttr
xchg bx, di ;bx <- saved bx
ret
GRSETSUBSCRIPTATTR endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetFontWeight
C DECLARATION: extern FontWeight
_far _pascal GrGetFontWeight(GStateHandle gstate);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRGETFONTWEIGHT proc far
C_GetOneWordArg bx, cx,dx ;bx <- handle of GState
xchg bx, di ;di <- handle of GState
call GrGetFontWeight
xchg bx, di ;bx <- saved bx
ret
GRGETFONTWEIGHT endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetFontWidth
C DECLARATION: extern FontWidth
_far _pascal GrGetFontWidth(GStateHandle gstate);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRGETFONTWIDTH proc far
C_GetOneWordArg bx, cx,dx ;bx <- handle of GState
xchg bx, di ;di <- handle of GState
call GrGetFontWeight
xchg bx, di ;bx <- saved bx
ret
GRGETFONTWIDTH endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetSuperscriptAttr
C DECLARATION: extern ScriptAttrAsWord
_far _pascal GrGetSuperscriptAttr(GStateHandle gstate);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRGETSUPERSCRIPTATTR proc far
C_GetOneWordArg bx, cx,dx ;bx <- handle of GState
xchg bx, di ;di <- handle of GState
call GrGetSuperscriptAttr
xchg bx, di ;bx <- saved bx
ret
GRGETSUPERSCRIPTATTR endp
COMMENT @----------------------------------------------------------------------
C FUNCTION: GrGetSubscriptAttr
C DECLARATION: extern ScriptAttrAsWord
_far _pascal GrGetSubscriptAttr(GStateHandle gstate);
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Gene 1/92 Initial version
------------------------------------------------------------------------------@
GRGETSUBSCRIPTATTR proc far
C_GetOneWordArg bx, cx,dx ;bx <- handle of GState
xchg bx, di ;di <- handle of GState
call GrGetSubscriptAttr
xchg bx, di ;bx <- saved bx
ret
GRGETSUBSCRIPTATTR endp
C_Common ends
SetDefaultConvention
|
; String Manipulation Code
; Started 05-Jan-20
;
; Initials: NB = Nolan Baker
; V1.0 - 05-Jan-20 : Original Release - NB
;
; Library Subroutines:
; str_Copy
; Copy a string from hl to de
; Entry: hl = src string, de = dest string
; str_Length
; Length of a string
; Entry: hl = string
; Return: de = length
; str_FromArray
; gets string by index
; Entry: bc = index, hl = string array
; Return: hl = string at index bc
; str_CopyLine
; Copies l(\n) from hl to de
; Entry: hl = src string, de = dest string
; Return: bc = length of line, hl = start of next line
; str_Append
; Appends one string to another
; Entry: hl = append string, de = dest string
; str_AppendChar
; Appends a character to a string
; Entry: a = character, hl = string
; str_Replace
; Replaces string bc in source hl with string af in destination de
; Entry: hl = src string, de = dest string, bc = replace string, af = with string
; str_Number
; Converts number hl to string de
; Entry: hl = 16 bit number, de = dest string
; str_Number24
; Converts number ehl to string bc
; Entry: ehl = 24 bit number, bc = dest string
IF !DEF(STRINGS_ASM)
STRINGS_ASM SET 1
rev_Check_strings_asm: MACRO
IF \1 > 1
WARN "Version \1 or later of 'strings.asm' is required."
ENDC
ENDM
INCLUDE "src/math.asm"
rev_Check_math_asm 1
SECTION "Strings Code", ROM0
;***************************************************************************
;
; str_Copy - Copy a string
;
; input:
; hl - src string
; de - dst string
;
;***************************************************************************
str_Copy::
ld a, [hli]
ld [de], a
inc de
and a
jr nz, str_Copy
ret
;***************************************************************************
;
; str_Length - Length of a string
;
; input:
; hl - string
; output:
; de - length
;
;***************************************************************************
str_Length::
ld de, 0
.loop
ld a, [hli]
and a
ret z
inc de
jr .loop
;***************************************************************************
;
; str_FromArray - gets string at index bc using separator a
;
; input:
; a - separatior (0 for strings, '\n' for lines, ' ' for words)
; bc - index
; hl - string array
; output:
; hl - string at index bc
;
;***************************************************************************
str_FromArray::
ld d, a;separator
inc bc
jr .test
.loop; find separator
ld a, [hli];get next character
cp a, d;is it a separator?
jr nz, .loop; if not, check the next character
.test; if so, check bc == 0
xor a
dec bc
cp a, b
jr nz, .loop
cp a, c
jr nz, .loop
ret
;***************************************************************************
;
; str_CopyLine - Copies line
;
; input:
; a - end character
; hl - string
; de - dest
; output:
; bc - length of line
; hl - start of next line
;
;***************************************************************************
str_CopyLine::
ld bc, 0
.loop
ld a, [hli]
cp "\n"
ret z
and a
ret z
ld [de], a
inc de
inc bc
jr .loop
;***************************************************************************
;
; str_Append - Appends string hl to de
;
; input:
; hl - append string
; de - dest string
;
;***************************************************************************
str_Append::
ld a, [de]
inc de
and a
jr nz, str_Append
dec de
call str_Copy
ret
;***************************************************************************
;
; str_AppendChar - Appends char a to hl
;
; input:
; a - character
; hl - string
;
;***************************************************************************
str_AppendChar:
push af;char
.loop
ld a, [hli]
and a
jr nz, .loop
xor a
ld [hld], a
pop af;char
ld [hl], a
ret
;***************************************************************************
;
; str_Replace - Replaces %s in src with bc, results in dest
;
; input:
; hl - src string
; de - dest string
; bc - replace data
;
;***************************************************************************
str_Replace::
ld a, [hli]
and a
jr z, .done
cp "%"
jp nz, .copyToDest
ld a, [hli]
cp "s"
jr z, .stringReplace
dec hl
jr str_Replace
.copyToDest
ld [de], a
inc de
jr str_Replace
.stringReplace
ld a, [bc]
and a
jr z, str_Copy
ld [de], a
inc bc
inc de
jr .stringReplace
.done
ld [de], a
ret
;***************************************************************************
;
; str_Number - converts number hl to string de
;
; input:
; hl - number
; de - dest string
;
;***************************************************************************
str_Number::
ld a, h ; if hl == 0, return "0",0
and a
jr nz, .skip
ld a, l
and a
jr nz, .skip
ld a, "0"
ld [de], a
inc de
xor a
ld [de], a
ret
.skip
push de ;dest string
ld c, 0 ;num digits
.divLoop
push bc
ld c, 10
call math_Divide
add a, 48;convert num to string
ld [de], a
inc de
pop bc
inc c ;num digits
ld a, h ; if hl > 0, loop
and a
jr nz, .divLoop
ld a, l
and a
jr nz, .divLoop
pop hl ;dest string
xor a
ld [de], a;terminate string
ld a, c
cp 1
ret z ;no need to swap if only one digit
push de
srl c;num digits / 2
dec de
.swapLoop
ld a, [hl]
ld b, a
ld a, [de]
ld [hli], a
ld a, b
ld [de], a
dec de
dec c
jr nz, .swapLoop
pop de
ret
;***************************************************************************
;
; str_Number24 - converts number ehl to string bc
;
; input:
; ehl - number
; bc - dest string
;
;***************************************************************************
str_Number24::
ld d, 0
ld a, e ; if ehl == 0, return "0",0
and a
jr nz, .skip
ld a, h
and a
jr nz, .skip
ld a, l
and a
jr nz, .skip
ld a, "0"
ld [bc], a
inc bc
xor a
ld [bc], a
ret
.skip
xor a
push bc ;dest string start
push af ;num digits
push bc ;dest string
.divLoop
ld d, 10
call math_Divide24
add a, "0";convert num to string
pop bc;dest string
ld [bc], a
inc bc
pop af;num digits
inc a
push af;num digits
push bc;dest string
ld a, e ; if ehl > 0, loop
and a
jr nz, .divLoop
ld a, h
and a
jr nz, .divLoop
ld a, l
and a
jr nz, .divLoop
pop bc ;dest string
xor a
ld [bc], a;terminate string
pop af;num digits
cp 1
pop hl ;dest string start
ret z ;no need to swap if only one digit
ld d, a;num digits
srl d;num digits / 2
dec bc
.swapLoop
ld a, [hl]
ld e, a
ld a, [bc]
ld [hli], a
ld a, e
ld [bc], a
dec bc
dec d
jr nz, .swapLoop
ret
ENDC ;STRINGS_ASM |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.