text stringlengths 1 1.05M |
|---|
; A029926: Convert n from degrees Fahrenheit to Centigrade (or Celsius).
; -18,-17,-17,-16,-16,-15,-14,-14,-13,-13,-12,-12,-11,-11,-10,-9,-9,-8,-8,-7,-7,-6,-6,-5,-4,-4,-3,-3,-2,-2,-1,-1,0,1,1,2,2,3,3,4,4,5,6,6,7,7,8,8,9,9,10,11,11,12,12,13,13,14,14,15,16,16,17,17,18,18
mov $1,2
mov $2,$0
mov $0,3
mul $2,5
add $1,$2
add $0,$1
mov $1,$0
mov $0,10
add $1,1
div $1,9
lpb $0
sub $0,1
sub $1,1
lpe
sub $1,8
|
; uint in_LookupKey(uchar c)
; 02.2008 aralbrec
PUBLIC in_LookupKey
EXTERN in_keytranstbl
; Given the ascii code of a character, returns the scan row and mask
; corresponding to the key that needs to be pressed to generate the
; character. Eg: Calling LookupKey with character 'A' will return
; '$fd' for key row and '$01' for the mask. You could then check to
; see if the key is pressed with the following bit of code:
;
; ld a,$fd
; in a,($fe)
; and $01
; jr z, a_is_pressed
;
; The mask returned will have bit 7 set to indicate if SHIFT also has
; to be pressed to generate the ascii code.
; enter: L = ascii character code
; exit : carry set & HL=0 if ascii code not found
; else: L = scan row, H = mask
; bit 7 of H set if SHIFT needs to be pressed
; uses : AF,BC,HL
; The 16-bit value returned is a scan code understood by
; in_KeyPressed.
.in_LookupKey
ld a,l
ld hl,in_keytranstbl
ld bc,80
cpir
jr nz, notfound
ld a,79
sub c ; A = position in table of ascii code
ld l,b
ld h,b
cp 40
jr c, noshift
sub 40
set 7,h
.noshift
.div5loop
inc b
sub 5
jp nc, div5loop
.donedivide
add a,6 ; A = bit position + 1, B = row + 1
ld l,$7f
.rowlp
rlc l
djnz rowlp
ld b,a
ld a,$80
.masklp
rlca
djnz masklp
or h
ld h,a
ret
.notfound
ld hl,0
scf
ret
|
; Additions to MAZE3D.ASM for MP4
; External Routines (called from C)
PUBLIC _TestGeometry
; Public variables (used by C Program and libmp4)
PUBLIC View3d, Side3d, P3d, X3d, W3d, VidMode
; Public variables (used by libmp3)
PUBLIC updatescreen
; =================== External Library Procedures =======================
; LIBMP4 Routines (Comment these out to use your own code)
EXTRN DrawBox:near
EXTRN DrawTrap:near
EXTRN DrawBackWall:near
EXTRN DrawSides:near
EXTRN DrawFloorCeiling:near
EXTRN DrawGrScreen:near
EXTRN UpdateGrScreen:near
; ============================= Variables ===============================
VidMode db TEXTMODE ; Can be TEXTMODE (default) or GRMODE
; Pointed Mouse Attribute:Character Lookup Table (North, East, South, West)
mousech dw MNCH, MECH, MSCH, MWCH
View3d db HALL,HALL,HALL,HALL,HALL,HALL,HALL,HALL,HALL,HALL,WALL
; The elements in _MAZE, looking down a direction
; Sample data (your program will change these)
Side3d db LSW, LRSW,LRSW,LSW, RSW, LRSW, 0 ,LRSW, 0 ,LRSW,LRSW
; The elements to the side (Bit7=1=LeftSideWall | Bit6=1=RightSideWall)
; Sample data (your program will change these)
; 3D Coordinate Arrays
; Widths of walls for each depth (Large at front, small in back)
w3d dw 20, 30, 24, 20, 16, 14, 12, 10, 8, 4, 2
; Sum of W3d (i.e., total size at each depth)
X3d dw 160,140,110, 86, 66, 50, 36, 24, 14, 6, 2
; Position Along the upper-left diagonal (screen offset)
; Example: At Level 2, Top-Left corner is at Column 20, Row 10
P3d dw 0
dw 20+320*10
dw 20+30+320*(10+15)
dw 20+30+24+320*(10+15+12)
dw 20+30+24+20+320*(10+15+12+10)
dw 20+30+24+20+16+320*(10+15+12+10+8)
dw 20+30+24+20+16+14+320*(10+15+12+10+8+7)
dw 20+30+24+20+16+14+12+320*(10+15+12+10+8+7+6)
dw 20+30+24+20+16+14+12+10+320*(10+15+12+10+8+7+6+5)
dw 20+30+24+20+16+14+12+10+8+320*(10+15+12+10+8+7+6+5+4)
dw 20+30+24+20+16+14+12+10+8+4+320*(10+15+12+10+8+7+6+5+4+2)
dw 20+30+24+20+16+14+12+10+8+4+2+320*(10+15+12+10+8+7+6+5+4+2+1)
; ================= Procedures (Your code goes here) ====================
; ============================== Free Code ==============================
_TestGeometry proc far
; Geometry Test Cases
; This routine is called when you run "mazec -t"
; Use and modify this routine to debug your code.
PUSH AX
PUSH BX ; Save Registers
PUSH CX
PUSH DX
PUSH DS
PUSH ES
MOV AX,CS ; Set DS=CS
MOV DS,AX
GMODE ; Switch to 320x200 Graphics-Mode (MACRO)
; --- Draw a Rectangular Box ---
mov dx,160-20
mov cx,40 ; 20 Pixels Wide
mov bx,40 ; 20 Pixels Tall
mov AL,RED ; Colored Red
call drawbox ; Width unchanged
; --- Draw a Left-Sided Trapezoid at left of screen ----
mov dx,0 ; Position
mov bx,80 ; 40 Pixels Tall
mov AL,GREEN ; Colored green
mov AH,0 ; Left-Sided trapezoid
call drawtrap ; Width (CX) unchanged
; --- Draw a Right-Sided Trapezoid at right of screen ---
add dx,320 - 2 ; Position (with -2 correction)
mov AH,1 ; Right-Sided
mov AL,BLUE ; Colored blue
call drawtrap ; Width (CX), Height(BX), and Color(AL) Unchanged
; --- Wait for a keypress while we look at the screen ---
call kbdin
TMODE ; Switch back to 80x25 Text-Mode (MACRO)
call showlibuse
POP ES
POP DS
POP DX
POP CX
POP BX ; Restore Registers
POP AX
ret
_TestGeometry endp
; ------------------------------------------------------------------------
UpdateScreen PROC NEAR
cmp VidMode,TEXTMODE
jne USGrMode
call UpdateTextScreen
ret
USGrMode: Call UpdateGrScreen
ret
UpdateScreen ENDP
|
; ---------------------------------------------------------------------------
; Object 1B - water surface (LZ)
; ---------------------------------------------------------------------------
WaterSurface:
moveq #0,d0
move.b obRoutine(a0),d0
move.w Surf_Index(pc,d0.w),d1
jmp Surf_Index(pc,d1.w)
; ===========================================================================
Surf_Index: dc.w Surf_Main-Surf_Index
dc.w Surf_Action-Surf_Index
surf_origX: equ $30 ; original x-axis position
surf_freeze: equ $32 ; flag to freeze animation
; ===========================================================================
Surf_Main: ; Routine 0
addq.b #2,obRoutine(a0)
move.l #Map_Surf,obMap(a0)
move.w #$C300,obGfx(a0)
move.b #4,obRender(a0)
move.b #$80,obActWid(a0)
move.w obX(a0),surf_origX(a0)
Surf_Action: ; Routine 2
move.w (v_screenposx).w,d1
andi.w #$FFE0,d1
add.w surf_origX(a0),d1
btst #0,(v_framebyte).w
beq.s @even ; branch on even frames
addi.w #$20,d1
@even:
move.w d1,obX(a0) ; match obj x-position to screen position
move.w (v_waterpos1).w,d1
move.w d1,obY(a0) ; match obj y-position to water height
tst.b surf_freeze(a0)
bne.s @stopped
btst #bitStart,(v_jpadpress1).w ; is Start button pressed?
beq.s @animate ; if not, branch
addq.b #3,obFrame(a0) ; use different frames
move.b #1,surf_freeze(a0) ; stop animation
bra.s @display
; ===========================================================================
@stopped:
tst.w (f_pause).w ; is the game paused?
bne.s @display ; if yes, branch
move.b #0,surf_freeze(a0) ; resume animation
subq.b #3,obFrame(a0) ; use normal frames
@animate:
subq.b #1,obTimeFrame(a0)
bpl.s @display
move.b #7,obTimeFrame(a0)
addq.b #1,obFrame(a0)
cmpi.b #3,obFrame(a0)
bcs.s @display
move.b #0,obFrame(a0)
@display:
bra.w DisplaySprite
|
#walkthrough/44.jpg
#SEQUENCE COUNTER
#SEQUENCES ARE ZERO-TERMINATED
#READ A SEQUENCE FROM IN
#WRITE THE SUM TO OUT.S
#WRITE THE LENGTH TO OUT.L
MOV RIGHT, RIGHT
START:
ADD UP
JEZ EXIT
MOV ACC, LEFT
MOV 1, RIGHT
SWP
ADD LEFT
SAV
MOV 0, ACC
JMP START
EXIT: SWP
MOV 0, RIGHT
MOV ACC, DOWN
MOV 0, ACC
SAV
MOV LEFT, DOWN
MOV UP, DOWN
START:
ADD UP
JEZ EXIT
SWP
ADD 1
SAV
MOV 0, ACC
JMP START
EXIT:
SWP
MOV ACC, DOWN
MOV 0, ACC
SAV
MOV UP, DOWN
MOV UP, DOWN
|
org 32768
meaning_of_life = 42
start:
nop
ld hl,hex_string
.loop
ld de,meaning_of_life
ret
dz "Captain Black"
db "(c)2019 Captain Black",0
hex_string:
hex "0123456789ABCDEF00"
|
; int fgetc_unlocked_fastcall(FILE *stream)
SECTION code_clib
SECTION code_stdio
PUBLIC _fgetc_unlocked_fastcall
EXTERN asm_fgetc_unlocked
_fgetc_unlocked_fastcall:
push hl
ex (sp),ix
call asm_fgetc_unlocked
pop ix
ret
|
gossip_hints:
addiu sp, sp, -0x18
sw ra, 0x0014(sp)
li v1, SAVE_CONTEXT
; Get Message ID
lh t7, 0x001C(s0)
andi t8, t7, 0x00FF
li at, 0xFF
bne t8, at, @@not_grotto
addiu v0, t8, 0x0400
lbu t8, 0x1397(v1) ; Grotto ID
andi t8, t8, 0x1F
addiu v0, t8, 0x0430
@@not_grotto:
; If Special flag is set, always display message
andi at, t7, 0x8000
bnez at, @@return
nop
; Switch case
lw t0, GOSSIP_HINT_CONDITION
beq t0, r0, @@default
li at, 1
beq t0, at, @@stone_of_agony
nop
@@always_hint:
; Always show message
b @@return
nop
@@stone_of_agony:
; Show message only if stone of agony is obtained
lb at, 0xA5(v1)
andi at, at, 0x0020 ; Stone of Agony
beqz at, @@no_hint
nop
b @@return
nop
@@default:
; Show message only if worn mask is the mask of truth
jal 0x79B44
nop
li at, 0x0008
beq v0, at, @@return
nop
@@no_hint:
; Change message to no response message id
li v0, 0x2053
@@return:
; Set the message id to play and return
sh v0, 0x010E(s0)
lw ra, 0x0014(sp)
jr ra
addiu sp, sp, 0x18 |
.code
; void AVX2_Packed_Convert_Short_Int_(YmmVal * values, YmmVal result[2])
AVX2_Packed_Convert_Short_Int_ proc
; Convert, sign extending, a int16_t into a int32_t.
; The maximum register size for source is 128 bits (xmm).
; As we're using 256 bits for source, we need two conversions.
;
; values = 16 uint16_t
; ymm0 = 8 uint32_t
; ymm1 = 8 uint32_t
vpmovsxwd ymm0, xmmword ptr [rcx]
vpmovsxwd ymm1, xmmword ptr [rcx+type xmmword]
vmovdqa ymmword ptr [rdx], ymm0
vmovdqa ymmword ptr [rdx+type ymmword], ymm1
vzeroupper
ret
AVX2_Packed_Convert_Short_Int_ endp
end |
SECTION code_clib
SECTION code_l
PUBLIC l_small_atoul
l_small_atoul:
; ascii buffer to unsigned long conversion
; whitespace is not skipped
; char consumption stops on overflow
;
; enter : de = char *
;
; exit : bc = & next char to interpret in buffer
; dehl = unsigned result (0 on invalid input)
; carry set on unsigned overflow
;
; uses : af, bc, de, hl
ld c,e
ld b,d
ld de,0
ld l,e
ld h,d
dec bc
push de
push hl
loop:
pop af
pop af
inc bc
ld a,(bc)
sub '0'
ccf
ret nc
cp 10
ret nc
push de
push hl
add hl,hl
rl e
rl d
jr c, overflow_0
push de
push hl
add hl,hl
rl e
rl d
jr c, overflow_0
add hl,hl
rl e
rl d
jr c, overflow_0
ex de,hl
ex (sp),hl
add hl,de
pop de
ex (sp),hl
adc hl,de
ex de,hl
pop hl
jr c, overflow_1
add a,l
ld l,a
jr nc, loop
inc h
jr nz, loop
inc e
jr nz, loop
inc d
jr nz, loop
overflow_1:
pop hl
pop de
scf
ret
overflow_0:
pop af
pop af
jr overflow_1
|
_rm: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "stat.h"
#include "user.h"
int
main(int argc, char *argv[])
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 e4 f0 and $0xfffffff0,%esp
6: 83 ec 20 sub $0x20,%esp
int i;
if(argc < 2){
9: 83 7d 08 01 cmpl $0x1,0x8(%ebp)
d: 7f 19 jg 28 <main+0x28>
printf(2, "Usage: rm files...\n");
f: c7 44 24 04 b9 0a 00 movl $0xab9,0x4(%esp)
16: 00
17: c7 04 24 02 00 00 00 movl $0x2,(%esp)
1e: e8 5e 04 00 00 call 481 <printf>
exit();
23: e8 c0 02 00 00 call 2e8 <exit>
}
for(i = 1; i < argc; i++){
28: c7 44 24 1c 01 00 00 movl $0x1,0x1c(%esp)
2f: 00
30: eb 43 jmp 75 <main+0x75>
if(unlink(argv[i]) < 0){
32: 8b 44 24 1c mov 0x1c(%esp),%eax
36: c1 e0 02 shl $0x2,%eax
39: 03 45 0c add 0xc(%ebp),%eax
3c: 8b 00 mov (%eax),%eax
3e: 89 04 24 mov %eax,(%esp)
41: e8 f2 02 00 00 call 338 <unlink>
46: 85 c0 test %eax,%eax
48: 79 26 jns 70 <main+0x70>
printf(2, "rm: %s failed to delete\n", argv[i]);
4a: 8b 44 24 1c mov 0x1c(%esp),%eax
4e: c1 e0 02 shl $0x2,%eax
51: 03 45 0c add 0xc(%ebp),%eax
54: 8b 00 mov (%eax),%eax
56: 89 44 24 08 mov %eax,0x8(%esp)
5a: c7 44 24 04 cd 0a 00 movl $0xacd,0x4(%esp)
61: 00
62: c7 04 24 02 00 00 00 movl $0x2,(%esp)
69: e8 13 04 00 00 call 481 <printf>
break;
6e: eb 0e jmp 7e <main+0x7e>
if(argc < 2){
printf(2, "Usage: rm files...\n");
exit();
}
for(i = 1; i < argc; i++){
70: 83 44 24 1c 01 addl $0x1,0x1c(%esp)
75: 8b 44 24 1c mov 0x1c(%esp),%eax
79: 3b 45 08 cmp 0x8(%ebp),%eax
7c: 7c b4 jl 32 <main+0x32>
printf(2, "rm: %s failed to delete\n", argv[i]);
break;
}
}
exit();
7e: e8 65 02 00 00 call 2e8 <exit>
83: 90 nop
00000084 <stosb>:
"cc");
}
static inline void
stosb(void *addr, int data, int cnt)
{
84: 55 push %ebp
85: 89 e5 mov %esp,%ebp
87: 57 push %edi
88: 53 push %ebx
asm volatile("cld; rep stosb" :
89: 8b 4d 08 mov 0x8(%ebp),%ecx
8c: 8b 55 10 mov 0x10(%ebp),%edx
8f: 8b 45 0c mov 0xc(%ebp),%eax
92: 89 cb mov %ecx,%ebx
94: 89 df mov %ebx,%edi
96: 89 d1 mov %edx,%ecx
98: fc cld
99: f3 aa rep stos %al,%es:(%edi)
9b: 89 ca mov %ecx,%edx
9d: 89 fb mov %edi,%ebx
9f: 89 5d 08 mov %ebx,0x8(%ebp)
a2: 89 55 10 mov %edx,0x10(%ebp)
"=D" (addr), "=c" (cnt) :
"0" (addr), "1" (cnt), "a" (data) :
"memory", "cc");
}
a5: 5b pop %ebx
a6: 5f pop %edi
a7: 5d pop %ebp
a8: c3 ret
000000a9 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
a9: 55 push %ebp
aa: 89 e5 mov %esp,%ebp
ac: 83 ec 10 sub $0x10,%esp
char *os;
os = s;
af: 8b 45 08 mov 0x8(%ebp),%eax
b2: 89 45 fc mov %eax,-0x4(%ebp)
while((*s++ = *t++) != 0)
b5: 8b 45 0c mov 0xc(%ebp),%eax
b8: 0f b6 10 movzbl (%eax),%edx
bb: 8b 45 08 mov 0x8(%ebp),%eax
be: 88 10 mov %dl,(%eax)
c0: 8b 45 08 mov 0x8(%ebp),%eax
c3: 0f b6 00 movzbl (%eax),%eax
c6: 84 c0 test %al,%al
c8: 0f 95 c0 setne %al
cb: 83 45 08 01 addl $0x1,0x8(%ebp)
cf: 83 45 0c 01 addl $0x1,0xc(%ebp)
d3: 84 c0 test %al,%al
d5: 75 de jne b5 <strcpy+0xc>
;
return os;
d7: 8b 45 fc mov -0x4(%ebp),%eax
}
da: c9 leave
db: c3 ret
000000dc <strcmp>:
int
strcmp(const char *p, const char *q)
{
dc: 55 push %ebp
dd: 89 e5 mov %esp,%ebp
while(*p && *p == *q)
df: eb 08 jmp e9 <strcmp+0xd>
p++, q++;
e1: 83 45 08 01 addl $0x1,0x8(%ebp)
e5: 83 45 0c 01 addl $0x1,0xc(%ebp)
}
int
strcmp(const char *p, const char *q)
{
while(*p && *p == *q)
e9: 8b 45 08 mov 0x8(%ebp),%eax
ec: 0f b6 00 movzbl (%eax),%eax
ef: 84 c0 test %al,%al
f1: 74 10 je 103 <strcmp+0x27>
f3: 8b 45 08 mov 0x8(%ebp),%eax
f6: 0f b6 10 movzbl (%eax),%edx
f9: 8b 45 0c mov 0xc(%ebp),%eax
fc: 0f b6 00 movzbl (%eax),%eax
ff: 38 c2 cmp %al,%dl
101: 74 de je e1 <strcmp+0x5>
p++, q++;
return (uchar)*p - (uchar)*q;
103: 8b 45 08 mov 0x8(%ebp),%eax
106: 0f b6 00 movzbl (%eax),%eax
109: 0f b6 d0 movzbl %al,%edx
10c: 8b 45 0c mov 0xc(%ebp),%eax
10f: 0f b6 00 movzbl (%eax),%eax
112: 0f b6 c0 movzbl %al,%eax
115: 89 d1 mov %edx,%ecx
117: 29 c1 sub %eax,%ecx
119: 89 c8 mov %ecx,%eax
}
11b: 5d pop %ebp
11c: c3 ret
0000011d <strlen>:
uint
strlen(char *s)
{
11d: 55 push %ebp
11e: 89 e5 mov %esp,%ebp
120: 83 ec 10 sub $0x10,%esp
int n;
for(n = 0; s[n]; n++)
123: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
12a: eb 04 jmp 130 <strlen+0x13>
12c: 83 45 fc 01 addl $0x1,-0x4(%ebp)
130: 8b 45 fc mov -0x4(%ebp),%eax
133: 03 45 08 add 0x8(%ebp),%eax
136: 0f b6 00 movzbl (%eax),%eax
139: 84 c0 test %al,%al
13b: 75 ef jne 12c <strlen+0xf>
;
return n;
13d: 8b 45 fc mov -0x4(%ebp),%eax
}
140: c9 leave
141: c3 ret
00000142 <memset>:
void*
memset(void *dst, int c, uint n)
{
142: 55 push %ebp
143: 89 e5 mov %esp,%ebp
145: 83 ec 0c sub $0xc,%esp
stosb(dst, c, n);
148: 8b 45 10 mov 0x10(%ebp),%eax
14b: 89 44 24 08 mov %eax,0x8(%esp)
14f: 8b 45 0c mov 0xc(%ebp),%eax
152: 89 44 24 04 mov %eax,0x4(%esp)
156: 8b 45 08 mov 0x8(%ebp),%eax
159: 89 04 24 mov %eax,(%esp)
15c: e8 23 ff ff ff call 84 <stosb>
return dst;
161: 8b 45 08 mov 0x8(%ebp),%eax
}
164: c9 leave
165: c3 ret
00000166 <strchr>:
char*
strchr(const char *s, char c)
{
166: 55 push %ebp
167: 89 e5 mov %esp,%ebp
169: 83 ec 04 sub $0x4,%esp
16c: 8b 45 0c mov 0xc(%ebp),%eax
16f: 88 45 fc mov %al,-0x4(%ebp)
for(; *s; s++)
172: eb 14 jmp 188 <strchr+0x22>
if(*s == c)
174: 8b 45 08 mov 0x8(%ebp),%eax
177: 0f b6 00 movzbl (%eax),%eax
17a: 3a 45 fc cmp -0x4(%ebp),%al
17d: 75 05 jne 184 <strchr+0x1e>
return (char*)s;
17f: 8b 45 08 mov 0x8(%ebp),%eax
182: eb 13 jmp 197 <strchr+0x31>
}
char*
strchr(const char *s, char c)
{
for(; *s; s++)
184: 83 45 08 01 addl $0x1,0x8(%ebp)
188: 8b 45 08 mov 0x8(%ebp),%eax
18b: 0f b6 00 movzbl (%eax),%eax
18e: 84 c0 test %al,%al
190: 75 e2 jne 174 <strchr+0xe>
if(*s == c)
return (char*)s;
return 0;
192: b8 00 00 00 00 mov $0x0,%eax
}
197: c9 leave
198: c3 ret
00000199 <gets>:
char*
gets(char *buf, int max)
{
199: 55 push %ebp
19a: 89 e5 mov %esp,%ebp
19c: 83 ec 28 sub $0x28,%esp
int i, cc;
char c;
for(i=0; i+1 < max; ){
19f: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
1a6: eb 44 jmp 1ec <gets+0x53>
cc = read(0, &c, 1);
1a8: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
1af: 00
1b0: 8d 45 ef lea -0x11(%ebp),%eax
1b3: 89 44 24 04 mov %eax,0x4(%esp)
1b7: c7 04 24 00 00 00 00 movl $0x0,(%esp)
1be: e8 3d 01 00 00 call 300 <read>
1c3: 89 45 f4 mov %eax,-0xc(%ebp)
if(cc < 1)
1c6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
1ca: 7e 2d jle 1f9 <gets+0x60>
break;
buf[i++] = c;
1cc: 8b 45 f0 mov -0x10(%ebp),%eax
1cf: 03 45 08 add 0x8(%ebp),%eax
1d2: 0f b6 55 ef movzbl -0x11(%ebp),%edx
1d6: 88 10 mov %dl,(%eax)
1d8: 83 45 f0 01 addl $0x1,-0x10(%ebp)
if(c == '\n' || c == '\r')
1dc: 0f b6 45 ef movzbl -0x11(%ebp),%eax
1e0: 3c 0a cmp $0xa,%al
1e2: 74 16 je 1fa <gets+0x61>
1e4: 0f b6 45 ef movzbl -0x11(%ebp),%eax
1e8: 3c 0d cmp $0xd,%al
1ea: 74 0e je 1fa <gets+0x61>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
1ec: 8b 45 f0 mov -0x10(%ebp),%eax
1ef: 83 c0 01 add $0x1,%eax
1f2: 3b 45 0c cmp 0xc(%ebp),%eax
1f5: 7c b1 jl 1a8 <gets+0xf>
1f7: eb 01 jmp 1fa <gets+0x61>
cc = read(0, &c, 1);
if(cc < 1)
break;
1f9: 90 nop
buf[i++] = c;
if(c == '\n' || c == '\r')
break;
}
buf[i] = '\0';
1fa: 8b 45 f0 mov -0x10(%ebp),%eax
1fd: 03 45 08 add 0x8(%ebp),%eax
200: c6 00 00 movb $0x0,(%eax)
return buf;
203: 8b 45 08 mov 0x8(%ebp),%eax
}
206: c9 leave
207: c3 ret
00000208 <stat>:
int
stat(char *n, struct stat *st)
{
208: 55 push %ebp
209: 89 e5 mov %esp,%ebp
20b: 83 ec 28 sub $0x28,%esp
int fd;
int r;
fd = open(n, O_RDONLY);
20e: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
215: 00
216: 8b 45 08 mov 0x8(%ebp),%eax
219: 89 04 24 mov %eax,(%esp)
21c: e8 07 01 00 00 call 328 <open>
221: 89 45 f0 mov %eax,-0x10(%ebp)
if(fd < 0)
224: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
228: 79 07 jns 231 <stat+0x29>
return -1;
22a: b8 ff ff ff ff mov $0xffffffff,%eax
22f: eb 23 jmp 254 <stat+0x4c>
r = fstat(fd, st);
231: 8b 45 0c mov 0xc(%ebp),%eax
234: 89 44 24 04 mov %eax,0x4(%esp)
238: 8b 45 f0 mov -0x10(%ebp),%eax
23b: 89 04 24 mov %eax,(%esp)
23e: e8 fd 00 00 00 call 340 <fstat>
243: 89 45 f4 mov %eax,-0xc(%ebp)
close(fd);
246: 8b 45 f0 mov -0x10(%ebp),%eax
249: 89 04 24 mov %eax,(%esp)
24c: e8 bf 00 00 00 call 310 <close>
return r;
251: 8b 45 f4 mov -0xc(%ebp),%eax
}
254: c9 leave
255: c3 ret
00000256 <atoi>:
int
atoi(const char *s)
{
256: 55 push %ebp
257: 89 e5 mov %esp,%ebp
259: 83 ec 10 sub $0x10,%esp
int n;
n = 0;
25c: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp)
while('0' <= *s && *s <= '9')
263: eb 24 jmp 289 <atoi+0x33>
n = n*10 + *s++ - '0';
265: 8b 55 fc mov -0x4(%ebp),%edx
268: 89 d0 mov %edx,%eax
26a: c1 e0 02 shl $0x2,%eax
26d: 01 d0 add %edx,%eax
26f: 01 c0 add %eax,%eax
271: 89 c2 mov %eax,%edx
273: 8b 45 08 mov 0x8(%ebp),%eax
276: 0f b6 00 movzbl (%eax),%eax
279: 0f be c0 movsbl %al,%eax
27c: 8d 04 02 lea (%edx,%eax,1),%eax
27f: 83 e8 30 sub $0x30,%eax
282: 89 45 fc mov %eax,-0x4(%ebp)
285: 83 45 08 01 addl $0x1,0x8(%ebp)
atoi(const char *s)
{
int n;
n = 0;
while('0' <= *s && *s <= '9')
289: 8b 45 08 mov 0x8(%ebp),%eax
28c: 0f b6 00 movzbl (%eax),%eax
28f: 3c 2f cmp $0x2f,%al
291: 7e 0a jle 29d <atoi+0x47>
293: 8b 45 08 mov 0x8(%ebp),%eax
296: 0f b6 00 movzbl (%eax),%eax
299: 3c 39 cmp $0x39,%al
29b: 7e c8 jle 265 <atoi+0xf>
n = n*10 + *s++ - '0';
return n;
29d: 8b 45 fc mov -0x4(%ebp),%eax
}
2a0: c9 leave
2a1: c3 ret
000002a2 <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
2a2: 55 push %ebp
2a3: 89 e5 mov %esp,%ebp
2a5: 83 ec 10 sub $0x10,%esp
char *dst, *src;
dst = vdst;
2a8: 8b 45 08 mov 0x8(%ebp),%eax
2ab: 89 45 f8 mov %eax,-0x8(%ebp)
src = vsrc;
2ae: 8b 45 0c mov 0xc(%ebp),%eax
2b1: 89 45 fc mov %eax,-0x4(%ebp)
while(n-- > 0)
2b4: eb 13 jmp 2c9 <memmove+0x27>
*dst++ = *src++;
2b6: 8b 45 fc mov -0x4(%ebp),%eax
2b9: 0f b6 10 movzbl (%eax),%edx
2bc: 8b 45 f8 mov -0x8(%ebp),%eax
2bf: 88 10 mov %dl,(%eax)
2c1: 83 45 f8 01 addl $0x1,-0x8(%ebp)
2c5: 83 45 fc 01 addl $0x1,-0x4(%ebp)
{
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
2c9: 83 7d 10 00 cmpl $0x0,0x10(%ebp)
2cd: 0f 9f c0 setg %al
2d0: 83 6d 10 01 subl $0x1,0x10(%ebp)
2d4: 84 c0 test %al,%al
2d6: 75 de jne 2b6 <memmove+0x14>
*dst++ = *src++;
return vdst;
2d8: 8b 45 08 mov 0x8(%ebp),%eax
}
2db: c9 leave
2dc: c3 ret
2dd: 90 nop
2de: 90 nop
2df: 90 nop
000002e0 <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
2e0: b8 01 00 00 00 mov $0x1,%eax
2e5: cd 40 int $0x40
2e7: c3 ret
000002e8 <exit>:
SYSCALL(exit)
2e8: b8 02 00 00 00 mov $0x2,%eax
2ed: cd 40 int $0x40
2ef: c3 ret
000002f0 <wait>:
SYSCALL(wait)
2f0: b8 03 00 00 00 mov $0x3,%eax
2f5: cd 40 int $0x40
2f7: c3 ret
000002f8 <pipe>:
SYSCALL(pipe)
2f8: b8 04 00 00 00 mov $0x4,%eax
2fd: cd 40 int $0x40
2ff: c3 ret
00000300 <read>:
SYSCALL(read)
300: b8 05 00 00 00 mov $0x5,%eax
305: cd 40 int $0x40
307: c3 ret
00000308 <write>:
SYSCALL(write)
308: b8 10 00 00 00 mov $0x10,%eax
30d: cd 40 int $0x40
30f: c3 ret
00000310 <close>:
SYSCALL(close)
310: b8 15 00 00 00 mov $0x15,%eax
315: cd 40 int $0x40
317: c3 ret
00000318 <kill>:
SYSCALL(kill)
318: b8 06 00 00 00 mov $0x6,%eax
31d: cd 40 int $0x40
31f: c3 ret
00000320 <exec>:
SYSCALL(exec)
320: b8 07 00 00 00 mov $0x7,%eax
325: cd 40 int $0x40
327: c3 ret
00000328 <open>:
SYSCALL(open)
328: b8 0f 00 00 00 mov $0xf,%eax
32d: cd 40 int $0x40
32f: c3 ret
00000330 <mknod>:
SYSCALL(mknod)
330: b8 11 00 00 00 mov $0x11,%eax
335: cd 40 int $0x40
337: c3 ret
00000338 <unlink>:
SYSCALL(unlink)
338: b8 12 00 00 00 mov $0x12,%eax
33d: cd 40 int $0x40
33f: c3 ret
00000340 <fstat>:
SYSCALL(fstat)
340: b8 08 00 00 00 mov $0x8,%eax
345: cd 40 int $0x40
347: c3 ret
00000348 <link>:
SYSCALL(link)
348: b8 13 00 00 00 mov $0x13,%eax
34d: cd 40 int $0x40
34f: c3 ret
00000350 <mkdir>:
SYSCALL(mkdir)
350: b8 14 00 00 00 mov $0x14,%eax
355: cd 40 int $0x40
357: c3 ret
00000358 <chdir>:
SYSCALL(chdir)
358: b8 09 00 00 00 mov $0x9,%eax
35d: cd 40 int $0x40
35f: c3 ret
00000360 <dup>:
SYSCALL(dup)
360: b8 0a 00 00 00 mov $0xa,%eax
365: cd 40 int $0x40
367: c3 ret
00000368 <getpid>:
SYSCALL(getpid)
368: b8 0b 00 00 00 mov $0xb,%eax
36d: cd 40 int $0x40
36f: c3 ret
00000370 <sbrk>:
SYSCALL(sbrk)
370: b8 0c 00 00 00 mov $0xc,%eax
375: cd 40 int $0x40
377: c3 ret
00000378 <sleep>:
SYSCALL(sleep)
378: b8 0d 00 00 00 mov $0xd,%eax
37d: cd 40 int $0x40
37f: c3 ret
00000380 <uptime>:
SYSCALL(uptime)
380: b8 0e 00 00 00 mov $0xe,%eax
385: cd 40 int $0x40
387: c3 ret
00000388 <clone>:
SYSCALL(clone)
388: b8 16 00 00 00 mov $0x16,%eax
38d: cd 40 int $0x40
38f: c3 ret
00000390 <texit>:
SYSCALL(texit)
390: b8 17 00 00 00 mov $0x17,%eax
395: cd 40 int $0x40
397: c3 ret
00000398 <tsleep>:
SYSCALL(tsleep)
398: b8 18 00 00 00 mov $0x18,%eax
39d: cd 40 int $0x40
39f: c3 ret
000003a0 <twakeup>:
SYSCALL(twakeup)
3a0: b8 19 00 00 00 mov $0x19,%eax
3a5: cd 40 int $0x40
3a7: c3 ret
000003a8 <putc>:
#include "stat.h"
#include "user.h"
static void
putc(int fd, char c)
{
3a8: 55 push %ebp
3a9: 89 e5 mov %esp,%ebp
3ab: 83 ec 28 sub $0x28,%esp
3ae: 8b 45 0c mov 0xc(%ebp),%eax
3b1: 88 45 f4 mov %al,-0xc(%ebp)
write(fd, &c, 1);
3b4: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp)
3bb: 00
3bc: 8d 45 f4 lea -0xc(%ebp),%eax
3bf: 89 44 24 04 mov %eax,0x4(%esp)
3c3: 8b 45 08 mov 0x8(%ebp),%eax
3c6: 89 04 24 mov %eax,(%esp)
3c9: e8 3a ff ff ff call 308 <write>
}
3ce: c9 leave
3cf: c3 ret
000003d0 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
3d0: 55 push %ebp
3d1: 89 e5 mov %esp,%ebp
3d3: 53 push %ebx
3d4: 83 ec 44 sub $0x44,%esp
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
3d7: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
if(sgn && xx < 0){
3de: 83 7d 14 00 cmpl $0x0,0x14(%ebp)
3e2: 74 17 je 3fb <printint+0x2b>
3e4: 83 7d 0c 00 cmpl $0x0,0xc(%ebp)
3e8: 79 11 jns 3fb <printint+0x2b>
neg = 1;
3ea: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp)
x = -xx;
3f1: 8b 45 0c mov 0xc(%ebp),%eax
3f4: f7 d8 neg %eax
3f6: 89 45 f4 mov %eax,-0xc(%ebp)
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
3f9: eb 06 jmp 401 <printint+0x31>
neg = 1;
x = -xx;
} else {
x = xx;
3fb: 8b 45 0c mov 0xc(%ebp),%eax
3fe: 89 45 f4 mov %eax,-0xc(%ebp)
}
i = 0;
401: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
do{
buf[i++] = digits[x % base];
408: 8b 4d ec mov -0x14(%ebp),%ecx
40b: 8b 5d 10 mov 0x10(%ebp),%ebx
40e: 8b 45 f4 mov -0xc(%ebp),%eax
411: ba 00 00 00 00 mov $0x0,%edx
416: f7 f3 div %ebx
418: 89 d0 mov %edx,%eax
41a: 0f b6 80 1c 0b 00 00 movzbl 0xb1c(%eax),%eax
421: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1)
425: 83 45 ec 01 addl $0x1,-0x14(%ebp)
}while((x /= base) != 0);
429: 8b 45 10 mov 0x10(%ebp),%eax
42c: 89 45 d4 mov %eax,-0x2c(%ebp)
42f: 8b 45 f4 mov -0xc(%ebp),%eax
432: ba 00 00 00 00 mov $0x0,%edx
437: f7 75 d4 divl -0x2c(%ebp)
43a: 89 45 f4 mov %eax,-0xc(%ebp)
43d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
441: 75 c5 jne 408 <printint+0x38>
if(neg)
443: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
447: 74 28 je 471 <printint+0xa1>
buf[i++] = '-';
449: 8b 45 ec mov -0x14(%ebp),%eax
44c: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1)
451: 83 45 ec 01 addl $0x1,-0x14(%ebp)
while(--i >= 0)
455: eb 1a jmp 471 <printint+0xa1>
putc(fd, buf[i]);
457: 8b 45 ec mov -0x14(%ebp),%eax
45a: 0f b6 44 05 dc movzbl -0x24(%ebp,%eax,1),%eax
45f: 0f be c0 movsbl %al,%eax
462: 89 44 24 04 mov %eax,0x4(%esp)
466: 8b 45 08 mov 0x8(%ebp),%eax
469: 89 04 24 mov %eax,(%esp)
46c: e8 37 ff ff ff call 3a8 <putc>
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
471: 83 6d ec 01 subl $0x1,-0x14(%ebp)
475: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
479: 79 dc jns 457 <printint+0x87>
putc(fd, buf[i]);
}
47b: 83 c4 44 add $0x44,%esp
47e: 5b pop %ebx
47f: 5d pop %ebp
480: c3 ret
00000481 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
481: 55 push %ebp
482: 89 e5 mov %esp,%ebp
484: 83 ec 38 sub $0x38,%esp
char *s;
int c, i, state;
uint *ap;
state = 0;
487: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
ap = (uint*)(void*)&fmt + 1;
48e: 8d 45 0c lea 0xc(%ebp),%eax
491: 83 c0 04 add $0x4,%eax
494: 89 45 f4 mov %eax,-0xc(%ebp)
for(i = 0; fmt[i]; i++){
497: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
49e: e9 7e 01 00 00 jmp 621 <printf+0x1a0>
c = fmt[i] & 0xff;
4a3: 8b 55 0c mov 0xc(%ebp),%edx
4a6: 8b 45 ec mov -0x14(%ebp),%eax
4a9: 8d 04 02 lea (%edx,%eax,1),%eax
4ac: 0f b6 00 movzbl (%eax),%eax
4af: 0f be c0 movsbl %al,%eax
4b2: 25 ff 00 00 00 and $0xff,%eax
4b7: 89 45 e8 mov %eax,-0x18(%ebp)
if(state == 0){
4ba: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
4be: 75 2c jne 4ec <printf+0x6b>
if(c == '%'){
4c0: 83 7d e8 25 cmpl $0x25,-0x18(%ebp)
4c4: 75 0c jne 4d2 <printf+0x51>
state = '%';
4c6: c7 45 f0 25 00 00 00 movl $0x25,-0x10(%ebp)
4cd: e9 4b 01 00 00 jmp 61d <printf+0x19c>
} else {
putc(fd, c);
4d2: 8b 45 e8 mov -0x18(%ebp),%eax
4d5: 0f be c0 movsbl %al,%eax
4d8: 89 44 24 04 mov %eax,0x4(%esp)
4dc: 8b 45 08 mov 0x8(%ebp),%eax
4df: 89 04 24 mov %eax,(%esp)
4e2: e8 c1 fe ff ff call 3a8 <putc>
4e7: e9 31 01 00 00 jmp 61d <printf+0x19c>
}
} else if(state == '%'){
4ec: 83 7d f0 25 cmpl $0x25,-0x10(%ebp)
4f0: 0f 85 27 01 00 00 jne 61d <printf+0x19c>
if(c == 'd'){
4f6: 83 7d e8 64 cmpl $0x64,-0x18(%ebp)
4fa: 75 2d jne 529 <printf+0xa8>
printint(fd, *ap, 10, 1);
4fc: 8b 45 f4 mov -0xc(%ebp),%eax
4ff: 8b 00 mov (%eax),%eax
501: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp)
508: 00
509: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp)
510: 00
511: 89 44 24 04 mov %eax,0x4(%esp)
515: 8b 45 08 mov 0x8(%ebp),%eax
518: 89 04 24 mov %eax,(%esp)
51b: e8 b0 fe ff ff call 3d0 <printint>
ap++;
520: 83 45 f4 04 addl $0x4,-0xc(%ebp)
524: e9 ed 00 00 00 jmp 616 <printf+0x195>
} else if(c == 'x' || c == 'p'){
529: 83 7d e8 78 cmpl $0x78,-0x18(%ebp)
52d: 74 06 je 535 <printf+0xb4>
52f: 83 7d e8 70 cmpl $0x70,-0x18(%ebp)
533: 75 2d jne 562 <printf+0xe1>
printint(fd, *ap, 16, 0);
535: 8b 45 f4 mov -0xc(%ebp),%eax
538: 8b 00 mov (%eax),%eax
53a: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
541: 00
542: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp)
549: 00
54a: 89 44 24 04 mov %eax,0x4(%esp)
54e: 8b 45 08 mov 0x8(%ebp),%eax
551: 89 04 24 mov %eax,(%esp)
554: e8 77 fe ff ff call 3d0 <printint>
ap++;
559: 83 45 f4 04 addl $0x4,-0xc(%ebp)
}
} else if(state == '%'){
if(c == 'd'){
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
55d: e9 b4 00 00 00 jmp 616 <printf+0x195>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
562: 83 7d e8 73 cmpl $0x73,-0x18(%ebp)
566: 75 46 jne 5ae <printf+0x12d>
s = (char*)*ap;
568: 8b 45 f4 mov -0xc(%ebp),%eax
56b: 8b 00 mov (%eax),%eax
56d: 89 45 e4 mov %eax,-0x1c(%ebp)
ap++;
570: 83 45 f4 04 addl $0x4,-0xc(%ebp)
if(s == 0)
574: 83 7d e4 00 cmpl $0x0,-0x1c(%ebp)
578: 75 27 jne 5a1 <printf+0x120>
s = "(null)";
57a: c7 45 e4 e6 0a 00 00 movl $0xae6,-0x1c(%ebp)
while(*s != 0){
581: eb 1f jmp 5a2 <printf+0x121>
putc(fd, *s);
583: 8b 45 e4 mov -0x1c(%ebp),%eax
586: 0f b6 00 movzbl (%eax),%eax
589: 0f be c0 movsbl %al,%eax
58c: 89 44 24 04 mov %eax,0x4(%esp)
590: 8b 45 08 mov 0x8(%ebp),%eax
593: 89 04 24 mov %eax,(%esp)
596: e8 0d fe ff ff call 3a8 <putc>
s++;
59b: 83 45 e4 01 addl $0x1,-0x1c(%ebp)
59f: eb 01 jmp 5a2 <printf+0x121>
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
5a1: 90 nop
5a2: 8b 45 e4 mov -0x1c(%ebp),%eax
5a5: 0f b6 00 movzbl (%eax),%eax
5a8: 84 c0 test %al,%al
5aa: 75 d7 jne 583 <printf+0x102>
5ac: eb 68 jmp 616 <printf+0x195>
putc(fd, *s);
s++;
}
} else if(c == 'c'){
5ae: 83 7d e8 63 cmpl $0x63,-0x18(%ebp)
5b2: 75 1d jne 5d1 <printf+0x150>
putc(fd, *ap);
5b4: 8b 45 f4 mov -0xc(%ebp),%eax
5b7: 8b 00 mov (%eax),%eax
5b9: 0f be c0 movsbl %al,%eax
5bc: 89 44 24 04 mov %eax,0x4(%esp)
5c0: 8b 45 08 mov 0x8(%ebp),%eax
5c3: 89 04 24 mov %eax,(%esp)
5c6: e8 dd fd ff ff call 3a8 <putc>
ap++;
5cb: 83 45 f4 04 addl $0x4,-0xc(%ebp)
5cf: eb 45 jmp 616 <printf+0x195>
} else if(c == '%'){
5d1: 83 7d e8 25 cmpl $0x25,-0x18(%ebp)
5d5: 75 17 jne 5ee <printf+0x16d>
putc(fd, c);
5d7: 8b 45 e8 mov -0x18(%ebp),%eax
5da: 0f be c0 movsbl %al,%eax
5dd: 89 44 24 04 mov %eax,0x4(%esp)
5e1: 8b 45 08 mov 0x8(%ebp),%eax
5e4: 89 04 24 mov %eax,(%esp)
5e7: e8 bc fd ff ff call 3a8 <putc>
5ec: eb 28 jmp 616 <printf+0x195>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
5ee: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp)
5f5: 00
5f6: 8b 45 08 mov 0x8(%ebp),%eax
5f9: 89 04 24 mov %eax,(%esp)
5fc: e8 a7 fd ff ff call 3a8 <putc>
putc(fd, c);
601: 8b 45 e8 mov -0x18(%ebp),%eax
604: 0f be c0 movsbl %al,%eax
607: 89 44 24 04 mov %eax,0x4(%esp)
60b: 8b 45 08 mov 0x8(%ebp),%eax
60e: 89 04 24 mov %eax,(%esp)
611: e8 92 fd ff ff call 3a8 <putc>
}
state = 0;
616: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
61d: 83 45 ec 01 addl $0x1,-0x14(%ebp)
621: 8b 55 0c mov 0xc(%ebp),%edx
624: 8b 45 ec mov -0x14(%ebp),%eax
627: 8d 04 02 lea (%edx,%eax,1),%eax
62a: 0f b6 00 movzbl (%eax),%eax
62d: 84 c0 test %al,%al
62f: 0f 85 6e fe ff ff jne 4a3 <printf+0x22>
putc(fd, c);
}
state = 0;
}
}
}
635: c9 leave
636: c3 ret
637: 90 nop
00000638 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
638: 55 push %ebp
639: 89 e5 mov %esp,%ebp
63b: 83 ec 10 sub $0x10,%esp
Header *bp, *p;
bp = (Header*)ap - 1;
63e: 8b 45 08 mov 0x8(%ebp),%eax
641: 83 e8 08 sub $0x8,%eax
644: 89 45 f8 mov %eax,-0x8(%ebp)
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
647: a1 3c 0b 00 00 mov 0xb3c,%eax
64c: 89 45 fc mov %eax,-0x4(%ebp)
64f: eb 24 jmp 675 <free+0x3d>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
651: 8b 45 fc mov -0x4(%ebp),%eax
654: 8b 00 mov (%eax),%eax
656: 3b 45 fc cmp -0x4(%ebp),%eax
659: 77 12 ja 66d <free+0x35>
65b: 8b 45 f8 mov -0x8(%ebp),%eax
65e: 3b 45 fc cmp -0x4(%ebp),%eax
661: 77 24 ja 687 <free+0x4f>
663: 8b 45 fc mov -0x4(%ebp),%eax
666: 8b 00 mov (%eax),%eax
668: 3b 45 f8 cmp -0x8(%ebp),%eax
66b: 77 1a ja 687 <free+0x4f>
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
66d: 8b 45 fc mov -0x4(%ebp),%eax
670: 8b 00 mov (%eax),%eax
672: 89 45 fc mov %eax,-0x4(%ebp)
675: 8b 45 f8 mov -0x8(%ebp),%eax
678: 3b 45 fc cmp -0x4(%ebp),%eax
67b: 76 d4 jbe 651 <free+0x19>
67d: 8b 45 fc mov -0x4(%ebp),%eax
680: 8b 00 mov (%eax),%eax
682: 3b 45 f8 cmp -0x8(%ebp),%eax
685: 76 ca jbe 651 <free+0x19>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
687: 8b 45 f8 mov -0x8(%ebp),%eax
68a: 8b 40 04 mov 0x4(%eax),%eax
68d: c1 e0 03 shl $0x3,%eax
690: 89 c2 mov %eax,%edx
692: 03 55 f8 add -0x8(%ebp),%edx
695: 8b 45 fc mov -0x4(%ebp),%eax
698: 8b 00 mov (%eax),%eax
69a: 39 c2 cmp %eax,%edx
69c: 75 24 jne 6c2 <free+0x8a>
bp->s.size += p->s.ptr->s.size;
69e: 8b 45 f8 mov -0x8(%ebp),%eax
6a1: 8b 50 04 mov 0x4(%eax),%edx
6a4: 8b 45 fc mov -0x4(%ebp),%eax
6a7: 8b 00 mov (%eax),%eax
6a9: 8b 40 04 mov 0x4(%eax),%eax
6ac: 01 c2 add %eax,%edx
6ae: 8b 45 f8 mov -0x8(%ebp),%eax
6b1: 89 50 04 mov %edx,0x4(%eax)
bp->s.ptr = p->s.ptr->s.ptr;
6b4: 8b 45 fc mov -0x4(%ebp),%eax
6b7: 8b 00 mov (%eax),%eax
6b9: 8b 10 mov (%eax),%edx
6bb: 8b 45 f8 mov -0x8(%ebp),%eax
6be: 89 10 mov %edx,(%eax)
6c0: eb 0a jmp 6cc <free+0x94>
} else
bp->s.ptr = p->s.ptr;
6c2: 8b 45 fc mov -0x4(%ebp),%eax
6c5: 8b 10 mov (%eax),%edx
6c7: 8b 45 f8 mov -0x8(%ebp),%eax
6ca: 89 10 mov %edx,(%eax)
if(p + p->s.size == bp){
6cc: 8b 45 fc mov -0x4(%ebp),%eax
6cf: 8b 40 04 mov 0x4(%eax),%eax
6d2: c1 e0 03 shl $0x3,%eax
6d5: 03 45 fc add -0x4(%ebp),%eax
6d8: 3b 45 f8 cmp -0x8(%ebp),%eax
6db: 75 20 jne 6fd <free+0xc5>
p->s.size += bp->s.size;
6dd: 8b 45 fc mov -0x4(%ebp),%eax
6e0: 8b 50 04 mov 0x4(%eax),%edx
6e3: 8b 45 f8 mov -0x8(%ebp),%eax
6e6: 8b 40 04 mov 0x4(%eax),%eax
6e9: 01 c2 add %eax,%edx
6eb: 8b 45 fc mov -0x4(%ebp),%eax
6ee: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
6f1: 8b 45 f8 mov -0x8(%ebp),%eax
6f4: 8b 10 mov (%eax),%edx
6f6: 8b 45 fc mov -0x4(%ebp),%eax
6f9: 89 10 mov %edx,(%eax)
6fb: eb 08 jmp 705 <free+0xcd>
} else
p->s.ptr = bp;
6fd: 8b 45 fc mov -0x4(%ebp),%eax
700: 8b 55 f8 mov -0x8(%ebp),%edx
703: 89 10 mov %edx,(%eax)
freep = p;
705: 8b 45 fc mov -0x4(%ebp),%eax
708: a3 3c 0b 00 00 mov %eax,0xb3c
}
70d: c9 leave
70e: c3 ret
0000070f <morecore>:
static Header*
morecore(uint nu)
{
70f: 55 push %ebp
710: 89 e5 mov %esp,%ebp
712: 83 ec 28 sub $0x28,%esp
char *p;
Header *hp;
if(nu < 4096)
715: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp)
71c: 77 07 ja 725 <morecore+0x16>
nu = 4096;
71e: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp)
p = sbrk(nu * sizeof(Header));
725: 8b 45 08 mov 0x8(%ebp),%eax
728: c1 e0 03 shl $0x3,%eax
72b: 89 04 24 mov %eax,(%esp)
72e: e8 3d fc ff ff call 370 <sbrk>
733: 89 45 f0 mov %eax,-0x10(%ebp)
if(p == (char*)-1)
736: 83 7d f0 ff cmpl $0xffffffff,-0x10(%ebp)
73a: 75 07 jne 743 <morecore+0x34>
return 0;
73c: b8 00 00 00 00 mov $0x0,%eax
741: eb 22 jmp 765 <morecore+0x56>
hp = (Header*)p;
743: 8b 45 f0 mov -0x10(%ebp),%eax
746: 89 45 f4 mov %eax,-0xc(%ebp)
hp->s.size = nu;
749: 8b 45 f4 mov -0xc(%ebp),%eax
74c: 8b 55 08 mov 0x8(%ebp),%edx
74f: 89 50 04 mov %edx,0x4(%eax)
free((void*)(hp + 1));
752: 8b 45 f4 mov -0xc(%ebp),%eax
755: 83 c0 08 add $0x8,%eax
758: 89 04 24 mov %eax,(%esp)
75b: e8 d8 fe ff ff call 638 <free>
return freep;
760: a1 3c 0b 00 00 mov 0xb3c,%eax
}
765: c9 leave
766: c3 ret
00000767 <malloc>:
void*
malloc(uint nbytes)
{
767: 55 push %ebp
768: 89 e5 mov %esp,%ebp
76a: 83 ec 28 sub $0x28,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
76d: 8b 45 08 mov 0x8(%ebp),%eax
770: 83 c0 07 add $0x7,%eax
773: c1 e8 03 shr $0x3,%eax
776: 83 c0 01 add $0x1,%eax
779: 89 45 f4 mov %eax,-0xc(%ebp)
if((prevp = freep) == 0){
77c: a1 3c 0b 00 00 mov 0xb3c,%eax
781: 89 45 f0 mov %eax,-0x10(%ebp)
784: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
788: 75 23 jne 7ad <malloc+0x46>
base.s.ptr = freep = prevp = &base;
78a: c7 45 f0 34 0b 00 00 movl $0xb34,-0x10(%ebp)
791: 8b 45 f0 mov -0x10(%ebp),%eax
794: a3 3c 0b 00 00 mov %eax,0xb3c
799: a1 3c 0b 00 00 mov 0xb3c,%eax
79e: a3 34 0b 00 00 mov %eax,0xb34
base.s.size = 0;
7a3: c7 05 38 0b 00 00 00 movl $0x0,0xb38
7aa: 00 00 00
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7ad: 8b 45 f0 mov -0x10(%ebp),%eax
7b0: 8b 00 mov (%eax),%eax
7b2: 89 45 ec mov %eax,-0x14(%ebp)
if(p->s.size >= nunits){
7b5: 8b 45 ec mov -0x14(%ebp),%eax
7b8: 8b 40 04 mov 0x4(%eax),%eax
7bb: 3b 45 f4 cmp -0xc(%ebp),%eax
7be: 72 4d jb 80d <malloc+0xa6>
if(p->s.size == nunits)
7c0: 8b 45 ec mov -0x14(%ebp),%eax
7c3: 8b 40 04 mov 0x4(%eax),%eax
7c6: 3b 45 f4 cmp -0xc(%ebp),%eax
7c9: 75 0c jne 7d7 <malloc+0x70>
prevp->s.ptr = p->s.ptr;
7cb: 8b 45 ec mov -0x14(%ebp),%eax
7ce: 8b 10 mov (%eax),%edx
7d0: 8b 45 f0 mov -0x10(%ebp),%eax
7d3: 89 10 mov %edx,(%eax)
7d5: eb 26 jmp 7fd <malloc+0x96>
else {
p->s.size -= nunits;
7d7: 8b 45 ec mov -0x14(%ebp),%eax
7da: 8b 40 04 mov 0x4(%eax),%eax
7dd: 89 c2 mov %eax,%edx
7df: 2b 55 f4 sub -0xc(%ebp),%edx
7e2: 8b 45 ec mov -0x14(%ebp),%eax
7e5: 89 50 04 mov %edx,0x4(%eax)
p += p->s.size;
7e8: 8b 45 ec mov -0x14(%ebp),%eax
7eb: 8b 40 04 mov 0x4(%eax),%eax
7ee: c1 e0 03 shl $0x3,%eax
7f1: 01 45 ec add %eax,-0x14(%ebp)
p->s.size = nunits;
7f4: 8b 45 ec mov -0x14(%ebp),%eax
7f7: 8b 55 f4 mov -0xc(%ebp),%edx
7fa: 89 50 04 mov %edx,0x4(%eax)
}
freep = prevp;
7fd: 8b 45 f0 mov -0x10(%ebp),%eax
800: a3 3c 0b 00 00 mov %eax,0xb3c
return (void*)(p + 1);
805: 8b 45 ec mov -0x14(%ebp),%eax
808: 83 c0 08 add $0x8,%eax
80b: eb 38 jmp 845 <malloc+0xde>
}
if(p == freep)
80d: a1 3c 0b 00 00 mov 0xb3c,%eax
812: 39 45 ec cmp %eax,-0x14(%ebp)
815: 75 1b jne 832 <malloc+0xcb>
if((p = morecore(nunits)) == 0)
817: 8b 45 f4 mov -0xc(%ebp),%eax
81a: 89 04 24 mov %eax,(%esp)
81d: e8 ed fe ff ff call 70f <morecore>
822: 89 45 ec mov %eax,-0x14(%ebp)
825: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
829: 75 07 jne 832 <malloc+0xcb>
return 0;
82b: b8 00 00 00 00 mov $0x0,%eax
830: eb 13 jmp 845 <malloc+0xde>
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
if((prevp = freep) == 0){
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
832: 8b 45 ec mov -0x14(%ebp),%eax
835: 89 45 f0 mov %eax,-0x10(%ebp)
838: 8b 45 ec mov -0x14(%ebp),%eax
83b: 8b 00 mov (%eax),%eax
83d: 89 45 ec mov %eax,-0x14(%ebp)
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
840: e9 70 ff ff ff jmp 7b5 <malloc+0x4e>
}
845: c9 leave
846: c3 ret
847: 90 nop
00000848 <xchg>:
asm volatile("sti");
}
static inline uint
xchg(volatile uint *addr, uint newval)
{
848: 55 push %ebp
849: 89 e5 mov %esp,%ebp
84b: 83 ec 10 sub $0x10,%esp
uint result;
// The + in "+m" denotes a read-modify-write operand.
asm volatile("lock; xchgl %0, %1" :
84e: 8b 55 08 mov 0x8(%ebp),%edx
851: 8b 45 0c mov 0xc(%ebp),%eax
854: 8b 4d 08 mov 0x8(%ebp),%ecx
857: f0 87 02 lock xchg %eax,(%edx)
85a: 89 45 fc mov %eax,-0x4(%ebp)
"+m" (*addr), "=a" (result) :
"1" (newval) :
"cc");
return result;
85d: 8b 45 fc mov -0x4(%ebp),%eax
}
860: c9 leave
861: c3 ret
00000862 <lock_init>:
#include "x86.h"
#include "proc.h"
unsigned long rands = 1;
void lock_init(lock_t *lock){
862: 55 push %ebp
863: 89 e5 mov %esp,%ebp
lock->locked = 0;
865: 8b 45 08 mov 0x8(%ebp),%eax
868: c7 00 00 00 00 00 movl $0x0,(%eax)
}
86e: 5d pop %ebp
86f: c3 ret
00000870 <lock_acquire>:
void lock_acquire(lock_t *lock){
870: 55 push %ebp
871: 89 e5 mov %esp,%ebp
873: 83 ec 08 sub $0x8,%esp
while(xchg(&lock->locked,1) != 0);
876: 8b 45 08 mov 0x8(%ebp),%eax
879: c7 44 24 04 01 00 00 movl $0x1,0x4(%esp)
880: 00
881: 89 04 24 mov %eax,(%esp)
884: e8 bf ff ff ff call 848 <xchg>
889: 85 c0 test %eax,%eax
88b: 75 e9 jne 876 <lock_acquire+0x6>
}
88d: c9 leave
88e: c3 ret
0000088f <lock_release>:
void lock_release(lock_t *lock){
88f: 55 push %ebp
890: 89 e5 mov %esp,%ebp
892: 83 ec 08 sub $0x8,%esp
xchg(&lock->locked,0);
895: 8b 45 08 mov 0x8(%ebp),%eax
898: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp)
89f: 00
8a0: 89 04 24 mov %eax,(%esp)
8a3: e8 a0 ff ff ff call 848 <xchg>
}
8a8: c9 leave
8a9: c3 ret
000008aa <thread_create>:
void *thread_create(void(*start_routine)(void*), void *arg){
8aa: 55 push %ebp
8ab: 89 e5 mov %esp,%ebp
8ad: 83 ec 28 sub $0x28,%esp
int tid;
void * stack = malloc(2 * 4096);
8b0: c7 04 24 00 20 00 00 movl $0x2000,(%esp)
8b7: e8 ab fe ff ff call 767 <malloc>
8bc: 89 45 f0 mov %eax,-0x10(%ebp)
void *garbage_stack = stack;
8bf: 8b 45 f0 mov -0x10(%ebp),%eax
8c2: 89 45 f4 mov %eax,-0xc(%ebp)
// printf(1,"start routine addr : %d\n",(uint)start_routine);
if((uint)stack % 4096){
8c5: 8b 45 f0 mov -0x10(%ebp),%eax
8c8: 25 ff 0f 00 00 and $0xfff,%eax
8cd: 85 c0 test %eax,%eax
8cf: 74 15 je 8e6 <thread_create+0x3c>
stack = stack + (4096 - (uint)stack % 4096);
8d1: 8b 45 f0 mov -0x10(%ebp),%eax
8d4: 89 c2 mov %eax,%edx
8d6: 81 e2 ff 0f 00 00 and $0xfff,%edx
8dc: b8 00 10 00 00 mov $0x1000,%eax
8e1: 29 d0 sub %edx,%eax
8e3: 01 45 f0 add %eax,-0x10(%ebp)
}
if (stack == 0){
8e6: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
8ea: 75 1b jne 907 <thread_create+0x5d>
printf(1,"malloc fail \n");
8ec: c7 44 24 04 ed 0a 00 movl $0xaed,0x4(%esp)
8f3: 00
8f4: c7 04 24 01 00 00 00 movl $0x1,(%esp)
8fb: e8 81 fb ff ff call 481 <printf>
return 0;
900: b8 00 00 00 00 mov $0x0,%eax
905: eb 6f jmp 976 <thread_create+0xcc>
}
tid = clone((uint)stack,PSIZE,(uint)start_routine,(int)arg);
907: 8b 4d 0c mov 0xc(%ebp),%ecx
90a: 8b 55 08 mov 0x8(%ebp),%edx
90d: 8b 45 f0 mov -0x10(%ebp),%eax
910: 89 4c 24 0c mov %ecx,0xc(%esp)
914: 89 54 24 08 mov %edx,0x8(%esp)
918: c7 44 24 04 00 10 00 movl $0x1000,0x4(%esp)
91f: 00
920: 89 04 24 mov %eax,(%esp)
923: e8 60 fa ff ff call 388 <clone>
928: 89 45 ec mov %eax,-0x14(%ebp)
if(tid < 0){
92b: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
92f: 79 1b jns 94c <thread_create+0xa2>
printf(1,"clone fails\n");
931: c7 44 24 04 fb 0a 00 movl $0xafb,0x4(%esp)
938: 00
939: c7 04 24 01 00 00 00 movl $0x1,(%esp)
940: e8 3c fb ff ff call 481 <printf>
return 0;
945: b8 00 00 00 00 mov $0x0,%eax
94a: eb 2a jmp 976 <thread_create+0xcc>
}
if(tid > 0){
94c: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
950: 7e 05 jle 957 <thread_create+0xad>
//store threads on thread table
return garbage_stack;
952: 8b 45 f4 mov -0xc(%ebp),%eax
955: eb 1f jmp 976 <thread_create+0xcc>
}
if(tid == 0){
957: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
95b: 75 14 jne 971 <thread_create+0xc7>
printf(1,"tid = 0 return \n");
95d: c7 44 24 04 08 0b 00 movl $0xb08,0x4(%esp)
964: 00
965: c7 04 24 01 00 00 00 movl $0x1,(%esp)
96c: e8 10 fb ff ff call 481 <printf>
}
// wait();
// free(garbage_stack);
return 0;
971: b8 00 00 00 00 mov $0x0,%eax
}
976: c9 leave
977: c3 ret
00000978 <random>:
// generate 0 -> max random number exclude max.
int random(int max){
978: 55 push %ebp
979: 89 e5 mov %esp,%ebp
rands = rands * 1664525 + 1013904233;
97b: a1 30 0b 00 00 mov 0xb30,%eax
980: 69 c0 0d 66 19 00 imul $0x19660d,%eax,%eax
986: 05 69 f3 6e 3c add $0x3c6ef369,%eax
98b: a3 30 0b 00 00 mov %eax,0xb30
return (int)(rands % max);
990: a1 30 0b 00 00 mov 0xb30,%eax
995: 8b 4d 08 mov 0x8(%ebp),%ecx
998: ba 00 00 00 00 mov $0x0,%edx
99d: f7 f1 div %ecx
99f: 89 d0 mov %edx,%eax
}
9a1: 5d pop %ebp
9a2: c3 ret
9a3: 90 nop
000009a4 <init_q>:
#include "queue.h"
#include "types.h"
#include "user.h"
void init_q(struct queue *q){
9a4: 55 push %ebp
9a5: 89 e5 mov %esp,%ebp
q->size = 0;
9a7: 8b 45 08 mov 0x8(%ebp),%eax
9aa: c7 00 00 00 00 00 movl $0x0,(%eax)
q->head = 0;
9b0: 8b 45 08 mov 0x8(%ebp),%eax
9b3: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax)
q->tail = 0;
9ba: 8b 45 08 mov 0x8(%ebp),%eax
9bd: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax)
}
9c4: 5d pop %ebp
9c5: c3 ret
000009c6 <add_q>:
void add_q(struct queue *q, int v){
9c6: 55 push %ebp
9c7: 89 e5 mov %esp,%ebp
9c9: 83 ec 28 sub $0x28,%esp
struct node * n = malloc(sizeof(struct node));
9cc: c7 04 24 08 00 00 00 movl $0x8,(%esp)
9d3: e8 8f fd ff ff call 767 <malloc>
9d8: 89 45 f4 mov %eax,-0xc(%ebp)
n->next = 0;
9db: 8b 45 f4 mov -0xc(%ebp),%eax
9de: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax)
n->value = v;
9e5: 8b 45 f4 mov -0xc(%ebp),%eax
9e8: 8b 55 0c mov 0xc(%ebp),%edx
9eb: 89 10 mov %edx,(%eax)
if(q->head == 0){
9ed: 8b 45 08 mov 0x8(%ebp),%eax
9f0: 8b 40 04 mov 0x4(%eax),%eax
9f3: 85 c0 test %eax,%eax
9f5: 75 0b jne a02 <add_q+0x3c>
q->head = n;
9f7: 8b 45 08 mov 0x8(%ebp),%eax
9fa: 8b 55 f4 mov -0xc(%ebp),%edx
9fd: 89 50 04 mov %edx,0x4(%eax)
a00: eb 0c jmp a0e <add_q+0x48>
}else{
q->tail->next = n;
a02: 8b 45 08 mov 0x8(%ebp),%eax
a05: 8b 40 08 mov 0x8(%eax),%eax
a08: 8b 55 f4 mov -0xc(%ebp),%edx
a0b: 89 50 04 mov %edx,0x4(%eax)
}
q->tail = n;
a0e: 8b 45 08 mov 0x8(%ebp),%eax
a11: 8b 55 f4 mov -0xc(%ebp),%edx
a14: 89 50 08 mov %edx,0x8(%eax)
q->size++;
a17: 8b 45 08 mov 0x8(%ebp),%eax
a1a: 8b 00 mov (%eax),%eax
a1c: 8d 50 01 lea 0x1(%eax),%edx
a1f: 8b 45 08 mov 0x8(%ebp),%eax
a22: 89 10 mov %edx,(%eax)
}
a24: c9 leave
a25: c3 ret
00000a26 <empty_q>:
int empty_q(struct queue *q){
a26: 55 push %ebp
a27: 89 e5 mov %esp,%ebp
if(q->size == 0)
a29: 8b 45 08 mov 0x8(%ebp),%eax
a2c: 8b 00 mov (%eax),%eax
a2e: 85 c0 test %eax,%eax
a30: 75 07 jne a39 <empty_q+0x13>
return 1;
a32: b8 01 00 00 00 mov $0x1,%eax
a37: eb 05 jmp a3e <empty_q+0x18>
else
return 0;
a39: b8 00 00 00 00 mov $0x0,%eax
}
a3e: 5d pop %ebp
a3f: c3 ret
00000a40 <pop_q>:
int pop_q(struct queue *q){
a40: 55 push %ebp
a41: 89 e5 mov %esp,%ebp
a43: 83 ec 28 sub $0x28,%esp
int val;
struct node *destroy;
if(!empty_q(q)){
a46: 8b 45 08 mov 0x8(%ebp),%eax
a49: 89 04 24 mov %eax,(%esp)
a4c: e8 d5 ff ff ff call a26 <empty_q>
a51: 85 c0 test %eax,%eax
a53: 75 5d jne ab2 <pop_q+0x72>
val = q->head->value;
a55: 8b 45 08 mov 0x8(%ebp),%eax
a58: 8b 40 04 mov 0x4(%eax),%eax
a5b: 8b 00 mov (%eax),%eax
a5d: 89 45 f0 mov %eax,-0x10(%ebp)
destroy = q->head;
a60: 8b 45 08 mov 0x8(%ebp),%eax
a63: 8b 40 04 mov 0x4(%eax),%eax
a66: 89 45 f4 mov %eax,-0xc(%ebp)
q->head = q->head->next;
a69: 8b 45 08 mov 0x8(%ebp),%eax
a6c: 8b 40 04 mov 0x4(%eax),%eax
a6f: 8b 50 04 mov 0x4(%eax),%edx
a72: 8b 45 08 mov 0x8(%ebp),%eax
a75: 89 50 04 mov %edx,0x4(%eax)
free(destroy);
a78: 8b 45 f4 mov -0xc(%ebp),%eax
a7b: 89 04 24 mov %eax,(%esp)
a7e: e8 b5 fb ff ff call 638 <free>
q->size--;
a83: 8b 45 08 mov 0x8(%ebp),%eax
a86: 8b 00 mov (%eax),%eax
a88: 8d 50 ff lea -0x1(%eax),%edx
a8b: 8b 45 08 mov 0x8(%ebp),%eax
a8e: 89 10 mov %edx,(%eax)
if(q->size == 0){
a90: 8b 45 08 mov 0x8(%ebp),%eax
a93: 8b 00 mov (%eax),%eax
a95: 85 c0 test %eax,%eax
a97: 75 14 jne aad <pop_q+0x6d>
q->head = 0;
a99: 8b 45 08 mov 0x8(%ebp),%eax
a9c: c7 40 04 00 00 00 00 movl $0x0,0x4(%eax)
q->tail = 0;
aa3: 8b 45 08 mov 0x8(%ebp),%eax
aa6: c7 40 08 00 00 00 00 movl $0x0,0x8(%eax)
}
return val;
aad: 8b 45 f0 mov -0x10(%ebp),%eax
ab0: eb 05 jmp ab7 <pop_q+0x77>
}
return -1;
ab2: b8 ff ff ff ff mov $0xffffffff,%eax
}
ab7: c9 leave
ab8: c3 ret
|
//
// Copyright (C) 2020 Christoph Sommer <sommer@cms-labs.org>
//
// Documentation for these modules is at http://veins.car2x.org/
//
// SPDX-License-Identifier: GPL-2.0-or-later
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#ifdef WITH_OSG
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/LineWidth>
#endif // ifdef WITH_OSG
#include "veins/visualizer/roads/RoadsOsgVisualizer.h"
#include "veins/modules/mobility/traci/TraCIScenarioManager.h"
#include "veins/modules/mobility/traci/TraCICommandInterface.h"
using veins::RoadsOsgVisualizer;
Define_Module(veins::RoadsOsgVisualizer);
#ifndef WITH_OSG
void RoadsOsgVisualizer::initialize(int stage)
{
}
#else
void RoadsOsgVisualizer::initialize(int stage)
{
bool enabled = par("enabled");
if (!enabled) return;
if (!hasGUI()) return;
if (stage == 0) {
TraCIScenarioManager* manager = TraCIScenarioManagerAccess().get();
ASSERT(manager);
figures = new osg::Group();
cOsgCanvas* canvas = getParentModule()->getOsgCanvas();
ASSERT(canvas);
osg::Group* scene = dynamic_cast<osg::Group*>(canvas->getScene());
if (!scene) {
scene = new osg::Group();
canvas->setScene(scene);
}
ASSERT(scene);
scene->addChild(figures);
auto onTraciInitialized = [this, manager](veins::SignalPayload<bool> payload) {
TraCICommandInterface* traci = manager->getCommandInterface();
ASSERT(traci);
std::string colorStr = par("lineColor");
auto color = cFigure::Color(colorStr.c_str());
double width = par("lineWidth");
auto laneIds = traci->getLaneIds();
for (auto laneId : laneIds) {
auto coords = traci->lane(laneId).getShape();
auto line = createLine(coords, color, width);
figures->addChild(line);
}
};
signalManager.subscribeCallback(manager, TraCIScenarioManager::traciInitializedSignal, onTraciInitialized);
}
}
void RoadsOsgVisualizer::handleMessage(cMessage* msg)
{
throw cRuntimeError("RoadsOsgVisualizer does not handle any events");
}
void RoadsOsgVisualizer::finish()
{
}
osg::Geode* RoadsOsgVisualizer::createLine(const std::list<veins::Coord>& coords, cFigure::Color color, double width)
{
auto verts = new osg::Vec3Array();
for (auto coord : coords) {
verts->push_back(osg::Vec3(coord.x, coord.y, coord.z));
}
auto primitiveSet = new osg::DrawArrays(osg::PrimitiveSet::LINE_STRIP);
primitiveSet->setFirst(0);
primitiveSet->setCount(verts->size());
auto geometry = new osg::Geometry();
geometry->setVertexArray(verts);
geometry->addPrimitiveSet(primitiveSet);
osg::Vec4 colorVec(color.red / 255.0, color.green / 255.0, color.blue / 255.0, 1.0);
auto material = new osg::Material();
material->setAmbient(osg::Material::FRONT_AND_BACK, colorVec);
material->setDiffuse(osg::Material::FRONT_AND_BACK, colorVec);
auto lineWidth = new osg::LineWidth();
lineWidth->setWidth(width);
auto stateSet = new osg::StateSet();
stateSet->setAttribute(material);
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
stateSet->setAttribute(lineWidth);
auto geode = new osg::Geode();
geode->addDrawable(geometry);
geode->setStateSet(stateSet);
return geode;
}
#endif // ifdef WITH_OSG
|
; *******************************************************************************************
; *******************************************************************************************
;
; Name : read.asm
; Purpose : READ/DATA/RESTORE Command
; Date : 31st August 2019
; Author : Paul Robson (paul@robsons.org.uk)
;
; *******************************************************************************************
; *******************************************************************************************
Command_READ: ;; read
jsr VariableFind ; get variable/value into zVarDataPtr,zVarType
lda zVarDataPtr ; save variable info on stack
pha
lda zVarDataPtr+1
pha
lda zVarType
pha
;
jsr READGetDataItem ; get the next data item
;
pla ; restore target variable information.
sta zVarType
pla
sta zVarDataPtr+1
pla
sta zVarDataPtr
;
ldx #0
jsr VariableSet ; set the value out.
;
#s_get ; look for comma
#s_next
cmp #token_Comma
beq Command_READ ; found, do another READ
#s_prev ; undo.
rts
Command_DATA: ;; data
jmp SkipEndOfCommand
; *******************************************************************************************
;
; RESTORE data pointer
;
; *******************************************************************************************
Command_RESTORE: ;; restore
pha
lda #0 ; this being zero means 'initialise next read'
sta DataLPtr+0
sta DataLPtr+1
pla
rts
; *******************************************************************************************
;
; Swap the Code and Data pointers
;
; *******************************************************************************************
READSwapPointers:
#s_offsetToA ; current code offset
pha ; save it
lda DataIndex ; get data offset, and copy to offset
#s_AToOffset
pla ; get code offset and save in DataIndex
sta DataIndex
phx
ldx #3 ; swap the Data Pointers (4 bytes) round.
_RSWLoop:
lda DataLPtr+0,x
pha
lda zCodePtr+0,x
sta DataLPtr+0,x
pla
sta zCodePtr+0,x
dex
bpl _RSWLoop
plx
rts
; *******************************************************************************************
;
; Get the next data item from code
;
; *******************************************************************************************
READGetDataItem:
jsr ReadSwapPointers ; swap code and data pointer.
lda zCodePtr+0 ; initialise ?
ora zCodePtr+1
bne _RGDIIsInitialised
;
#s_tostart BasicProgram ; go to start
bra _RGDIFindData ; locate next data from start and read that.
;
; If pointing at a comma, it was DATA xxx,yyy,zzz so can skip and fetch.
;
_RGDIIsInitialised:
#s_get ; is there a comma, e.g. data continuation
cmp #token_Comma
beq _RGDISkipEvaluateExit
;
; No data, so scan forward for next command till data/end.
;
_RGDIFindData:
#s_get ; what's here.
cmp #0 ; end of line
beq _RGDIFindNextLine
cmp #token_DATA ; found data token
beq _RGDISkipEvaluateExit ; then skip it and evaluate
#s_skipelement
bra _RGDIFindData
;
_RGDIFindNextLine:
#s_nextLine ; next line
#s_startLine ; get offset to see if end.
#s_get
pha
#s_next ; to first token/character
#s_next
#s_next
pla
bne _RGDIFindData ; back to scanning.
jsr ReadSwapPointers ; so we get error in line number of READ
#Fatal "Out of Data" ; nothing to evaluate
_RGDISkipEvaluateExit:
#s_next ; skip over , or DATA token.
jsr EvaluateExpression ; evaluate the expression
jsr ReadSwapPointers ; swap the pointers around.
rts
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "test_precomp.hpp"
namespace opencv_test { namespace {
const string FEATURES2D_DIR = "features2d";
const string IMAGE_FILENAME = "tsukuba.png";
const string DESCRIPTOR_DIR = FEATURES2D_DIR + "/descriptor_extractors";
}} // namespace
#include "test_descriptors_regression.impl.hpp"
namespace opencv_test { namespace {
/****************************************************************************************\
* Tests registrations *
\****************************************************************************************/
TEST( Features2d_DescriptorExtractor_BRISK, regression )
{
CV_DescriptorExtractorTest<Hamming> test( "descriptor-brisk",
(CV_DescriptorExtractorTest<Hamming>::DistanceType)2.f,
BRISK::create() );
test.safe_run();
}
TEST( Features2d_DescriptorExtractor_ORB, regression )
{
// TODO adjust the parameters below
CV_DescriptorExtractorTest<Hamming> test( "descriptor-orb",
#if CV_NEON
(CV_DescriptorExtractorTest<Hamming>::DistanceType)25.f,
#else
(CV_DescriptorExtractorTest<Hamming>::DistanceType)12.f,
#endif
ORB::create() );
test.safe_run();
}
TEST( Features2d_DescriptorExtractor_KAZE, regression )
{
CV_DescriptorExtractorTest< L2<float> > test( "descriptor-kaze", 0.03f,
KAZE::create(),
L2<float>(), KAZE::create() );
test.safe_run();
}
TEST( Features2d_DescriptorExtractor_AKAZE, regression )
{
CV_DescriptorExtractorTest<Hamming> test( "descriptor-akaze",
(CV_DescriptorExtractorTest<Hamming>::DistanceType)(486*0.05f),
AKAZE::create(),
Hamming(), AKAZE::create());
test.safe_run();
}
TEST( Features2d_DescriptorExtractor_AKAZE_DESCRIPTOR_KAZE, regression )
{
CV_DescriptorExtractorTest< L2<float> > test( "descriptor-akaze-with-kaze-desc", 0.03f,
AKAZE::create(AKAZE::DESCRIPTOR_KAZE),
L2<float>(), AKAZE::create(AKAZE::DESCRIPTOR_KAZE));
test.safe_run();
}
TEST( Features2d_DescriptorExtractor, batch )
{
string path = string(cvtest::TS::ptr()->get_data_path() + "detectors_descriptors_evaluation/images_datasets/graf");
vector<Mat> imgs, descriptors;
vector<vector<KeyPoint> > keypoints;
int i, n = 6;
Ptr<ORB> orb = ORB::create();
for( i = 0; i < n; i++ )
{
string imgname = format("%s/img%d.png", path.c_str(), i+1);
Mat img = imread(imgname, 0);
imgs.push_back(img);
}
orb->detect(imgs, keypoints);
orb->compute(imgs, keypoints, descriptors);
ASSERT_EQ((int)keypoints.size(), n);
ASSERT_EQ((int)descriptors.size(), n);
for( i = 0; i < n; i++ )
{
EXPECT_GT((int)keypoints[i].size(), 100);
EXPECT_GT(descriptors[i].rows, 100);
}
}
class DescriptorImage : public TestWithParam<std::string>
{
protected:
virtual void SetUp() {
pattern = GetParam();
}
std::string pattern;
};
TEST_P(DescriptorImage, no_crash)
{
vector<String> fnames;
glob(cvtest::TS::ptr()->get_data_path() + pattern, fnames, false);
sort(fnames.begin(), fnames.end());
Ptr<AKAZE> akaze_mldb = AKAZE::create(AKAZE::DESCRIPTOR_MLDB);
Ptr<AKAZE> akaze_mldb_upright = AKAZE::create(AKAZE::DESCRIPTOR_MLDB_UPRIGHT);
Ptr<AKAZE> akaze_mldb_256 = AKAZE::create(AKAZE::DESCRIPTOR_MLDB, 256);
Ptr<AKAZE> akaze_mldb_upright_256 = AKAZE::create(AKAZE::DESCRIPTOR_MLDB_UPRIGHT, 256);
Ptr<AKAZE> akaze_kaze = AKAZE::create(AKAZE::DESCRIPTOR_KAZE);
Ptr<AKAZE> akaze_kaze_upright = AKAZE::create(AKAZE::DESCRIPTOR_KAZE_UPRIGHT);
Ptr<ORB> orb = ORB::create();
Ptr<KAZE> kaze = KAZE::create();
Ptr<BRISK> brisk = BRISK::create();
size_t n = fnames.size();
vector<KeyPoint> keypoints;
Mat descriptors;
orb->setMaxFeatures(5000);
for(size_t i = 0; i < n; i++ )
{
printf("%d. image: %s:\n", (int)i, fnames[i].c_str());
if( strstr(fnames[i].c_str(), "MP.png") != 0 )
{
printf("\tskip\n");
continue;
}
bool checkCount = strstr(fnames[i].c_str(), "templ.png") == 0;
Mat img = imread(fnames[i], -1);
printf("\t%dx%d\n", img.cols, img.rows);
#define TEST_DETECTOR(name, descriptor) \
keypoints.clear(); descriptors.release(); \
printf("\t" name "\n"); fflush(stdout); \
descriptor->detectAndCompute(img, noArray(), keypoints, descriptors); \
printf("\t\t\t(%d keypoints, descriptor size = %d)\n", (int)keypoints.size(), descriptors.cols); fflush(stdout); \
if (checkCount) \
{ \
EXPECT_GT((int)keypoints.size(), 0); \
} \
ASSERT_EQ(descriptors.rows, (int)keypoints.size());
TEST_DETECTOR("AKAZE:MLDB", akaze_mldb);
TEST_DETECTOR("AKAZE:MLDB_UPRIGHT", akaze_mldb_upright);
TEST_DETECTOR("AKAZE:MLDB_256", akaze_mldb_256);
TEST_DETECTOR("AKAZE:MLDB_UPRIGHT_256", akaze_mldb_upright_256);
TEST_DETECTOR("AKAZE:KAZE", akaze_kaze);
TEST_DETECTOR("AKAZE:KAZE_UPRIGHT", akaze_kaze_upright);
TEST_DETECTOR("KAZE", kaze);
TEST_DETECTOR("ORB", orb);
TEST_DETECTOR("BRISK", brisk);
}
}
INSTANTIATE_TEST_CASE_P(Features2d, DescriptorImage,
testing::Values(
"shared/lena.png",
"shared/box*.png",
"shared/fruits*.png",
"shared/airplane.png",
"shared/graffiti.png",
"shared/1_itseez-0001*.png",
"shared/pic*.png",
"shared/templ.png"
)
);
}} // namespace
|
;
; OZ-7xx DK emulation layer for Z88DK
; by Stefano Bodrato - Oct. 2003
;
; void ozvline(byte x,byte y,byte len,byte color)
;
; ------
; $Id: ozvline.asm,v 1.3 2016-06-28 14:48:17 dom Exp $
;
SECTION code_clib
PUBLIC ozvline
PUBLIC _ozvline
EXTERN swapgfxbk
EXTERN __oz_gfxend
EXTERN line
EXTERN ozplotpixel
EXTERN ozpointcolor
.ozvline
._ozvline
push ix
ld ix,2
add ix,sp
call ozpointcolor
ld l,(ix+6) ;y0
ld h,(ix+8) ;x0
ld e,h ;x1
ld a,(ix+4)
add l
ld d,a ;y1 (y0 + len)
call swapgfxbk
push hl
push de
call ozplotpixel
pop de
pop hl
ld ix,ozplotpixel
call line
jp __oz_gfxend
|
EX2DS SEGMENT
is2pow DB ? ; 1- is pow, 0-is not pow
NUM DW 8192
EX2DS ENDS
sseg segment stack
dw 100h dup(?)
sseg ends
cseg segment
assume ds:EX2DS,cs:cseg,ss:sseg
start: mov ax,EX2DS
mov ds,ax
;initialisation
mov si,0
mov is2pow,0
mov cx,15
mov ax,NUM
;check bit number
L2: shl ax,1
jc L1
loop L2
;check that number is pow of 2
L1: cmp ax,0
jnz SOF
mov is2pow,1
SOF: mov ah,4ch
int 21h
cseg ends
end start |
; A061340: a(n) = n*omega(n)^n where omega(n) is the number of distinct prime divisors of n.
; Submitted by Jon Maiga
; 0,2,3,4,5,384,7,8,9,10240,11,49152,13,229376,491520,16,17,4718592,19,20971520,44040192,92274688,23,402653184,25,1744830464,27,7516192768,29,6176733962839470,31,32,283467841536,584115552256,1202590842880,2473901162496,37,10445360463872,21440476741632,43980465111040,41,4595597543523519086778,43,774056185954304,1583296743997440,3236962232172544,47,13510798882111488,49,56294995342131200,114841790497947648,234187180623265792,53,972777519512027136,1981583836043018240,4035225266123964416
mov $1,$0
add $0,1
seq $1,1221 ; Number of distinct primes dividing n (also called omega(n)).
pow $1,$0
mul $0,$1
|
; A156573: a(n) = 34*a(n-1)-a(n-2)-4232 for n > 2; a(1)=529, a(2)=13225.
; 529,13225,444889,15108769,513249025,17435353849,592288777609,20120383080625,683500735959409,23218904639535049,788759257008228025,26794595833640213569,910227499086759029089,30920940373116166771225
seq $0,2315 ; NSW numbers: a(n) = 6*a(n-1) - a(n-2); also a(n)^2 - 2*b(n)^2 = -1 with b(n)=A001653(n+1).
pow $0,2
div $0,48
mul $0,12696
add $0,529
|
; A194114: Sum{floor(j*sqrt(11) : 1<=j<=n}; n-th partial sum of Beatty sequence for sqrt(11).
; 3,9,18,31,47,66,89,115,144,177,213,252,295,341,390,443,499,558,621,687,756,828,904,983,1065,1151,1240,1332,1428,1527,1629,1735,1844,1956,2072,2191,2313,2439,2568,2700,2835,2974,3116,3261,3410,3562,3717
lpb $0
mov $2,$0
sub $0,1
seq $2,171982 ; Beatty sequence for sqrt(11).
add $1,$2
lpe
add $1,3
mov $0,$1
|
; A042986: Primes congruent to {0, 1, 2, 3} mod 5.
; Submitted by Jon Maiga
; 2,3,5,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
mov $1,3
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,5
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,18
add $5,$1
div $5,5
mov $6,$5
lpe
mov $0,$5
add $0,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x3026, %rsi
lea addresses_D_ht+0x1414, %rdi
nop
nop
nop
nop
nop
xor %r13, %r13
mov $31, %rcx
rep movsl
nop
nop
cmp $9830, %r8
lea addresses_normal_ht+0xda6, %r11
nop
nop
nop
nop
nop
inc %rdx
mov $0x6162636465666768, %r8
movq %r8, %xmm1
vmovups %ymm1, (%r11)
nop
nop
and %rdx, %rdx
lea addresses_WC_ht+0x1e2e6, %r11
nop
nop
nop
nop
nop
cmp $24050, %rdx
mov (%r11), %di
nop
nop
cmp %r8, %r8
lea addresses_UC_ht+0x15e6, %rdi
nop
nop
nop
cmp %rcx, %rcx
mov (%rdi), %si
nop
nop
nop
nop
sub $60192, %rsi
lea addresses_WC_ht+0x1ade6, %rsi
lea addresses_WT_ht+0x12406, %rdi
sub $37751, %rax
mov $41, %rcx
rep movsw
nop
nop
nop
nop
add $13277, %rcx
lea addresses_UC_ht+0x15cd6, %r8
lfence
vmovups (%r8), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $0, %xmm1, %rdx
nop
and %rax, %rax
lea addresses_WT_ht+0x1b9e6, %rsi
lea addresses_normal_ht+0x135e6, %rdi
and %r11, %r11
mov $120, %rcx
rep movsq
nop
xor $41900, %rdx
lea addresses_WC_ht+0x16f66, %rsi
clflush (%rsi)
nop
and $29340, %rdx
movw $0x6162, (%rsi)
nop
mfence
lea addresses_WT_ht+0x1fb6, %rcx
nop
sub $63926, %rdx
vmovups (%rcx), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rdi
cmp %rcx, %rcx
lea addresses_A_ht+0x1c266, %r8
nop
nop
add $12318, %r13
movups (%r8), %xmm1
vpextrq $1, %xmm1, %rdi
nop
inc %rsi
lea addresses_UC_ht+0x4de6, %rsi
lea addresses_D_ht+0xf9e6, %rdi
nop
nop
nop
add $61218, %r8
mov $44, %rcx
rep movsq
nop
nop
nop
and %rax, %rax
lea addresses_WT_ht+0x103e6, %r13
nop
nop
nop
nop
dec %rax
mov (%r13), %ecx
add $6926, %rsi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %r8
push %rdi
push %rdx
push %rsi
// Store
lea addresses_UC+0x3e6, %r12
nop
nop
nop
nop
add $36092, %r8
mov $0x5152535455565758, %rdi
movq %rdi, (%r12)
nop
nop
nop
nop
sub %rdi, %rdi
// Store
lea addresses_normal+0xbde6, %rdi
nop
nop
sub $22487, %rsi
movb $0x51, (%rdi)
nop
nop
nop
and %r15, %r15
// Store
lea addresses_normal+0x1b6, %r14
nop
sub $4152, %r12
movb $0x51, (%r14)
nop
nop
add %r15, %r15
// Faulty Load
lea addresses_normal+0xbde6, %rsi
nop
nop
nop
cmp $11471, %rdx
movb (%rsi), %r8b
lea oracles, %r12
and $0xff, %r8
shlq $12, %r8
mov (%r12,%r8,1), %r8
pop %rsi
pop %rdx
pop %rdi
pop %r8
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': True, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 7, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': True, 'congruent': 11, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 3, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 7, 'size': 16, 'same': True, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 8, 'size': 4, 'same': False, 'NT': False}}
{'51': 21829}
51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51 51
*/
|
SFX_Battle_0C_Ch1:
unknownnoise0x20 15, 143, 17
unknownnoise0x20 4, 255, 18
unknownnoise0x20 10, 241, 85
endchannel
|
; Startup Code for Sega Master System
;
; Haroldo O. Pinheiro February 2006
;
; $Id: sms_crt0.asm,v 1.20 2016-07-13 22:12:25 dom Exp $
;
DEFC ROM_Start = $0000
DEFC INT_Start = $0038
DEFC NMI_Start = $0066
DEFC CODE_Start = $0100
DEFC RAM_Start = $C000
DEFC RAM_Length = $2000
DEFC Stack_Top = $dff0
MODULE sms_crt0
;-------
; Include zcc_opt.def to find out information about us
;-------
defc crt0 = 1
INCLUDE "zcc_opt.def"
;-------
; Some general scope declarations
;-------
EXTERN _main ;main() is always external to crt0 code
PUBLIC cleanup ;jp'd to by exit()
PUBLIC l_dcal ;jp(hl)
PUBLIC raster_procs ;Raster interrupt handlers
PUBLIC pause_procs ;Pause interrupt handlers
PUBLIC timer ;This is incremented every time a VBL/HBL interrupt happens
PUBLIC _pause_flag ;This alternates between 0 and 1 every time pause is pressed
PUBLIC __GAMEGEAR_ENABLED
PUBLIC __IO_VDP_DATA
PUBLIC __IO_VDP_COMMAND
PUBLIC __IO_VDP_STATUS
defc __IO_VDP_DATA = 0xbe
defc __IO_VDP_COMMAND = 0xbf
defc __IO_VDP_STATUS = 0xbf
if __GAMEGEAR__
defc CONSOLE_XOFFSET = 6
defc CONSOLE_YOFFSET = 3
defc CONSOLE_COLUMNS = 20
defc CONSOLE_ROWS = 18
defc __GAMEGEAR_ENABLED = 1
else
defc __GAMEGEAR_ENABLED = 0
defc CONSOLE_COLUMNS = 32
defc CONSOLE_ROWS = 24
endif
defc TAR__register_sp = Stack_Top
defc TAR__clib_exit_stack_size = 32
defc __CPU_CLOCK = 3580000
INCLUDE "crt/classic/crt_rules.inc"
org ROM_Start
jp start
defm "Sega Master System - Small C+"
;-------
; Interrupt handlers
;-------
filler1:
defs (INT_Start - filler1)
int_RASTER:
push af
in a, ($BF)
or a
jp p, int_not_VBL ; Bit 7 not set
;int_VBL:
push hl
ld hl, timer
ld a, (hl)
inc a
ld (hl), a
inc hl
ld a, (hl)
adc a, 1
ld (hl), a ;Increments the timer
ld hl, raster_procs
call int_handler
pop hl
int_not_VBL:
pop af
ei
ret
filler2:
defs (NMI_Start - filler2)
int_PAUSE:
push af
push hl
ld hl, _pause_flag
ld a, (hl)
xor a, 1
ld (hl), a
ld hl, pause_procs
call int_handler
pop hl
pop af
retn
int_handler:
push bc
push de
int_loop:
ld a, (hl)
inc hl
or (hl)
jr z, int_done
push hl
ld a, (hl)
dec hl
ld l, (hl)
ld h, a
call call_int_handler
pop hl
inc hl
jr int_loop
int_done:
pop de
pop bc
ret
call_int_handler:
jp (hl)
;-------
; Beginning of the actual code
;-------
filler3:
defs (CODE_Start - filler3)
start:
; Make room for the atexit() stack
INCLUDE "crt/classic/crt_init_sp.asm"
INCLUDE "crt/classic/crt_init_atexit.asm"
; Clear static memory
ld hl,RAM_Start
ld de,RAM_Start+1
ld bc,RAM_Length-1
ld (hl),0
ldir
call crt0_init_bss
ld (exitsp),sp
call DefaultInitialiseVDP
im 1
ei
; Entry to the user code
call _main
cleanup:
;
; Deallocate memory which has been allocated here!
;
push hl
call crt0_exit
endloop:
jr endloop
l_dcal:
jp (hl)
;---------------------------------
; VDP Initialization
;---------------------------------
DefaultInitialiseVDP:
ld hl,_Data
ld b,_End-_Data
ld c,$bf
otir
IF __GAMEGEAR__
; Load default palette for gamegear
EXTERN asm_load_palette_gamegear
ld hl,gg_palette
ld b,16
ld c,0
call asm_load_palette_gamegear
ENDIF
ret
gg_palette:
defw 0x0000 ;transparent
defw 0x0000 ;00 00 00
defw 0x00a0 ;00 aa 00
defw 0x00f0 ;00 ff 00
defw 0x0500 ;00 00 55
defw 0x0f00 ;00 00 ff
defw 0x0005 ;55 00 00
defw 0x0ff0 ;00 ff ff
defw 0x000a ;aa 00 00
defw 0x000f ;ff 00 00
defw 0x0055 ;00 55 55
defw 0x00ff ;ff ff 00
defw 0x0050 ;00 55 00
defw 0x0f0f ;ff 00 ff
defw 0x0555 ;55 55 55
defw 0x0fff ;ff ff ff
DEFC SpriteSet = 0 ; 0 for sprites to use tiles 0-255, 1 for 256+
DEFC NameTableAddress = $3800 ; must be a multiple of $800; usually $3800; fills $700 bytes (unstretched)
DEFC SpriteTableAddress = $3f00 ; must be a multiple of $100; usually $3f00; fills $100 bytes
_Data:
defb @00000100,$80
; |||||||`- Disable synch
; ||||||`-- Enable extra height modes
; |||||`--- SMS mode instead of SG
; ||||`---- Shift sprites left 8 pixels
; |||`----- Enable line interrupts
; ||`------ Blank leftmost column for scrolling
; |`------- Fix top 2 rows during horizontal scrolling
; `-------- Fix right 8 columns during vertical scrolling
defb @10000000,$81
; |||| |`- Zoomed sprites -> 16x16 pixels
; |||| `-- Doubled sprites -> 2 tiles per sprite, 8x16
; |||`---- 30 row/240 line mode
; ||`----- 28 row/224 line mode
; |`------ Enable VBlank interrupts
; `------- Enable display
defb (NameTableAddress/1024) |@11110001,$82
defb $FF,$83
defb $FF,$84
defb (SpriteTableAddress/128)|@10000001,$85
defb (SpriteSet/2^2) |@11111011,$86
defb $f|$f0,$87
; `-------- Border palette colour (sprite palette)
defb $00,$88
; ``------- Horizontal scroll
defb $00,$89
; ``------- Vertical scroll
defb $ff,$8a
; ``------- Line interrupt spacing ($ff to disable)
_End:
INCLUDE "crt/classic/crt_runtime_selection.asm"
IF DEFINED_CRT_ORG_BSS
defc __crt_org_bss = CRT_ORG_BSS
ELSE
defc __crt_org_bss = RAM_Start
ENDIF
; If we were given a model then use it
IF DEFINED_CRT_MODEL
defc __crt_model = CRT_MODEL
ELSE
defc __crt_model = 1
ENDIF
INCLUDE "crt/classic/crt_section.asm"
SECTION bss_crt
raster_procs: defs 16 ;Raster interrupt handlers
pause_procs: defs 16 ;Pause interrupt handlers
timer: defw 0 ;This is incremented every time a VBL/HBL interrupt happens
_pause_flag: defb 0 ;This alternates between 0 and 1 every time pause is pressed
__gamegear_flag: defb 0 ;Non zero if running on a gamegear
; DEFINE SECTIONS FOR BANKSWITCHING
; consistent with appmake and new c library
IFNDEF CRT_ORG_BANK_02
defc CRT_ORG_BANK_02 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_03
defc CRT_ORG_BANK_03 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_04
defc CRT_ORG_BANK_04 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_05
defc CRT_ORG_BANK_05 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_06
defc CRT_ORG_BANK_06 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_07
defc CRT_ORG_BANK_07 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_08
defc CRT_ORG_BANK_08 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_09
defc CRT_ORG_BANK_09 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0A
defc CRT_ORG_BANK_0A = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0B
defc CRT_ORG_BANK_0B = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0C
defc CRT_ORG_BANK_0C = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0D
defc CRT_ORG_BANK_0D = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0E
defc CRT_ORG_BANK_0E = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_0F
defc CRT_ORG_BANK_0F = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_10
defc CRT_ORG_BANK_10 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_11
defc CRT_ORG_BANK_11 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_12
defc CRT_ORG_BANK_12 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_13
defc CRT_ORG_BANK_13 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_14
defc CRT_ORG_BANK_14 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_15
defc CRT_ORG_BANK_15 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_16
defc CRT_ORG_BANK_16 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_17
defc CRT_ORG_BANK_17 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_18
defc CRT_ORG_BANK_18 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_19
defc CRT_ORG_BANK_19 = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1A
defc CRT_ORG_BANK_1A = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1B
defc CRT_ORG_BANK_1B = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1C
defc CRT_ORG_BANK_1C = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1D
defc CRT_ORG_BANK_1D = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1E
defc CRT_ORG_BANK_1E = 0x8000
ENDIF
IFNDEF CRT_ORG_BANK_1F
defc CRT_ORG_BANK_1F = 0x8000
ENDIF
SECTION BANK_02
org CRT_ORG_BANK_02
SECTION BANK_03
org CRT_ORG_BANK_03
SECTION BANK_04
org CRT_ORG_BANK_04
SECTION BANK_05
org CRT_ORG_BANK_05
SECTION BANK_06
org CRT_ORG_BANK_06
SECTION BANK_07
org CRT_ORG_BANK_07
SECTION BANK_08
org CRT_ORG_BANK_08
SECTION BANK_09
org CRT_ORG_BANK_09
SECTION BANK_0A
org CRT_ORG_BANK_0A
SECTION BANK_0B
org CRT_ORG_BANK_0B
SECTION BANK_0C
org CRT_ORG_BANK_0C
SECTION BANK_0D
org CRT_ORG_BANK_0D
SECTION BANK_0E
org CRT_ORG_BANK_0E
SECTION BANK_0F
org CRT_ORG_BANK_0F
SECTION BANK_10
org CRT_ORG_BANK_10
SECTION BANK_11
org CRT_ORG_BANK_11
SECTION BANK_12
org CRT_ORG_BANK_12
SECTION BANK_13
org CRT_ORG_BANK_13
SECTION BANK_14
org CRT_ORG_BANK_14
SECTION BANK_15
org CRT_ORG_BANK_15
SECTION BANK_16
org CRT_ORG_BANK_16
SECTION BANK_17
org CRT_ORG_BANK_17
SECTION BANK_18
org CRT_ORG_BANK_18
SECTION BANK_19
org CRT_ORG_BANK_19
SECTION BANK_1A
org CRT_ORG_BANK_1A
SECTION BANK_1B
org CRT_ORG_BANK_1B
SECTION BANK_1C
org CRT_ORG_BANK_1C
SECTION BANK_1D
org CRT_ORG_BANK_1D
SECTION BANK_1E
org CRT_ORG_BANK_1E
SECTION BANK_1F
org CRT_ORG_BANK_1F
|
db "DARKNESS@" ; species name
db "It dwells in the"
next "darkness of caves."
next "It uses its sharp"
page "claws to dig up"
next "gems that it uses"
next "to nourish itself.@"
|
//----------------------------------*-C++-*----------------------------------//
/*!
* \file Utils/utils/Hash_Functions.cc
* \author Thomas M. Evans
* \date Sat Sep 03 18:55:17 2011
* \brief Member definitions of Hash_Functions classes.
* \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC.
*/
//---------------------------------------------------------------------------//
#include "Hash_Functions.hh"
//===========================================================================//
// PRIME NUMBER TABLE
//===========================================================================//
namespace
{
//! Table of prime numbers.
def::size_type primes[] = {251, // 0
509, // 1
1021, // 2
2039, // 3
4093, // 4
8191, // 5
16381, // 6
32749, // 7
65521, // 8
131071, // 9
262139, // 10
524287, // 11
1048573, // 12
2097143, // 13
4194301, // 14
8388593, // 15
16777213, // 16
33554393, // 17
67108859, // 18
134217689, // 19
268435399, // 20
536870909, // 21
1073741789, // 22
2147483647}; // 23
//! Number of primes in the table.
const def::size_type num_primes = 24;
}
//===========================================================================//
// HASH_FUNCTIONS DEFINITIONS
//===========================================================================//
namespace profugus
{
//---------------------------------------------------------------------------//
// INT_MOD_HASH_FUNCTION DEFINITIONS
//---------------------------------------------------------------------------//
// CONSTRUCTOR
//---------------------------------------------------------------------------//
/*!
* \brief Constructor.
*/
Int_Mod_Hash_Function::Int_Mod_Hash_Function(size_type num_objects)
{
// find the prime number > num_objects using the prime number table
size_type *M = std::lower_bound(&primes[0],
&primes[num_primes], num_objects);
CHECK(M != &primes[num_primes]);
// assign M
d_M = *M;
ENSURE(d_M >= num_objects);
}
} // end namespace profugus
//---------------------------------------------------------------------------//
// end of Hash_Functions.cc
//---------------------------------------------------------------------------//
|
; Program 01 - Addition of two 20-Bytes numbers
; Written by Hamidreza Hosseinkhani (hosseinkhani@live.com)
; June, 2011
TITLE Addition of two 20-Bytes numbers
StkSeg SEGMENT para stack 'stack'
DB 64 DUP (?)
StkSeg ENDS
DtaSeg SEGMENT para private 'data'
Num1L DT 11223344556677889900h
Num1H DT 0AABBCCDDEEFF12345678h
ORG 0020h
Num2L DT 0FEDCBA9876543210ABCDh
Num2H DT 0ABBACDDCEFFEAFFAACCAh
ORG 0050h
Sum DD 5 DUP (?)
DtaSeg ENDS
CodSeg SEGMENT para private 'code'
Main PROC near
ASSUME cs:CodSeg, ds:DtaSeg, ss:StkSeg
mov ax, DtaSeg
mov ds, ax
mov si, OFFSET Num1L
mov di, OFFSET Num2L
mov bx, OFFSET Sum
mov ax, WORD PTR [si]
add ax, WORD PTR [di]
mov WORD PTR [bx], ax
inc si
inc si
inc di
inc di
inc bx
inc bx
mov cx, 9
Next: mov ax, WORD PTR [si]
adc ax, WORD PTR [di]
mov WORD PTR [bx], ax
inc si
inc si
inc di
inc di
inc bx
inc bx
loop Next
mov ax, 4C00h
int 21h
Main ENDP
CodSeg ENDS
END Main |
#include "UI/MainWindow/MainWindow.h"
#include "ui_mainwindow.h"
/*!
*/
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Fix to resize MainWindow smaller
ui->lblImage->setMinimumSize(1, 1);
// Register Events
this->connect(ui->btnDetectFeatures, SIGNAL(clicked()), this, SLOT(btnDetectFeatures_clicked()));
this->connect(ui->btnMatchFeatures, SIGNAL(clicked()), this, SLOT(btnMatchFeatures_clicked()));
this->connect(ui->sldCurrentImage, SIGNAL(valueChanged(int)), this, SLOT(sldCurrentImage_valueChanged()));
this->connect(ui->btnManualSelectFeature, SIGNAL(clicked()), this, SLOT(btnManualSelectFeature_clicked()));
//this->connect(ui-actionImport)
this->connect(ui->actionNode_Editor, &QAction::triggered, this, &MainWindow::mnuNodeEditor_clicked);
this->connect(ui->actionImport, &QAction::triggered, this, &MainWindow::mnuImport_clicked);
this->connect(ui->action3D_View, &QAction::triggered, this, &MainWindow::mnu3DView_clicked);
this->connect(ui->actionFootage_viewer, &QAction::triggered, this, &MainWindow::mnuFootage_viewer_clicked);
this->connect(ui->actionSettings, &QAction::triggered, this, &MainWindow::mnuSettings_clicked);
}
/*!
*/
MainWindow::~MainWindow()
{
delete ui;
}
/*!
*/
void MainWindow::presentImage() {
int currIdx = ui->sldCurrentImage->value();
if(this->imgContainerList.size() <= 0 || this->featureContainerList.size() <= 0) {
std::cout << "imgContainerList count:" << this->imgContainerList.size() << std::endl;
std::cout << "featureContainerList count:" << this->featureContainerList.size() << std::endl;
return;
}
cv::Mat currImage = ImageUtils::DrawKeypointFeatures(imgContainerList[currIdx].getImage(), this->featureContainerList[currIdx]);
QPixmap pixmapImg = ImageConverter::ToQPixmap(currImage);
ui->lblImage->setPixmap(pixmapImg.scaled(ui->lblImage->width(), ui->lblImage->height(), Qt::KeepAspectRatio));
}
/*!
*
*/
void MainWindow::manualSelectFeature()
{
// Get current image
// Select rectangle and add this as keypoint to feature container
int currIdx = ui->sldCurrentImage->value();
if(this->imgContainerList.size() > currIdx) {
cv::Mat currImage = imgContainerList[currIdx].getImage();
// Define initial bounding box
cv::Rect2d bbox(287, 23, 86, 320);
// Uncomment the line below to select a different bounding box
bbox = cv::selectROI(currImage, false);
if(this->featureContainerList.size() > 0) {
// Set center of selected rectangle as keypoint
this->featureContainerList.at(0).keyPointList.at(0).pt.x = float(bbox.x + (bbox.width / 2));
this->featureContainerList.at(0).keyPointList.at(0).pt.y = float(bbox.y + (bbox.height / 2));
// Display bounding box.
//cv::rectangle(currImage, bbox, cv::Scalar( 255, 0, 0 ), 2, 1 );
} else {
// TODO
}
}
}
/*!
Event Handlers
*/
void MainWindow::btnDetectFeatures_clicked() {
std::cout << "btnDetectFeatures_clicked" << std::endl;
DetectorManager detector(this->settings);
this->featureContainerList = detector.StartDetection(this->imgContainerList);
this->presentImage();
}
/*!
*/
void MainWindow::btnMatchFeatures_clicked()
{
if(this->imgContainerList.size() != this->featureContainerList.size()) {
return;
}
SettingsFeatureTracker tmpSettings;
CSRTTracker tracker(tmpSettings);
tracker.StartTracking(this->imgContainerList, this->featureContainerList);
return;
SIFTDescriptorExtractor extractor;
this->descContainerList = extractor.StartExtraction(this->imgContainerList, this->featureContainerList);
std::cout << "descriptorList count " << this->descContainerList.size() << std::endl;
FLANNMatcher matcher(this->imgContainerList, this->descContainerList);
this->dmatchContainerList = matcher.StartMatching();
std::cout << "DMatchContainer List count " << this->dmatchContainerList.size() << std::endl;
}
/*!
*/
void MainWindow::sldCurrentImage_valueChanged() {
this->presentImage();
}
/*!
*/
void MainWindow::btnManualSelectFeature_clicked()
{
this->manualSelectFeature();
}
void MainWindow::mnuNodeEditor_clicked()
{
this->nodeGraph = std::make_shared<NodeGraph>(this);
this->addDockWidget(Qt::TopDockWidgetArea, this->nodeGraph.get());
//this->viewport3d->initVulkanRender();
}
/*!
*/
void MainWindow::mnu3DView_clicked()
{
this->viewport3d = std::make_shared<Viewport3d>(this);
this->addDockWidget(Qt::RightDockWidgetArea, this->viewport3d.get());
this->viewport3d->setFloating(true);
this->viewport3d->resize(1280, 720);
this->viewport3d->initVulkanRender();
}
/*!
*/
void MainWindow::mnuFootage_viewer_clicked()
{
this->footageViewer = std::make_shared<FootageViewer>(this);
this->addDockWidget(Qt::BottomDockWidgetArea, this->footageViewer.get());
}
/*!
*/
void MainWindow::mnuSettings_clicked()
{
SettingsWindow settingsWindow(this->settings);
settingsWindow.exec();
if (settingsWindow.result() == QDialog::Accepted) {
this->settings = settingsWindow.getDataFromFields();
}
}
/*!
*/
void MainWindow::mnuImport_clicked()
{
QStringList imageList = ImageLoader::PickImages();
if (imageList.size() <= 0) {
return;
}
//Check file extension
QFileInfo info(imageList.at(0));
std::cout << "File suffix:" << info.suffix().toStdString() << std::endl;
if (info.suffix().toStdString() == "mp4") {
this->imgContainerList = ImageLoader::LoadVideo(imageList.at(0));
}
else {
this->imgContainerList = ImageLoader::BulkLoadImage(imageList);
}
ui->sldCurrentImage->setRange(0, static_cast<int>(this->imgContainerList.size()) - 1);
this->presentImage();
}
/*!
*/
void MainWindow::resizeEvent(QResizeEvent *event) {
this->presentImage();
}
|
; A083318: a(0) = 1; for n>0, a(n) = 2^n + 1.
; 1,3,5,9,17,33,65,129,257,513,1025,2049,4097,8193,16385,32769,65537,131073,262145,524289,1048577,2097153,4194305,8388609,16777217,33554433,67108865,134217729,268435457,536870913,1073741825,2147483649,4294967297,8589934593,17179869185,34359738369,68719476737,137438953473,274877906945,549755813889,1099511627777,2199023255553,4398046511105,8796093022209,17592186044417,35184372088833,70368744177665,140737488355329,281474976710657,562949953421313,1125899906842625,2251799813685249,4503599627370497
mov $1,2
pow $1,$0
div $1,2
mul $1,2
add $1,1
mov $0,$1
|
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/module-decoder.h"
#include "src/base/functional.h"
#include "src/base/platform/platform.h"
#include "src/base/template-utils.h"
#include "src/counters.h"
#include "src/flags.h"
#include "src/macro-assembler.h"
#include "src/objects-inl.h"
#include "src/ostreams.h"
#include "src/v8.h"
#include "src/wasm/decoder.h"
#include "src/wasm/function-body-decoder-impl.h"
#include "src/wasm/wasm-limits.h"
namespace v8 {
namespace internal {
namespace wasm {
#define TRACE(...) \
do { \
if (FLAG_trace_wasm_decoder) PrintF(__VA_ARGS__); \
} while (false)
namespace {
constexpr char kNameString[] = "name";
constexpr char kExceptionString[] = "exception";
constexpr char kUnknownString[] = "<unknown>";
template <size_t N>
constexpr size_t num_chars(const char (&)[N]) {
return N - 1; // remove null character at end.
}
const char* ExternalKindName(ImportExportKindCode kind) {
switch (kind) {
case kExternalFunction:
return "function";
case kExternalTable:
return "table";
case kExternalMemory:
return "memory";
case kExternalGlobal:
return "global";
}
return "unknown";
}
} // namespace
const char* SectionName(SectionCode code) {
switch (code) {
case kUnknownSectionCode:
return "Unknown";
case kTypeSectionCode:
return "Type";
case kImportSectionCode:
return "Import";
case kFunctionSectionCode:
return "Function";
case kTableSectionCode:
return "Table";
case kMemorySectionCode:
return "Memory";
case kGlobalSectionCode:
return "Global";
case kExportSectionCode:
return "Export";
case kStartSectionCode:
return "Start";
case kCodeSectionCode:
return "Code";
case kElementSectionCode:
return "Element";
case kDataSectionCode:
return "Data";
case kNameSectionCode:
return kNameString;
case kExceptionSectionCode:
if (FLAG_experimental_wasm_eh) return kExceptionString;
return kUnknownString;
default:
return kUnknownString;
}
}
namespace {
bool validate_utf8(Decoder* decoder, WireBytesRef string) {
return unibrow::Utf8::ValidateEncoding(
decoder->start() + decoder->GetBufferRelativeOffset(string.offset()),
string.length());
}
ValueType TypeOf(const WasmModule* module, const WasmInitExpr& expr) {
switch (expr.kind) {
case WasmInitExpr::kNone:
return kWasmStmt;
case WasmInitExpr::kGlobalIndex:
return expr.val.global_index < module->globals.size()
? module->globals[expr.val.global_index].type
: kWasmStmt;
case WasmInitExpr::kI32Const:
return kWasmI32;
case WasmInitExpr::kI64Const:
return kWasmI64;
case WasmInitExpr::kF32Const:
return kWasmF32;
case WasmInitExpr::kF64Const:
return kWasmF64;
case WasmInitExpr::kAnyRefConst:
return kWasmAnyRef;
default:
UNREACHABLE();
}
}
// Reads a length-prefixed string, checking that it is within bounds. Returns
// the offset of the string, and the length as an out parameter.
WireBytesRef consume_string(Decoder& decoder, bool validate_utf8,
const char* name) {
uint32_t length = decoder.consume_u32v("string length");
uint32_t offset = decoder.pc_offset();
const byte* string_start = decoder.pc();
// Consume bytes before validation to guarantee that the string is not oob.
if (length > 0) {
decoder.consume_bytes(length, name);
if (decoder.ok() && validate_utf8 &&
!unibrow::Utf8::ValidateEncoding(string_start, length)) {
decoder.errorf(string_start, "%s: no valid UTF-8 string", name);
}
}
return {offset, decoder.failed() ? 0 : length};
}
// An iterator over the sections in a wasm binary module.
// Automatically skips all unknown sections.
class WasmSectionIterator {
public:
explicit WasmSectionIterator(Decoder& decoder)
: decoder_(decoder),
section_code_(kUnknownSectionCode),
section_start_(decoder.pc()),
section_end_(decoder.pc()) {
next();
}
inline bool more() const { return decoder_.ok() && decoder_.more(); }
inline SectionCode section_code() const { return section_code_; }
inline const byte* section_start() const { return section_start_; }
inline uint32_t section_length() const {
return static_cast<uint32_t>(section_end_ - section_start_);
}
inline Vector<const uint8_t> payload() const {
return {payload_start_, payload_length()};
}
inline const byte* payload_start() const { return payload_start_; }
inline uint32_t payload_length() const {
return static_cast<uint32_t>(section_end_ - payload_start_);
}
inline const byte* section_end() const { return section_end_; }
// Advances to the next section, checking that decoding the current section
// stopped at {section_end_}.
void advance(bool move_to_section_end = false) {
if (move_to_section_end && decoder_.pc() < section_end_) {
decoder_.consume_bytes(
static_cast<uint32_t>(section_end_ - decoder_.pc()));
}
if (decoder_.pc() != section_end_) {
const char* msg = decoder_.pc() < section_end_ ? "shorter" : "longer";
decoder_.errorf(decoder_.pc(),
"section was %s than expected size "
"(%u bytes expected, %zu decoded)",
msg, section_length(),
static_cast<size_t>(decoder_.pc() - section_start_));
}
next();
}
private:
Decoder& decoder_;
SectionCode section_code_;
const byte* section_start_;
const byte* payload_start_;
const byte* section_end_;
// Reads the section code/name at the current position and sets up
// the embedder fields.
void next() {
if (!decoder_.more()) {
section_code_ = kUnknownSectionCode;
return;
}
section_start_ = decoder_.pc();
uint8_t section_code = decoder_.consume_u8("section code");
// Read and check the section size.
uint32_t section_length = decoder_.consume_u32v("section length");
payload_start_ = decoder_.pc();
if (decoder_.checkAvailable(section_length)) {
// Get the limit of the section within the module.
section_end_ = payload_start_ + section_length;
} else {
// The section would extend beyond the end of the module.
section_end_ = payload_start_;
}
if (section_code == kUnknownSectionCode) {
// Check for the known "name" section.
section_code =
ModuleDecoder::IdentifyUnknownSection(decoder_, section_end_);
// As a side effect, the above function will forward the decoder to after
// the identifier string.
payload_start_ = decoder_.pc();
} else if (!IsValidSectionCode(section_code)) {
decoder_.errorf(decoder_.pc(), "unknown section code #0x%02x",
section_code);
section_code = kUnknownSectionCode;
}
section_code_ = decoder_.failed() ? kUnknownSectionCode
: static_cast<SectionCode>(section_code);
if (section_code_ == kUnknownSectionCode && section_end_ > decoder_.pc()) {
// skip to the end of the unknown section.
uint32_t remaining = static_cast<uint32_t>(section_end_ - decoder_.pc());
decoder_.consume_bytes(remaining, "section payload");
}
}
};
} // namespace
// The main logic for decoding the bytes of a module.
class ModuleDecoderImpl : public Decoder {
public:
explicit ModuleDecoderImpl(ModuleOrigin origin)
: Decoder(nullptr, nullptr),
origin_(FLAG_assume_asmjs_origin ? kAsmJsOrigin : origin) {}
ModuleDecoderImpl(const byte* module_start, const byte* module_end,
ModuleOrigin origin)
: Decoder(module_start, module_end),
origin_(FLAG_assume_asmjs_origin ? kAsmJsOrigin : origin) {
if (end_ < start_) {
error(start_, "end is less than start");
end_ = start_;
}
}
virtual void onFirstError() {
pc_ = end_; // On error, terminate section decoding loop.
}
void DumpModule(const Vector<const byte> module_bytes) {
std::string path;
if (FLAG_dump_wasm_module_path) {
path = FLAG_dump_wasm_module_path;
if (path.size() &&
!base::OS::isDirectorySeparator(path[path.size() - 1])) {
path += base::OS::DirectorySeparator();
}
}
// File are named `HASH.{ok,failed}.wasm`.
size_t hash = base::hash_range(module_bytes.start(), module_bytes.end());
EmbeddedVector<char, 32> buf;
SNPrintF(buf, "%016zx.%s.wasm", hash, ok() ? "ok" : "failed");
std::string name(buf.start());
if (FILE* wasm_file = base::OS::FOpen((path + name).c_str(), "wb")) {
if (fwrite(module_bytes.start(), module_bytes.length(), 1, wasm_file) !=
1) {
OFStream os(stderr);
os << "Error while dumping wasm file" << std::endl;
}
fclose(wasm_file);
}
}
void StartDecoding(Isolate* isolate) {
CHECK_NULL(module_);
SetCounters(isolate->counters());
module_.reset(new WasmModule(base::make_unique<Zone>(
isolate->wasm_engine()->allocator(), "signatures")));
module_->initial_pages = 0;
module_->maximum_pages = 0;
module_->mem_export = false;
module_->origin = origin_;
}
void DecodeModuleHeader(Vector<const uint8_t> bytes, uint8_t offset) {
if (failed()) return;
Reset(bytes, offset);
const byte* pos = pc_;
uint32_t magic_word = consume_u32("wasm magic");
#define BYTES(x) (x & 0xFF), (x >> 8) & 0xFF, (x >> 16) & 0xFF, (x >> 24) & 0xFF
if (magic_word != kWasmMagic) {
errorf(pos,
"expected magic word %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmMagic), BYTES(magic_word));
}
pos = pc_;
{
uint32_t magic_version = consume_u32("wasm version");
if (magic_version != kWasmVersion) {
errorf(pos,
"expected version %02x %02x %02x %02x, "
"found %02x %02x %02x %02x",
BYTES(kWasmVersion), BYTES(magic_version));
}
}
#undef BYTES
}
void DecodeSection(SectionCode section_code, Vector<const uint8_t> bytes,
uint32_t offset, bool verify_functions = true) {
if (failed()) return;
Reset(bytes, offset);
TRACE("Section: %s\n", SectionName(section_code));
TRACE("Decode Section %p - %p\n", static_cast<const void*>(bytes.begin()),
static_cast<const void*>(bytes.end()));
// Check if the section is out-of-order.
if (section_code < next_section_) {
errorf(pc(), "unexpected section: %s", SectionName(section_code));
return;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kExceptionSectionCode:
// Note: kExceptionSectionCode > kCodeSectionCode, but must appear
// before the code section. Hence, treat it as a special case.
if (++number_of_exception_sections > 1) {
errorf(pc(), "Multiple exception sections not allowed");
return;
} else if (next_section_ >= kCodeSectionCode) {
errorf(pc(), "Exception section must appear before the code section");
return;
}
break;
default:
next_section_ = section_code;
++next_section_;
break;
}
switch (section_code) {
case kUnknownSectionCode:
break;
case kTypeSectionCode:
DecodeTypeSection();
break;
case kImportSectionCode:
DecodeImportSection();
break;
case kFunctionSectionCode:
DecodeFunctionSection();
break;
case kTableSectionCode:
DecodeTableSection();
break;
case kMemorySectionCode:
DecodeMemorySection();
break;
case kGlobalSectionCode:
DecodeGlobalSection();
break;
case kExportSectionCode:
DecodeExportSection();
break;
case kStartSectionCode:
DecodeStartSection();
break;
case kCodeSectionCode:
DecodeCodeSection(verify_functions);
break;
case kElementSectionCode:
DecodeElementSection();
break;
case kDataSectionCode:
DecodeDataSection();
break;
case kNameSectionCode:
DecodeNameSection();
break;
case kExceptionSectionCode:
if (FLAG_experimental_wasm_eh) {
DecodeExceptionSection();
} else {
errorf(pc(), "unexpected section: %s", SectionName(section_code));
}
break;
default:
errorf(pc(), "unexpected section: %s", SectionName(section_code));
return;
}
if (pc() != bytes.end()) {
const char* msg = pc() < bytes.end() ? "shorter" : "longer";
errorf(pc(),
"section was %s than expected size "
"(%zu bytes expected, %zu decoded)",
msg, bytes.size(), static_cast<size_t>(pc() - bytes.begin()));
}
}
void DecodeTypeSection() {
uint32_t signatures_count = consume_count("types count", kV8MaxWasmTypes);
module_->signatures.reserve(signatures_count);
for (uint32_t i = 0; ok() && i < signatures_count; ++i) {
TRACE("DecodeSignature[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
FunctionSig* s = consume_sig(module_->signature_zone.get());
module_->signatures.push_back(s);
uint32_t id = s ? module_->signature_map.FindOrInsert(*s) : 0;
module_->signature_ids.push_back(id);
}
module_->signature_map.Freeze();
}
void DecodeImportSection() {
uint32_t import_table_count =
consume_count("imports count", kV8MaxWasmImports);
module_->import_table.reserve(import_table_count);
for (uint32_t i = 0; ok() && i < import_table_count; ++i) {
TRACE("DecodeImportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->import_table.push_back({
{0, 0}, // module_name
{0, 0}, // field_name
kExternalFunction, // kind
0 // index
});
WasmImport* import = &module_->import_table.back();
const byte* pos = pc_;
import->module_name = consume_string(true, "module name");
import->field_name = consume_string(true, "field name");
import->kind =
static_cast<ImportExportKindCode>(consume_u8("import kind"));
switch (import->kind) {
case kExternalFunction: {
// ===== Imported function =======================================
import->index = static_cast<uint32_t>(module_->functions.size());
module_->num_imported_functions++;
module_->functions.push_back({nullptr, // sig
import->index, // func_index
0, // sig_index
{0, 0}, // code
true, // imported
false}); // exported
WasmFunction* function = &module_->functions.back();
function->sig_index =
consume_sig_index(module_.get(), &function->sig);
break;
}
case kExternalTable: {
// ===== Imported table ==========================================
if (!AddTable(module_.get())) break;
import->index = static_cast<uint32_t>(module_->tables.size());
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
table->imported = true;
ValueType type = consume_reference_type();
if (!FLAG_experimental_wasm_anyref) {
if (type != kWasmAnyFunc) {
error(pc_ - 1, "invalid table type");
break;
}
}
table->type = type;
uint8_t flags = validate_table_flags("element count");
consume_resizable_limits(
"element count", "elements", FLAG_wasm_max_table_size,
&table->initial_size, &table->has_maximum_size,
FLAG_wasm_max_table_size, &table->maximum_size, flags);
break;
}
case kExternalMemory: {
// ===== Imported memory =========================================
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory);
consume_resizable_limits(
"memory", "pages", FLAG_wasm_max_mem_pages,
&module_->initial_pages, &module_->has_maximum_pages,
kSpecMaxWasmMemoryPages, &module_->maximum_pages, flags);
break;
}
case kExternalGlobal: {
// ===== Imported global =========================================
import->index = static_cast<uint32_t>(module_->globals.size());
module_->globals.push_back(
{kWasmStmt, false, WasmInitExpr(), {0}, true, false});
WasmGlobal* global = &module_->globals.back();
global->type = consume_value_type();
global->mutability = consume_mutability();
if (global->mutability) {
if (FLAG_experimental_wasm_mut_global) {
module_->num_imported_mutable_globals++;
} else {
error("mutable globals cannot be imported");
}
}
break;
}
default:
errorf(pos, "unknown import kind 0x%02x", import->kind);
break;
}
}
}
void DecodeFunctionSection() {
uint32_t functions_count =
consume_count("functions count", kV8MaxWasmFunctions);
auto counter =
SELECT_WASM_COUNTER(GetCounters(), origin_, wasm_functions_per, module);
counter->AddSample(static_cast<int>(functions_count));
DCHECK_EQ(module_->functions.size(), module_->num_imported_functions);
uint32_t total_function_count =
module_->num_imported_functions + functions_count;
module_->functions.reserve(total_function_count);
module_->num_declared_functions = functions_count;
for (uint32_t i = 0; i < functions_count; ++i) {
uint32_t func_index = static_cast<uint32_t>(module_->functions.size());
module_->functions.push_back({nullptr, // sig
func_index, // func_index
0, // sig_index
{0, 0}, // code
false, // imported
false}); // exported
WasmFunction* function = &module_->functions.back();
function->sig_index = consume_sig_index(module_.get(), &function->sig);
if (!ok()) return;
}
DCHECK_EQ(module_->functions.size(), total_function_count);
}
void DecodeTableSection() {
// TODO(ahaas): Set the correct limit to {kV8MaxWasmTables} once the
// implementation of AnyRef landed.
uint32_t max_count = FLAG_experimental_wasm_anyref ? 10 : kV8MaxWasmTables;
uint32_t table_count = consume_count("table count", max_count);
for (uint32_t i = 0; ok() && i < table_count; i++) {
if (!AddTable(module_.get())) break;
module_->tables.emplace_back();
WasmTable* table = &module_->tables.back();
table->type = consume_reference_type();
uint8_t flags = validate_table_flags("table elements");
consume_resizable_limits(
"table elements", "elements", FLAG_wasm_max_table_size,
&table->initial_size, &table->has_maximum_size,
FLAG_wasm_max_table_size, &table->maximum_size, flags);
}
}
void DecodeMemorySection() {
uint32_t memory_count = consume_count("memory count", kV8MaxWasmMemories);
for (uint32_t i = 0; ok() && i < memory_count; i++) {
if (!AddMemory(module_.get())) break;
uint8_t flags = validate_memory_flags(&module_->has_shared_memory);
consume_resizable_limits(
"memory", "pages", FLAG_wasm_max_mem_pages, &module_->initial_pages,
&module_->has_maximum_pages, kSpecMaxWasmMemoryPages,
&module_->maximum_pages, flags);
}
}
void DecodeGlobalSection() {
uint32_t globals_count = consume_count("globals count", kV8MaxWasmGlobals);
uint32_t imported_globals = static_cast<uint32_t>(module_->globals.size());
module_->globals.reserve(imported_globals + globals_count);
for (uint32_t i = 0; ok() && i < globals_count; ++i) {
TRACE("DecodeGlobal[%d] module+%d\n", i, static_cast<int>(pc_ - start_));
// Add an uninitialized global and pass a pointer to it.
module_->globals.push_back(
{kWasmStmt, false, WasmInitExpr(), {0}, false, false});
WasmGlobal* global = &module_->globals.back();
DecodeGlobalInModule(module_.get(), i + imported_globals, global);
}
if (ok()) CalculateGlobalOffsets(module_.get());
}
void DecodeExportSection() {
uint32_t export_table_count =
consume_count("exports count", kV8MaxWasmExports);
module_->export_table.reserve(export_table_count);
for (uint32_t i = 0; ok() && i < export_table_count; ++i) {
TRACE("DecodeExportTable[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->export_table.push_back({
{0, 0}, // name
kExternalFunction, // kind
0 // index
});
WasmExport* exp = &module_->export_table.back();
exp->name = consume_string(true, "field name");
const byte* pos = pc();
exp->kind = static_cast<ImportExportKindCode>(consume_u8("export kind"));
switch (exp->kind) {
case kExternalFunction: {
WasmFunction* func = nullptr;
exp->index = consume_func_index(module_.get(), &func);
module_->num_exported_functions++;
if (func) func->exported = true;
break;
}
case kExternalTable: {
WasmTable* table = nullptr;
exp->index = consume_table_index(module_.get(), &table);
if (table) table->exported = true;
break;
}
case kExternalMemory: {
uint32_t index = consume_u32v("memory index");
// TODO(titzer): This should become more regular
// once we support multiple memories.
if (!module_->has_memory || index != 0) {
error("invalid memory index != 0");
}
module_->mem_export = true;
break;
}
case kExternalGlobal: {
WasmGlobal* global = nullptr;
exp->index = consume_global_index(module_.get(), &global);
if (global) {
if (!FLAG_experimental_wasm_mut_global && global->mutability) {
error("mutable globals cannot be exported");
}
global->exported = true;
}
break;
}
default:
errorf(pos, "invalid export kind 0x%02x", exp->kind);
break;
}
}
// Check for duplicate exports (except for asm.js).
if (ok() && origin_ != kAsmJsOrigin && module_->export_table.size() > 1) {
std::vector<WasmExport> sorted_exports(module_->export_table);
auto cmp_less = [this](const WasmExport& a, const WasmExport& b) {
// Return true if a < b.
if (a.name.length() != b.name.length()) {
return a.name.length() < b.name.length();
}
const byte* left = start() + GetBufferRelativeOffset(a.name.offset());
const byte* right = start() + GetBufferRelativeOffset(b.name.offset());
return memcmp(left, right, a.name.length()) < 0;
};
std::stable_sort(sorted_exports.begin(), sorted_exports.end(), cmp_less);
auto it = sorted_exports.begin();
WasmExport* last = &*it++;
for (auto end = sorted_exports.end(); it != end; last = &*it++) {
DCHECK(!cmp_less(*it, *last)); // Vector must be sorted.
if (!cmp_less(*last, *it)) {
const byte* pc = start() + GetBufferRelativeOffset(it->name.offset());
TruncatedUserString<> name(pc, it->name.length());
errorf(pc, "Duplicate export name '%.*s' for %s %d and %s %d",
name.length(), name.start(), ExternalKindName(last->kind),
last->index, ExternalKindName(it->kind), it->index);
break;
}
}
}
}
void DecodeStartSection() {
WasmFunction* func;
const byte* pos = pc_;
module_->start_function_index = consume_func_index(module_.get(), &func);
if (func &&
(func->sig->parameter_count() > 0 || func->sig->return_count() > 0)) {
error(pos, "invalid start function: non-zero parameter or return count");
}
}
void DecodeElementSection() {
uint32_t element_count =
consume_count("element count", FLAG_wasm_max_table_size);
if (element_count > 0 && module_->tables.size() == 0) {
error(pc_, "The element section requires a table");
}
for (uint32_t i = 0; ok() && i < element_count; ++i) {
const byte* pos = pc();
uint32_t table_index = consume_u32v("table index");
if (!FLAG_experimental_wasm_anyref && table_index != 0) {
errorf(pos, "illegal table index %u != 0", table_index);
}
if (table_index >= module_->tables.size()) {
errorf(pos, "out of bounds table index %u", table_index);
break;
}
if (module_->tables[table_index].type != kWasmAnyFunc) {
errorf(pos, "Invalid element segment. Table %u is not of type AnyFunc",
table_index);
break;
}
WasmInitExpr offset = consume_init_expr(module_.get(), kWasmI32);
uint32_t num_elem =
consume_count("number of elements", kV8MaxWasmTableEntries);
module_->table_inits.emplace_back(table_index, offset);
WasmTableInit* init = &module_->table_inits.back();
for (uint32_t j = 0; j < num_elem; j++) {
WasmFunction* func = nullptr;
uint32_t index = consume_func_index(module_.get(), &func);
DCHECK_IMPLIES(ok(), func != nullptr);
if (!ok()) break;
DCHECK_EQ(index, func->func_index);
init->entries.push_back(index);
}
}
}
void DecodeCodeSection(bool verify_functions) {
uint32_t pos = pc_offset();
uint32_t functions_count = consume_u32v("functions count");
CheckFunctionsCount(functions_count, pos);
for (uint32_t i = 0; ok() && i < functions_count; ++i) {
const byte* pos = pc();
uint32_t size = consume_u32v("body size");
if (size > kV8MaxWasmFunctionSize) {
errorf(pos, "size %u > maximum function size %zu", size,
kV8MaxWasmFunctionSize);
return;
}
uint32_t offset = pc_offset();
consume_bytes(size, "function body");
if (failed()) break;
DecodeFunctionBody(i, size, offset, verify_functions);
}
}
bool CheckFunctionsCount(uint32_t functions_count, uint32_t offset) {
if (functions_count != module_->num_declared_functions) {
Reset(nullptr, nullptr, offset);
errorf(nullptr, "function body count %u mismatch (%u expected)",
functions_count, module_->num_declared_functions);
return false;
}
return true;
}
void DecodeFunctionBody(uint32_t index, uint32_t length, uint32_t offset,
bool verify_functions) {
WasmFunction* function =
&module_->functions[index + module_->num_imported_functions];
function->code = {offset, length};
if (verify_functions) {
ModuleWireBytes bytes(start_, end_);
VerifyFunctionBody(module_->signature_zone->allocator(),
index + module_->num_imported_functions, bytes,
module_.get(), function);
}
}
void DecodeDataSection() {
uint32_t data_segments_count =
consume_count("data segments count", kV8MaxWasmDataSegments);
module_->data_segments.reserve(data_segments_count);
for (uint32_t i = 0; ok() && i < data_segments_count; ++i) {
if (!module_->has_memory) {
error("cannot load data without memory");
break;
}
TRACE("DecodeDataSegment[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->data_segments.push_back({
WasmInitExpr(), // dest_addr
{0, 0} // source
});
WasmDataSegment* segment = &module_->data_segments.back();
DecodeDataSegmentInModule(module_.get(), segment);
}
}
void DecodeNameSection() {
// TODO(titzer): find a way to report name errors as warnings.
// Use an inner decoder so that errors don't fail the outer decoder.
Decoder inner(start_, pc_, end_, buffer_offset_);
// Decode all name subsections.
// Be lenient with their order.
while (inner.ok() && inner.more()) {
uint8_t name_type = inner.consume_u8("name type");
if (name_type & 0x80) inner.error("name type if not varuint7");
uint32_t name_payload_len = inner.consume_u32v("name payload length");
if (!inner.checkAvailable(name_payload_len)) break;
// Decode module name, ignore the rest.
// Function and local names will be decoded when needed.
if (name_type == NameSectionKindCode::kModule) {
WireBytesRef name = wasm::consume_string(inner, false, "module name");
if (inner.ok() && validate_utf8(&inner, name)) module_->name = name;
} else {
inner.consume_bytes(name_payload_len, "name subsection payload");
}
}
// Skip the whole names section in the outer decoder.
consume_bytes(static_cast<uint32_t>(end_ - start_), nullptr);
}
void DecodeExceptionSection() {
uint32_t exception_count =
consume_count("exception count", kV8MaxWasmExceptions);
for (uint32_t i = 0; ok() && i < exception_count; ++i) {
TRACE("DecodeExceptionSignature[%d] module+%d\n", i,
static_cast<int>(pc_ - start_));
module_->exceptions.emplace_back(
consume_exception_sig(module_->signature_zone.get()));
}
}
ModuleResult FinishDecoding(bool verify_functions = true) {
if (ok()) {
CalculateGlobalOffsets(module_.get());
}
ModuleResult result = toResult(std::move(module_));
if (verify_functions && result.ok()) {
// Copy error code and location.
result.MoveErrorFrom(intermediate_result_);
}
return result;
}
// Decodes an entire module.
ModuleResult DecodeModule(Isolate* isolate, bool verify_functions = true) {
StartDecoding(isolate);
uint32_t offset = 0;
Vector<const byte> orig_bytes(start(), end() - start());
DecodeModuleHeader(Vector<const uint8_t>(start(), end() - start()), offset);
if (failed()) {
return FinishDecoding(verify_functions);
}
// Size of the module header.
offset += 8;
Decoder decoder(start_ + offset, end_, offset);
WasmSectionIterator section_iter(decoder);
while (ok() && section_iter.more()) {
// Shift the offset by the section header length
offset += section_iter.payload_start() - section_iter.section_start();
if (section_iter.section_code() != SectionCode::kUnknownSectionCode) {
DecodeSection(section_iter.section_code(), section_iter.payload(),
offset, verify_functions);
}
// Shift the offset by the remaining section payload
offset += section_iter.payload_length();
section_iter.advance(true);
}
if (FLAG_dump_wasm_module) DumpModule(orig_bytes);
if (decoder.failed()) {
return decoder.toResult<std::unique_ptr<WasmModule>>(nullptr);
}
return FinishDecoding(verify_functions);
}
// Decodes a single anonymous function starting at {start_}.
FunctionResult DecodeSingleFunction(Zone* zone,
const ModuleWireBytes& wire_bytes,
const WasmModule* module,
std::unique_ptr<WasmFunction> function) {
pc_ = start_;
function->sig = consume_sig(zone);
function->code = {off(pc_), static_cast<uint32_t>(end_ - pc_)};
if (ok())
VerifyFunctionBody(zone->allocator(), 0, wire_bytes, module,
function.get());
FunctionResult result(std::move(function));
// Copy error code and location.
result.MoveErrorFrom(intermediate_result_);
return result;
}
// Decodes a single function signature at {start}.
FunctionSig* DecodeFunctionSignature(Zone* zone, const byte* start) {
pc_ = start;
FunctionSig* result = consume_sig(zone);
return ok() ? result : nullptr;
}
WasmInitExpr DecodeInitExpr(const byte* start) {
pc_ = start;
return consume_init_expr(nullptr, kWasmStmt);
}
const std::shared_ptr<WasmModule>& shared_module() const { return module_; }
Counters* GetCounters() const {
DCHECK_NOT_NULL(counters_);
return counters_;
}
void SetCounters(Counters* counters) {
DCHECK_NULL(counters_);
counters_ = counters;
}
private:
std::shared_ptr<WasmModule> module_;
Counters* counters_ = nullptr;
// The type section is the first section in a module.
uint8_t next_section_ = kFirstSectionInModule;
uint32_t number_of_exception_sections = 0;
// We store next_section_ as uint8_t instead of SectionCode so that we can
// increment it. This static_assert should make sure that SectionCode does not
// get bigger than uint8_t accidentially.
static_assert(sizeof(ModuleDecoderImpl::next_section_) == sizeof(SectionCode),
"type mismatch");
Result<bool> intermediate_result_;
ModuleOrigin origin_;
uint32_t off(const byte* ptr) {
return static_cast<uint32_t>(ptr - start_) + buffer_offset_;
}
bool AddTable(WasmModule* module) {
if (FLAG_experimental_wasm_anyref) return true;
if (module->tables.size() > 0) {
error("At most one table is supported");
return false;
} else {
return true;
}
}
bool AddMemory(WasmModule* module) {
if (module->has_memory) {
error("At most one memory is supported");
return false;
} else {
module->has_memory = true;
return true;
}
}
// Decodes a single global entry inside a module starting at {pc_}.
void DecodeGlobalInModule(WasmModule* module, uint32_t index,
WasmGlobal* global) {
global->type = consume_value_type();
global->mutability = consume_mutability();
const byte* pos = pc();
global->init = consume_init_expr(module, kWasmStmt);
if (global->init.kind == WasmInitExpr::kGlobalIndex) {
uint32_t other_index = global->init.val.global_index;
if (other_index >= index) {
errorf(pos,
"invalid global index in init expression, "
"index %u, other_index %u",
index, other_index);
} else if (module->globals[other_index].type != global->type) {
errorf(pos,
"type mismatch in global initialization "
"(from global #%u), expected %s, got %s",
other_index, ValueTypes::TypeName(global->type),
ValueTypes::TypeName(module->globals[other_index].type));
}
} else {
if (global->type != TypeOf(module, global->init)) {
errorf(pos, "type error in global initialization, expected %s, got %s",
ValueTypes::TypeName(global->type),
ValueTypes::TypeName(TypeOf(module, global->init)));
}
}
}
// Decodes a single data segment entry inside a module starting at {pc_}.
void DecodeDataSegmentInModule(WasmModule* module, WasmDataSegment* segment) {
expect_u8("linear memory index", 0);
segment->dest_addr = consume_init_expr(module, kWasmI32);
uint32_t source_length = consume_u32v("source size");
uint32_t source_offset = pc_offset();
consume_bytes(source_length, "segment data");
if (failed()) return;
segment->source = {source_offset, source_length};
}
// Calculate individual global offsets and total size of globals table.
void CalculateGlobalOffsets(WasmModule* module) {
uint32_t offset = 0;
uint32_t num_imported_mutable_globals = 0;
if (module->globals.size() == 0) {
module->globals_buffer_size = 0;
return;
}
for (WasmGlobal& global : module->globals) {
byte size = ValueTypes::MemSize(ValueTypes::MachineTypeFor(global.type));
if (global.mutability && global.imported) {
DCHECK(FLAG_experimental_wasm_mut_global);
global.index = num_imported_mutable_globals++;
} else {
offset = (offset + size - 1) & ~(size - 1); // align
global.offset = offset;
offset += size;
}
}
module->globals_buffer_size = offset;
}
// Verifies the body (code) of a given function.
void VerifyFunctionBody(AccountingAllocator* allocator, uint32_t func_num,
const ModuleWireBytes& wire_bytes,
const WasmModule* module, WasmFunction* function) {
WasmFunctionName func_name(function,
wire_bytes.GetNameOrNull(function, module));
if (FLAG_trace_wasm_decoder || FLAG_trace_wasm_decode_time) {
StdoutStream os;
os << "Verifying wasm function " << func_name << std::endl;
}
FunctionBody body = {
function->sig, function->code.offset(),
start_ + GetBufferRelativeOffset(function->code.offset()),
start_ + GetBufferRelativeOffset(function->code.end_offset())};
DecodeResult result = VerifyWasmCodeWithStats(allocator, module, body,
origin_, GetCounters());
if (result.failed()) {
// Wrap the error message from the function decoder.
std::ostringstream wrapped;
wrapped << "in function " << func_name << ": " << result.error_msg();
result.error(result.error_offset(), wrapped.str());
// Set error code and location, if this is the first error.
if (intermediate_result_.ok()) {
intermediate_result_.MoveErrorFrom(result);
}
}
}
WireBytesRef consume_string(bool validate_utf8, const char* name) {
return wasm::consume_string(*this, validate_utf8, name);
}
uint32_t consume_sig_index(WasmModule* module, FunctionSig** sig) {
const byte* pos = pc_;
uint32_t sig_index = consume_u32v("signature index");
if (sig_index >= module->signatures.size()) {
errorf(pos, "signature index %u out of bounds (%d signatures)", sig_index,
static_cast<int>(module->signatures.size()));
*sig = nullptr;
return 0;
}
*sig = module->signatures[sig_index];
return sig_index;
}
uint32_t consume_count(const char* name, size_t maximum) {
const byte* p = pc_;
uint32_t count = consume_u32v(name);
if (count > maximum) {
errorf(p, "%s of %u exceeds internal limit of %zu", name, count, maximum);
return static_cast<uint32_t>(maximum);
}
return count;
}
uint32_t consume_func_index(WasmModule* module, WasmFunction** func) {
return consume_index("function index", module->functions, func);
}
uint32_t consume_global_index(WasmModule* module, WasmGlobal** global) {
return consume_index("global index", module->globals, global);
}
uint32_t consume_table_index(WasmModule* module, WasmTable** table) {
return consume_index("table index", module->tables, table);
}
template <typename T>
uint32_t consume_index(const char* name, std::vector<T>& vector, T** ptr) {
const byte* pos = pc_;
uint32_t index = consume_u32v(name);
if (index >= vector.size()) {
errorf(pos, "%s %u out of bounds (%d entr%s)", name, index,
static_cast<int>(vector.size()), vector.size() == 1 ? "y" : "ies");
*ptr = nullptr;
return 0;
}
*ptr = &vector[index];
return index;
}
uint8_t validate_table_flags(const char* name) {
uint8_t flags = consume_u8("resizable limits flags");
const byte* pos = pc();
if (flags & 0xFE) {
errorf(pos - 1, "invalid %s limits flags", name);
}
return flags;
}
uint8_t validate_memory_flags(bool* has_shared_memory) {
uint8_t flags = consume_u8("resizable limits flags");
const byte* pos = pc();
*has_shared_memory = false;
if (FLAG_experimental_wasm_threads) {
if (flags & 0xFC) {
errorf(pos - 1, "invalid memory limits flags");
} else if (flags == 3) {
DCHECK_NOT_NULL(has_shared_memory);
*has_shared_memory = true;
} else if (flags == 2) {
errorf(pos - 1,
"memory limits flags should have maximum defined if shared is "
"true");
}
} else {
if (flags & 0xFE) {
errorf(pos - 1, "invalid memory limits flags");
}
}
return flags;
}
void consume_resizable_limits(const char* name, const char* units,
uint32_t max_initial, uint32_t* initial,
bool* has_max, uint32_t max_maximum,
uint32_t* maximum, uint8_t flags) {
const byte* pos = pc();
*initial = consume_u32v("initial size");
*has_max = false;
if (*initial > max_initial) {
errorf(pos,
"initial %s size (%u %s) is larger than implementation limit (%u)",
name, *initial, units, max_initial);
}
if (flags & 1) {
*has_max = true;
pos = pc();
*maximum = consume_u32v("maximum size");
if (*maximum > max_maximum) {
errorf(
pos,
"maximum %s size (%u %s) is larger than implementation limit (%u)",
name, *maximum, units, max_maximum);
}
if (*maximum < *initial) {
errorf(pos, "maximum %s size (%u %s) is less than initial (%u %s)",
name, *maximum, units, *initial, units);
}
} else {
*has_max = false;
*maximum = max_initial;
}
}
bool expect_u8(const char* name, uint8_t expected) {
const byte* pos = pc();
uint8_t value = consume_u8(name);
if (value != expected) {
errorf(pos, "expected %s 0x%02x, got 0x%02x", name, expected, value);
return false;
}
return true;
}
WasmInitExpr consume_init_expr(WasmModule* module, ValueType expected) {
const byte* pos = pc();
uint8_t opcode = consume_u8("opcode");
WasmInitExpr expr;
unsigned len = 0;
switch (opcode) {
case kExprGetGlobal: {
GlobalIndexImmediate<Decoder::kValidate> imm(this, pc() - 1);
if (module->globals.size() <= imm.index) {
error("global index is out of bounds");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
break;
}
WasmGlobal* global = &module->globals[imm.index];
if (global->mutability || !global->imported) {
error(
"only immutable imported globals can be used in initializer "
"expressions");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
break;
}
expr.kind = WasmInitExpr::kGlobalIndex;
expr.val.global_index = imm.index;
len = imm.length;
break;
}
case kExprI32Const: {
ImmI32Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kI32Const;
expr.val.i32_const = imm.value;
len = imm.length;
break;
}
case kExprF32Const: {
ImmF32Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kF32Const;
expr.val.f32_const = imm.value;
len = imm.length;
break;
}
case kExprI64Const: {
ImmI64Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kI64Const;
expr.val.i64_const = imm.value;
len = imm.length;
break;
}
case kExprF64Const: {
ImmF64Immediate<Decoder::kValidate> imm(this, pc() - 1);
expr.kind = WasmInitExpr::kF64Const;
expr.val.f64_const = imm.value;
len = imm.length;
break;
}
case kExprRefNull: {
if (FLAG_experimental_wasm_anyref) {
expr.kind = WasmInitExpr::kAnyRefConst;
len = 0;
break;
}
V8_FALLTHROUGH;
}
default: {
error("invalid opcode in initialization expression");
expr.kind = WasmInitExpr::kNone;
expr.val.i32_const = 0;
}
}
consume_bytes(len, "init code");
if (!expect_u8("end opcode", kExprEnd)) {
expr.kind = WasmInitExpr::kNone;
}
if (expected != kWasmStmt && TypeOf(module, expr) != kWasmI32) {
errorf(pos, "type error in init expression, expected %s, got %s",
ValueTypes::TypeName(expected),
ValueTypes::TypeName(TypeOf(module, expr)));
}
return expr;
}
// Read a mutability flag
bool consume_mutability() {
byte val = consume_u8("mutability");
if (val > 1) error(pc_ - 1, "invalid mutability");
return val != 0;
}
// Reads a single 8-bit integer, interpreting it as a local type.
ValueType consume_value_type() {
byte val = consume_u8("value type");
ValueTypeCode t = static_cast<ValueTypeCode>(val);
switch (t) {
case kLocalI32:
return kWasmI32;
case kLocalI64:
return kWasmI64;
case kLocalF32:
return kWasmF32;
case kLocalF64:
return kWasmF64;
default:
if (origin_ == kWasmOrigin) {
switch (t) {
case kLocalS128:
if (FLAG_experimental_wasm_simd) return kWasmS128;
break;
case kLocalAnyFunc:
if (FLAG_experimental_wasm_anyref) return kWasmAnyFunc;
break;
case kLocalAnyRef:
if (FLAG_experimental_wasm_anyref) return kWasmAnyRef;
break;
default:
break;
}
}
error(pc_ - 1, "invalid local type");
return kWasmStmt;
}
}
// Reads a single 8-bit integer, interpreting it as a reference type.
ValueType consume_reference_type() {
byte val = consume_u8("reference type");
ValueTypeCode t = static_cast<ValueTypeCode>(val);
switch (t) {
case kLocalAnyFunc:
return kWasmAnyFunc;
case kLocalAnyRef:
if (!FLAG_experimental_wasm_anyref) {
error(pc_ - 1,
"Invalid type. Set --experimental-wasm-anyref to use 'AnyRef'");
}
return kWasmAnyRef;
default:
break;
}
error(pc_ - 1, "invalid reference type");
return kWasmStmt;
}
FunctionSig* consume_sig(Zone* zone) {
constexpr bool has_return_values = true;
return consume_sig_internal(zone, has_return_values);
}
WasmExceptionSig* consume_exception_sig(Zone* zone) {
constexpr bool has_return_values = true;
return consume_sig_internal(zone, !has_return_values);
}
private:
FunctionSig* consume_sig_internal(Zone* zone, bool has_return_values) {
if (has_return_values && !expect_u8("type form", kWasmFunctionTypeCode))
return nullptr;
// parse parameter types
uint32_t param_count =
consume_count("param count", kV8MaxWasmFunctionParams);
if (failed()) return nullptr;
std::vector<ValueType> params;
for (uint32_t i = 0; ok() && i < param_count; ++i) {
ValueType param = consume_value_type();
params.push_back(param);
}
std::vector<ValueType> returns;
uint32_t return_count = 0;
if (has_return_values) {
// parse return types
const size_t max_return_count = FLAG_experimental_wasm_mv
? kV8MaxWasmFunctionMultiReturns
: kV8MaxWasmFunctionReturns;
return_count = consume_count("return count", max_return_count);
if (failed()) return nullptr;
for (uint32_t i = 0; ok() && i < return_count; ++i) {
ValueType ret = consume_value_type();
returns.push_back(ret);
}
}
if (failed()) return nullptr;
// FunctionSig stores the return types first.
ValueType* buffer = zone->NewArray<ValueType>(param_count + return_count);
uint32_t b = 0;
for (uint32_t i = 0; i < return_count; ++i) buffer[b++] = returns[i];
for (uint32_t i = 0; i < param_count; ++i) buffer[b++] = params[i];
return new (zone) FunctionSig(return_count, param_count, buffer);
}
};
ModuleResult DecodeWasmModule(Isolate* isolate, const byte* module_start,
const byte* module_end, bool verify_functions,
ModuleOrigin origin, Counters* counters) {
auto counter =
SELECT_WASM_COUNTER(counters, origin, wasm_decode, module_time);
TimedHistogramScope wasm_decode_module_time_scope(counter);
size_t size = module_end - module_start;
if (module_start > module_end) return ModuleResult::Error("start > end");
if (size >= kV8MaxWasmModuleSize)
return ModuleResult::Error("size > maximum module size: %zu", size);
// TODO(bradnelson): Improve histogram handling of size_t.
auto size_counter =
SELECT_WASM_COUNTER(counters, origin, wasm, module_size_bytes);
size_counter->AddSample(static_cast<int>(size));
// Signatures are stored in zone memory, which have the same lifetime
// as the {module}.
ModuleDecoderImpl decoder(module_start, module_end, origin);
ModuleResult result = decoder.DecodeModule(isolate, verify_functions);
// TODO(bradnelson): Improve histogram handling of size_t.
// TODO(titzer): this isn't accurate, since it doesn't count the data
// allocated on the C++ heap.
// https://bugs.chromium.org/p/chromium/issues/detail?id=657320
if (result.ok()) {
auto peak_counter = SELECT_WASM_COUNTER(counters, origin, wasm_decode,
module_peak_memory_bytes);
peak_counter->AddSample(
static_cast<int>(result.val->signature_zone->allocation_size()));
}
return result;
}
ModuleDecoder::ModuleDecoder() = default;
ModuleDecoder::~ModuleDecoder() = default;
const std::shared_ptr<WasmModule>& ModuleDecoder::shared_module() const {
return impl_->shared_module();
}
void ModuleDecoder::StartDecoding(Isolate* isolate, ModuleOrigin origin) {
DCHECK_NULL(impl_);
impl_.reset(new ModuleDecoderImpl(origin));
impl_->StartDecoding(isolate);
}
void ModuleDecoder::DecodeModuleHeader(Vector<const uint8_t> bytes,
uint32_t offset) {
impl_->DecodeModuleHeader(bytes, offset);
}
void ModuleDecoder::DecodeSection(SectionCode section_code,
Vector<const uint8_t> bytes, uint32_t offset,
bool verify_functions) {
impl_->DecodeSection(section_code, bytes, offset, verify_functions);
}
void ModuleDecoder::DecodeFunctionBody(uint32_t index, uint32_t length,
uint32_t offset, bool verify_functions) {
impl_->DecodeFunctionBody(index, length, offset, verify_functions);
}
bool ModuleDecoder::CheckFunctionsCount(uint32_t functions_count,
uint32_t offset) {
return impl_->CheckFunctionsCount(functions_count, offset);
}
ModuleResult ModuleDecoder::FinishDecoding(bool verify_functions) {
return impl_->FinishDecoding(verify_functions);
}
SectionCode ModuleDecoder::IdentifyUnknownSection(Decoder& decoder,
const byte* end) {
WireBytesRef string = wasm::consume_string(decoder, true, "section name");
if (decoder.failed() || decoder.pc() > end) {
return kUnknownSectionCode;
}
const byte* section_name_start =
decoder.start() + decoder.GetBufferRelativeOffset(string.offset());
TRACE(" +%d section name : \"%.*s\"\n",
static_cast<int>(section_name_start - decoder.start()),
string.length() < 20 ? string.length() : 20, section_name_start);
if (string.length() == num_chars(kNameString) &&
strncmp(reinterpret_cast<const char*>(section_name_start), kNameString,
num_chars(kNameString)) == 0) {
return kNameSectionCode;
}
return kUnknownSectionCode;
}
bool ModuleDecoder::ok() { return impl_->ok(); }
ModuleResult SyncDecodeWasmModule(Isolate* isolate, const byte* module_start,
const byte* module_end, bool verify_functions,
ModuleOrigin origin) {
return DecodeWasmModule(isolate, module_start, module_end, verify_functions,
origin, isolate->counters());
}
ModuleResult AsyncDecodeWasmModule(
Isolate* isolate, const byte* module_start, const byte* module_end,
bool verify_functions, ModuleOrigin origin,
const std::shared_ptr<Counters> async_counters) {
return DecodeWasmModule(isolate, module_start, module_end, verify_functions,
origin, async_counters.get());
}
FunctionSig* DecodeWasmSignatureForTesting(Zone* zone, const byte* start,
const byte* end) {
ModuleDecoderImpl decoder(start, end, kWasmOrigin);
return decoder.DecodeFunctionSignature(zone, start);
}
WasmInitExpr DecodeWasmInitExprForTesting(const byte* start, const byte* end) {
AccountingAllocator allocator;
ModuleDecoderImpl decoder(start, end, kWasmOrigin);
return decoder.DecodeInitExpr(start);
}
FunctionResult DecodeWasmFunctionForTesting(
Zone* zone, const ModuleWireBytes& wire_bytes, const WasmModule* module,
const byte* function_start, const byte* function_end, Counters* counters) {
size_t size = function_end - function_start;
if (function_start > function_end)
return FunctionResult::Error("start > end");
auto size_histogram = SELECT_WASM_COUNTER(counters, module->origin, wasm,
function_size_bytes);
// TODO(bradnelson): Improve histogram handling of ptrdiff_t.
size_histogram->AddSample(static_cast<int>(size));
if (size > kV8MaxWasmFunctionSize)
return FunctionResult::Error("size > maximum function size: %zu", size);
ModuleDecoderImpl decoder(function_start, function_end, kWasmOrigin);
decoder.SetCounters(counters);
return decoder.DecodeSingleFunction(zone, wire_bytes, module,
base::make_unique<WasmFunction>());
}
AsmJsOffsetsResult DecodeAsmJsOffsets(const byte* tables_start,
const byte* tables_end) {
AsmJsOffsets table;
Decoder decoder(tables_start, tables_end);
uint32_t functions_count = decoder.consume_u32v("functions count");
// Reserve space for the entries, taking care of invalid input.
if (functions_count < static_cast<unsigned>(tables_end - tables_start)) {
table.reserve(functions_count);
}
for (uint32_t i = 0; i < functions_count && decoder.ok(); ++i) {
uint32_t size = decoder.consume_u32v("table size");
if (size == 0) {
table.emplace_back();
continue;
}
if (!decoder.checkAvailable(size)) {
decoder.error("illegal asm function offset table size");
}
const byte* table_end = decoder.pc() + size;
uint32_t locals_size = decoder.consume_u32v("locals size");
int function_start_position = decoder.consume_u32v("function start pos");
int last_byte_offset = locals_size;
int last_asm_position = function_start_position;
std::vector<AsmJsOffsetEntry> func_asm_offsets;
func_asm_offsets.reserve(size / 4); // conservative estimation
// Add an entry for the stack check, associated with position 0.
func_asm_offsets.push_back(
{0, function_start_position, function_start_position});
while (decoder.ok() && decoder.pc() < table_end) {
last_byte_offset += decoder.consume_u32v("byte offset delta");
int call_position =
last_asm_position + decoder.consume_i32v("call position delta");
int to_number_position =
call_position + decoder.consume_i32v("to_number position delta");
last_asm_position = to_number_position;
func_asm_offsets.push_back(
{last_byte_offset, call_position, to_number_position});
}
if (decoder.pc() != table_end) {
decoder.error("broken asm offset table");
}
table.push_back(std::move(func_asm_offsets));
}
if (decoder.more()) decoder.error("unexpected additional bytes");
return decoder.toResult(std::move(table));
}
std::vector<CustomSectionOffset> DecodeCustomSections(const byte* start,
const byte* end) {
Decoder decoder(start, end);
decoder.consume_bytes(4, "wasm magic");
decoder.consume_bytes(4, "wasm version");
std::vector<CustomSectionOffset> result;
while (decoder.more()) {
byte section_code = decoder.consume_u8("section code");
uint32_t section_length = decoder.consume_u32v("section length");
uint32_t section_start = decoder.pc_offset();
if (section_code != 0) {
// Skip known sections.
decoder.consume_bytes(section_length, "section bytes");
continue;
}
uint32_t name_length = decoder.consume_u32v("name length");
uint32_t name_offset = decoder.pc_offset();
decoder.consume_bytes(name_length, "section name");
uint32_t payload_offset = decoder.pc_offset();
if (section_length < (payload_offset - section_start)) {
decoder.error("invalid section length");
break;
}
uint32_t payload_length = section_length - (payload_offset - section_start);
decoder.consume_bytes(payload_length);
if (decoder.failed()) break;
result.push_back({{section_start, section_length},
{name_offset, name_length},
{payload_offset, payload_length}});
}
return result;
}
namespace {
bool FindSection(Decoder& decoder, SectionCode section_code) {
static constexpr int kModuleHeaderSize = 8;
decoder.consume_bytes(kModuleHeaderSize, "module header");
WasmSectionIterator section_iter(decoder);
while (decoder.ok() && section_iter.more() &&
section_iter.section_code() != kNameSectionCode) {
section_iter.advance(true);
}
if (!section_iter.more()) return false;
// Reset the decoder to not read beyond the name section end.
decoder.Reset(section_iter.payload(), decoder.pc_offset());
return true;
}
} // namespace
void DecodeFunctionNames(const byte* module_start, const byte* module_end,
std::unordered_map<uint32_t, WireBytesRef>* names) {
DCHECK_NOT_NULL(names);
DCHECK(names->empty());
Decoder decoder(module_start, module_end);
if (!FindSection(decoder, kNameSectionCode)) return;
while (decoder.ok() && decoder.more()) {
uint8_t name_type = decoder.consume_u8("name type");
if (name_type & 0x80) break; // no varuint7
uint32_t name_payload_len = decoder.consume_u32v("name payload length");
if (!decoder.checkAvailable(name_payload_len)) break;
if (name_type != NameSectionKindCode::kFunction) {
decoder.consume_bytes(name_payload_len, "name subsection payload");
continue;
}
uint32_t functions_count = decoder.consume_u32v("functions count");
for (; decoder.ok() && functions_count > 0; --functions_count) {
uint32_t function_index = decoder.consume_u32v("function index");
WireBytesRef name = wasm::consume_string(decoder, false, "function name");
// Be lenient with errors in the name section: Ignore non-UTF8 names. You
// can even assign to the same function multiple times (last valid one
// wins).
if (decoder.ok() && validate_utf8(&decoder, name)) {
names->insert(std::make_pair(function_index, name));
}
}
}
}
void DecodeLocalNames(const byte* module_start, const byte* module_end,
LocalNames* result) {
DCHECK_NOT_NULL(result);
DCHECK(result->names.empty());
Decoder decoder(module_start, module_end);
if (!FindSection(decoder, kNameSectionCode)) return;
while (decoder.ok() && decoder.more()) {
uint8_t name_type = decoder.consume_u8("name type");
if (name_type & 0x80) break; // no varuint7
uint32_t name_payload_len = decoder.consume_u32v("name payload length");
if (!decoder.checkAvailable(name_payload_len)) break;
if (name_type != NameSectionKindCode::kLocal) {
decoder.consume_bytes(name_payload_len, "name subsection payload");
continue;
}
uint32_t local_names_count = decoder.consume_u32v("local names count");
for (uint32_t i = 0; i < local_names_count; ++i) {
uint32_t func_index = decoder.consume_u32v("function index");
if (func_index > kMaxInt) continue;
result->names.emplace_back(static_cast<int>(func_index));
LocalNamesPerFunction& func_names = result->names.back();
result->max_function_index =
std::max(result->max_function_index, func_names.function_index);
uint32_t num_names = decoder.consume_u32v("namings count");
for (uint32_t k = 0; k < num_names; ++k) {
uint32_t local_index = decoder.consume_u32v("local index");
WireBytesRef name = wasm::consume_string(decoder, true, "local name");
if (!decoder.ok()) break;
if (local_index > kMaxInt) continue;
func_names.max_local_index =
std::max(func_names.max_local_index, static_cast<int>(local_index));
func_names.names.emplace_back(static_cast<int>(local_index), name);
}
}
}
}
#undef TRACE
} // namespace wasm
} // namespace internal
} // namespace v8
|
; A040433: Continued fraction for sqrt(455).
; 21,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42,3,42
mov $1,7
lpb $0,1
mod $0,2
mul $1,2
lpe
gcd $1,$0
mul $1,3
|
; A137224: Mix 4*n^2, 1+4*n^2, 1+(2n+1)^2, (2n+1)^2 (or A016742, A053755, A069894, A016754).
; 0,1,2,1,4,5,10,9,16,17,26,25,36,37,50,49,64,65,82,81,100,101,122,121,144,145,170,169,196,197,226,225,256,257,290,289,324,325,362,361,400,401,442,441,484,485,530,529,576,577,626,625,676,677,730,729,784,785,842,841,900,901,962,961,1024,1025,1090,1089,1156,1157,1226,1225,1296,1297,1370,1369,1444,1445,1522,1521,1600,1601,1682,1681,1764,1765,1850,1849,1936,1937,2026,2025,2116,2117,2210,2209,2304,2305,2402,2401
mov $1,$0
div $1,2
add $0,$1
mod $0,2
pow $1,2
add $1,$0
mov $0,$1
|
; A056489: Number of periodic palindromes using exactly three different symbols.
; 0,0,0,3,6,21,36,93,150,345,540,1173,1806,3801,5796,11973,18150,37065,55980,113493,171006,345081,519156,1044453,1569750,3151785,4733820,9492213,14250606,28550361,42850116,85798533,128746950,257690505,386634060,773661333,1160688606,2322163641,3483638676,6968850213,10454061750,20911269225,31368476700,62743244853,94118013006,188248608921,282379204836,564783575493,847187946150,1694426223945,2541664501740,5083429666773,7625194831806,15250590990201,22875987148596,45752376950373,68628766752150
mov $2,$0
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
sub $0,1
div $0,2
mov $3,$0
seq $3,210448 ; Total number of different letters summed over all ternary words of length n.
add $1,$3
lpe
mov $0,$1
|
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include "Chronometer.hpp"
#ifndef FPS_HPP
#define FPS_HPP
/**Una clase estupidamente simple, calcula el FrameRate del programa y lo imprime con sf::Text al fondo de la ventana.
*Tiene una referencia al RenderWindow para preguntar respecto al tamano de la ventana y demas.
*Usa un cronometro simple y una variable entera.
*No tiene sentido crear mas de un objeto FPS.
*/
class FPS
{
public:
explicit FPS(sf::RenderWindow& R, unsigned F = 60);
~FPS();
void draw();
private:
unsigned FCount;
sf::Clock C;
sf::Text T;
sf::Font FT;
static sf::Time Tick;
sf::RenderWindow& RW;
};
#endif
|
; A144844: a(n) = ((2 + sqrt(2))^n - (2 - sqrt(2))^n)^2/8.
; 0,1,16,196,2304,26896,313600,3655744,42614784,496754944,5790601216,67500196864,786839961600,9172078759936,106917585289216,1246322708463616,14528202160472064,169353135091941376,1974124812461670400,23012085209172803584,268248523260228009984,3126933938286047002624,36450213166391656185856,424894822243555694608384,4952937014257101727334400,57735664882110997983133696,673016230528303568955375616,7845252106811198835666190336,91450960359621171752441217024,1066030515888209265687166713856,12426562349220026501237309440000,144854626127087480952101193908224,1688549264128169665420269384105984,19683172665029686061234836423573504,229443874923843554073136976726327296
seq $0,60995 ; Number of routes of length 2n on the sides of an octagon from a point to opposite point.
pow $0,2
div $0,4
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8ServicePortConnectEvent.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/modules/v8/V8ServicePortConnectEventInit.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/frame/LocalDOMWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8ServicePortConnectEvent::wrapperTypeInfo = { gin::kEmbedderBlink, V8ServicePortConnectEvent::domTemplate, V8ServicePortConnectEvent::refObject, V8ServicePortConnectEvent::derefObject, V8ServicePortConnectEvent::trace, 0, 0, V8ServicePortConnectEvent::preparePrototypeObject, V8ServicePortConnectEvent::installConditionallyEnabledProperties, "ServicePortConnectEvent", &V8ExtendableEvent::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in ServicePortConnectEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& ServicePortConnectEvent::s_wrapperTypeInfo = V8ServicePortConnectEvent::wrapperTypeInfo;
namespace ServicePortConnectEventV8Internal {
static void targetURLAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ServicePortConnectEvent* impl = V8ServicePortConnectEvent::toImpl(holder);
v8SetReturnValueString(info, impl->targetURL(), info.GetIsolate());
}
static void targetURLAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
ServicePortConnectEventV8Internal::targetURLAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void originAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ServicePortConnectEvent* impl = V8ServicePortConnectEvent::toImpl(holder);
v8SetReturnValueString(info, impl->origin(), info.GetIsolate());
}
static void originAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
ServicePortConnectEventV8Internal::originAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void respondWithMethodPromise(const v8::FunctionCallbackInfo<v8::Value>& info, ExceptionState& exceptionState)
{
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
return;
}
ServicePortConnectEvent* impl = V8ServicePortConnectEvent::toImpl(info.Holder());
ScriptPromise response;
{
response = ScriptPromise::cast(ScriptState::current(info.GetIsolate()), info[0]);
if (!response.isUndefinedOrNull() && !response.isObject()) {
exceptionState.throwTypeError("parameter 1 ('response') is not an object.");
return;
}
}
ScriptState* scriptState = ScriptState::current(info.GetIsolate());
ScriptPromise result = impl->respondWith(scriptState, response, exceptionState);
if (exceptionState.hadException()) {
return;
}
v8SetReturnValue(info, result.v8Value());
}
static void respondWithMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "respondWith", "ServicePortConnectEvent", info.Holder(), info.GetIsolate());
respondWithMethodPromise(info, exceptionState);
if (exceptionState.hadException())
v8SetReturnValue(info, exceptionState.reject(ScriptState::current(info.GetIsolate())).v8Value());
}
static void respondWithMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
ServicePortConnectEventV8Internal::respondWithMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ConstructionContext, "ServicePortConnectEvent", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
V8StringResource<> type;
ServicePortConnectEventInit eventInitDict;
{
type = info[0];
if (!type.prepare())
return;
if (!isUndefinedOrNull(info[1]) && !info[1]->IsObject()) {
exceptionState.throwTypeError("parameter 2 ('eventInitDict') is not an object.");
exceptionState.throwIfNeeded();
return;
}
V8ServicePortConnectEventInit::toImpl(info.GetIsolate(), info[1], eventInitDict, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
RefPtrWillBeRawPtr<ServicePortConnectEvent> impl = ServicePortConnectEvent::create(type, eventInitDict);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8ServicePortConnectEvent::wrapperTypeInfo, wrapper);
v8SetReturnValue(info, wrapper);
}
} // namespace ServicePortConnectEventV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8ServicePortConnectEventAccessors[] = {
{"targetURL", ServicePortConnectEventV8Internal::targetURLAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"origin", ServicePortConnectEventV8Internal::originAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8ServicePortConnectEventMethods[] = {
{"respondWith", ServicePortConnectEventV8Internal::respondWithMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
};
void V8ServicePortConnectEvent::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SCOPED_SAMPLING_STATE("blink", "DOMConstructor");
if (!info.IsConstructCall()) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("ServicePortConnectEvent"));
return;
}
if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
v8SetReturnValue(info, info.Holder());
return;
}
ServicePortConnectEventV8Internal::constructor(info);
}
static void installV8ServicePortConnectEventTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
if (!RuntimeEnabledFeatures::navigatorConnectEnabled())
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "ServicePortConnectEvent", V8ExtendableEvent::domTemplate(isolate), V8ServicePortConnectEvent::internalFieldCount, 0, 0, 0, 0, 0, 0);
else
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "ServicePortConnectEvent", V8ExtendableEvent::domTemplate(isolate), V8ServicePortConnectEvent::internalFieldCount,
0, 0,
V8ServicePortConnectEventAccessors, WTF_ARRAY_LENGTH(V8ServicePortConnectEventAccessors),
V8ServicePortConnectEventMethods, WTF_ARRAY_LENGTH(V8ServicePortConnectEventMethods));
functionTemplate->SetCallHandler(V8ServicePortConnectEvent::constructorCallback);
functionTemplate->SetLength(1);
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8ServicePortConnectEvent::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8ServicePortConnectEventTemplate);
}
bool V8ServicePortConnectEvent::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8ServicePortConnectEvent::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
ServicePortConnectEvent* V8ServicePortConnectEvent::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8ServicePortConnectEvent::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<ServicePortConnectEvent>()->ref();
#endif
}
void V8ServicePortConnectEvent::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<ServicePortConnectEvent>()->deref();
#endif
}
} // namespace blink
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright(c) 2011-2016 Intel Corporation All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; * Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in
; the documentation and/or other materials provided with the
; distribution.
; * Neither the name of Intel Corporation nor the names of its
; contributors may be used to endorse or promote products derived
; from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
default rel
[bits 64]
%include "reg_sizes.asm"
extern XTS_AES_256_enc_sse
extern XTS_AES_256_enc_avx
extern XTS_AES_256_enc_expanded_key_sse
extern XTS_AES_256_enc_expanded_key_avx
extern XTS_AES_256_dec_sse
extern XTS_AES_256_dec_avx
extern XTS_AES_256_dec_expanded_key_sse
extern XTS_AES_256_dec_expanded_key_avx
%if (AS_FEATURE_LEVEL) >= 10
extern XTS_AES_256_enc_vaes
extern XTS_AES_256_enc_expanded_key_vaes
extern XTS_AES_256_dec_vaes
extern XTS_AES_256_dec_expanded_key_vaes
%endif
section .text
%include "multibinary.asm"
;;;;
; instantiate XTS_AES_256_enc, XTS_AES_256_enc_expanded_key, XTS_AES_256_dec, and XTS_AES_256_dec_expanded_key
;;;;
mbin_interface XTS_AES_256_enc
mbin_dispatch_init7 XTS_AES_256_enc, XTS_AES_256_enc_sse, XTS_AES_256_enc_sse, XTS_AES_256_enc_avx, XTS_AES_256_enc_avx, XTS_AES_256_enc_avx, XTS_AES_256_enc_vaes
mbin_interface XTS_AES_256_enc_expanded_key
mbin_dispatch_init7 XTS_AES_256_enc_expanded_key, XTS_AES_256_enc_expanded_key_sse, XTS_AES_256_enc_expanded_key_sse, XTS_AES_256_enc_expanded_key_avx, XTS_AES_256_enc_expanded_key_avx, XTS_AES_256_enc_expanded_key_avx, XTS_AES_256_enc_expanded_key_vaes
mbin_interface XTS_AES_256_dec
mbin_dispatch_init7 XTS_AES_256_dec, XTS_AES_256_dec_sse, XTS_AES_256_dec_sse, XTS_AES_256_dec_avx, XTS_AES_256_dec_avx, XTS_AES_256_dec_avx, XTS_AES_256_dec_vaes
mbin_interface XTS_AES_256_dec_expanded_key
mbin_dispatch_init7 XTS_AES_256_dec_expanded_key, XTS_AES_256_dec_expanded_key_sse, XTS_AES_256_dec_expanded_key_sse, XTS_AES_256_dec_expanded_key_avx, XTS_AES_256_dec_expanded_key_avx, XTS_AES_256_dec_expanded_key_avx, XTS_AES_256_dec_expanded_key_vaes
;;; func core, ver, snum
slversion XTS_AES_256_enc, 01, 04, 0076
slversion XTS_AES_256_enc_expanded_key, 01, 04, 0077
slversion XTS_AES_256_dec, 01, 04, 0078
slversion XTS_AES_256_dec_expanded_key, 01, 04, 0079
|
.586
.model flat
.code
_conta_vocali_consonanti proc
push ebp
mov ebp,esp
push esi
push edi
push ebx
mov ebx, dword ptr[ebp+8] ;arr
; unsigned char !
mov al, byte ptr [ebx]
cmp al, 0
je fine
mov esi, 0d
mov edi, 0d ; vow
mov ecx, 0d ; cons
mov edx, 0d ; symbols
mov eax, 0d ; min counter
; ABOVE & BELOW UNSIGNED
; GREATER & LESS
is_alpha:
push eax
mov al, byte ptr[ebx+esi]
cmp al, 0
je primo
; alpha check
cmp al, 41h
jl not_alpha
cmp al, 5Ah
jle found_letter
cmp al, 61h
jl not_alpha
cmp al, 7Ah
jg not_alpha
found_letter:
secondo_ciclo:
cmp al, 65
je vowel_f
cmp al, 69
je vowel_f
cmp al, 73
je vowel_f
cmp al, 79
je vowel_f
cmp al, 85
je vowel_f
;min
cmp al, 97
je min_vowel_f
cmp al, 101
je min_vowel_f
cmp al, 105
je min_vowel_f
cmp al, 111
je min_vowel_f
cmp al, 117
je min_vowel_f
add ecx, 1d
jmp keep
not_alpha:
add edx, 1d
keep:
inc esi
jmp is_alpha
min_vowel_f:
pop eax
inc eax
inc edi
jmp keep
vowel_f:
pop eax
inc edi
jmp keep
primo:
pop eax ; min val
mov ebx, dword ptr[ebp+12]
mov [ebx], edi
mov ebx, dword ptr[ebp+16]
mov [ebx], ecx
mov ebx, eax ; min val
cmp edi, 0
je first_p
jmp secondo
first_p:
cmp ecx, 0
je first_p_
jmp secondo
first_p_:
mov eax, -1
secondo:
cmp edx, 0
je sec_f
jmp fine
sec_f:
mov eax, -2
terzo:
cmp ebx, 0 ; all capital
je terzo_f
jmp fine
terzo_f:
mov eax, -3
fine:
pop ebx
pop edi
pop esi
mov esp, ebp
pop ebp
ret
_conta_vocali_consonanti endp
end |
; void *p_list_pop_front(p_list_t *list)
SECTION code_clib
SECTION code_adt_p_list
PUBLIC p_list_pop_front
EXTERN asm_p_list_pop_front
defc p_list_pop_front = asm_p_list_pop_front
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _p_list_pop_front
defc _p_list_pop_front = p_list_pop_front
ENDIF
|
; how to use cmpsb instruction to compare byte strings.
name "cmpsb"
org 100h
; set forward direction:
cld
; load source into ds:si,
; load target into es:di:
mov ax, cs
mov ds, ax
mov es, ax
lea si, str1
lea di, str2
; set counter to string length:
mov cx, size
; compare until equal:
repe cmpsb
jnz not_equal
; "yes" - equal!
mov al, 'y'
mov ah, 0eh
int 10h
jmp exit_here
not_equal:
; "no" - not equal!
mov al, 'n'
mov ah, 0eh
int 10h
exit_here:
; wait for any key press:
mov ah, 0
int 16h
ret
; strings must have equal lengths:
x1:
str1 db 'test string'
str2 db 'test string'
size = ($ - x1) / 2
|
<%
from pwnlib.shellcraft import i386, pretty, common
from pwnlib.util.packing import pack, unpack
from pwnlib.util.lists import group
from pwnlib import constants, log
%>
<%page args="egg, start_address = 0"/>
<%docstring>
egghunter(egg, start_address = 0)
Searches memory for the byte sequence 'egg'.
Return value is the address immediately following the match,
stored in RDI.
Arguments:
egg(str, int): String of bytes, or word-size integer to search for
start_address(int): Where to start the search
</%docstring>
<%
egghunter_loop = common.label('egghunter_loop')
memcmp = common.label('egghunter_memcmp')
done = common.label('egghunter_done')
next_page = common.label('egghunter_nextpage')
egg_str = egg
if isinstance(egg, int):
egg_str = pack(egg)
if len(egg_str) % 4:
log = log.getLogger('pwnlib.shellcraft.templates.i386.linux.egghunter')
log.error("Egg size must be a multiple of four bytes")
%>
cld
${i386.pushstr(egg_str, False)}
% if start_address:
${i386.mov('ebx', start_address)}
% endif
## Search for pages
${egghunter_loop}:
${i386.linux.access('ebx', 0)}
## EFAULT == Bad address
cmp al, (-${pretty(constants.EFAULT)}) & 0xff
jz ${next_page}
## We found a page, scan all of the DWORDs
${i386.mov('edx', 0x1000 // 4)}
${memcmp}:
test edx, edx
jz ${next_page}
## Scan forward by DWORD
${i386.setregs({'esi':'esp',
'edi':'ebx',
'ecx': len(egg_str) // 4})}
## Success?
repe cmpsd
jz ${done}
## Increment the starting point, decement the counter, restart
add ebx, 4
dec edx
jnz ${memcmp}
${next_page}:
## Next page
or bx, 0xfff
inc ebx
jmp ${egghunter_loop}
${done}:
|
BITS 32
;TEST_FILE_META_BEGIN
;TEST_TYPE=TEST_F
;TEST_IGNOREFLAGS=FLAG_OF
;TEST_FILE_META_END
; ROL8rCL
mov bh, 0x41
mov cl, 0x4
;TEST_BEGIN_RECORDING
rol bh, cl
;TEST_END_RECORDING
|
; /*****************************************************************************
; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers *
; *****************************************************************************
; * Copyright 2021 Marco Spedaletti (asimov@mclink.it)
; *
; * 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.
; *----------------------------------------------------------------------------
; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0
; * (la "Licenza"); è proibito usare questo file se non in conformità alla
; * Licenza. Una copia della Licenza è disponibile all'indirizzo:
; *
; * http://www.apache.org/licenses/LICENSE-2.0
; *
; * Se non richiesto dalla legislazione vigente o concordato per iscritto,
; * il software distribuito nei termini della Licenza è distribuito
; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o
; * implicite. Consultare la Licenza per il testo specifico che regola le
; * autorizzazioni e le limitazioni previste dalla medesima.
; ****************************************************************************/
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;* *
;* PLOT ROUTINE ON TED *
;* *
;* by Marco Spedaletti *
;* *
;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
PLOTX = $22 ; $23
PLOTY = $24
PLOTM = $25
PLOTOMA = $26
PLOTAMA = $27
;--------------
PLOT:
CLC
LDA PLOTY
CMP CLIPY2
BCC PLOTCLIP2
BEQ PLOTCLIP2
JMP PLOTP
PLOTCLIP2:
CMP CLIPY1
BEQ PLOTCLIP3
BCS PLOTCLIP3
JMP PLOTP
PLOTCLIP3:
LDA PLOTX+1
CMP CLIPX2+1
BCC PLOTCLIP4
BEQ PLOTCLIP3B
JMP PLOTP
PLOTCLIP3B:
LDA PLOTX
CMP CLIPX2
BCC PLOTCLIP4
BEQ PLOTCLIP4
JMP PLOTP
PLOTCLIP4:
LDA PLOTX+1
CMP CLIPX1+1
BCS PLOTCLIP5
BEQ PLOTCLIP4B
JMP PLOTP
PLOTCLIP4B:
LDA PLOTX
CMP CLIPX1
BCS PLOTCLIP5
BEQ PLOTCLIP5
JMP PLOTP
PLOTCLIP5:
PLOTMODE:
LDA CURRENTMODE
; BITMAP_MODE_STANDARD
CMP #2
BNE PLOT2X
JMP PLOT2
PLOT2X:
; BITMAP_MODE_MULTICOLOR
CMP #3
BNE PLOT3X
JMP PLOT3
PLOT3X:
; TILEMAP_MODE_STANDARD
CMP #0
BNE PLOT0X
JMP PLOT0
PLOT0X:
; TILEMAP_MODE_MULTICOLOR
CMP #1
BNE PLOT1X
JMP PLOT1
PLOT1X:
; TILEMAP_MODE_EXTENDED
CMP #4
BNE PLOT4X
JMP PLOT4
PLOT4X:
RTS
PLOT0:
PLOT1:
PLOT4:
RTS
PLOT2:
;-------------------------
;calc Y-cell, divide by 8
;y/8 is y-cell table index
;-------------------------
LDA PLOTY
LSR ;/ 2
LSR ;/ 4
LSR ;/ 8
TAY ;tbl_8,y index
CLC
;------------------------
;calc X-cell, divide by 8
;divide 2-byte PLOTX / 8
;------------------------
LDA PLOTX
ROR PLOTX+1 ;rotate the high byte into carry flag
ROR ;lo byte / 2 (rotate C into low byte)
LSR ;lo byte / 4
LSR ;lo byte / 8
TAX ;tbl_8,x index
;----------------------------------
;add x & y to calc cell point is in
;----------------------------------
CLC
LDA PLOTVBASELO,Y ;table of $A000 row base addresses
ADC PLOT8LO,X ;+ (8 * Xcell)
STA PLOTDEST ;= cell address
LDA PLOTVBASEHI,Y ;do the high byte
ADC PLOT8HI,X
STA PLOTDEST+1
CLC
TXA
ADC PLOTCVBASELO,Y ;table of $8400 row base addresses
STA PLOTCDEST ;= cell address
LDA #0
ADC PLOTCVBASEHI,Y ;do the high byte
STA PLOTCDEST+1
SEC
LDA PLOTCDEST
SBC #$00
STA PLOTLDEST ;= cell address
LDA PLOTCDEST+1
SBC #$04
STA PLOTLDEST+1 ;= cell address
;---------------------------------
;get in-cell offset to point (0-7)
;---------------------------------
LDA PLOTX ;get PLOTX offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAX ;put into index register
LDA PLOTY ;get PLOTY offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAY ;put into index register
LDA #<PLOTORBIT
STA TMPPTR
LDA #>PLOTORBIT
STA TMPPTR+1
CLC
TXA
ADC TMPPTR
STA TMPPTR
LDA #0
ADC TMPPTR+1
STA TMPPTR+1
LDY #0
LDA (TMPPTR),Y
STA PLOTOMA
LDA PLOTX
AND #$07
TAX
LDA PLOTANDBIT,X
STA PLOTAMA
;---------------------------------
;get in-cell offset to point (0-7)
;---------------------------------
LDA PLOTX ;get PLOTX offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAX ;put into index register
LDA PLOTY ;get PLOTY offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAY ;put into index register
JMP PLOTCOMMON
PLOT3:
;-------------------------
;calc Y-cell, divide by 8
;y/8 is y-cell table index
;-------------------------
LDA PLOTY
LSR ;/ 2
LSR ;/ 4
LSR ;/ 8
TAY ;tbl_8,y index
CLC
;------------------------
;calc X-cell, divide by 8
;divide 2-byte PLOTX / 8
;------------------------
LDA PLOTX
ROR PLOTX+1 ;rotate the high byte into carry flag
ROR ;lo byte / 2 (rotate C into low byte)
LSR ;lo byte / 4
TAX ;tbl_8,x index
;----------------------------------
;add x & y to calc cell point is in
;----------------------------------
CLC
LDA PLOTVBASELO,Y ;table of $A000 row base addresses
ADC PLOT8LO,X ;+ (8 * Xcell)
STA PLOTDEST ;= cell address
LDA PLOTVBASEHI,Y ;do the high byte
ADC PLOT8HI,X
STA PLOTDEST+1
CLC
TXA
ADC PLOTCVBASELO,Y ;table of $8400 row base addresses
STA PLOTCDEST ;= cell address
LDA #0
ADC PLOTCVBASEHI,Y ;do the high byte
STA PLOTCDEST+1
TXA
ADC PLOTC2VBASELO,Y ;table of $8400 row base addresses
STA PLOTC2DEST ;= cell address
LDA #0
ADC PLOTC2VBASEHI,Y ;do the high byte
STA PLOTC2DEST+1
;---------------------------------
;get in-cell offset to point (0-7)
;---------------------------------
LDA PLOTX ;get PLOTX offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAX ;put into index register
LDA PLOTY ;get PLOTY offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAY ;put into index register
LDY #0
LDA (PLOTCDEST),Y
AND #$0F
CMP _PEN
BEQ PLOT3C1
LDY #0
LDA (PLOTCDEST),Y
LSR
LSR
LSR
LSR
CMP _PEN
BEQ PLOT3C2
LDA (PLOTC2DEST),Y
AND #$0F
CMP _PEN
BEQ PLOT3C3
LDA LASTCOLOR
CMP #1
BEQ PLOT3SC2
CMP #2
BEQ PLOT3SC3
CMP #3
BEQ PLOT3SC1
PLOT3SC1:
LDA (PLOTCDEST),Y
AND #$0F
STA (PLOTCDEST),Y
LDA _PEN
ASL
ASL
ASL
ASL
ORA (PLOTCDEST),Y
STA (PLOTCDEST),Y
LDA #1
STA LASTCOLOR
PLOT3C1:
LDA #<PLOTORBIT41
STA TMPPTR
LDA #>PLOTORBIT41
STA TMPPTR+1
JMP PLOT3PEN
PLOT3SC2:
LDA (PLOTCDEST),Y
AND #$F0
STA (PLOTCDEST),Y
LDA _PEN
ORA (PLOTCDEST),Y
STA (PLOTCDEST),Y
LDA #2
STA LASTCOLOR
PLOT3C2:
LDA #<PLOTORBIT42
STA TMPPTR
LDA #>PLOTORBIT42
STA TMPPTR+1
JMP PLOT3PEN
PLOT3SC3:
LDA _PEN
LDY #0
STA (PLOTC2DEST),Y
LDA #3
STA LASTCOLOR
PLOT3C3:
LDA #<PLOTORBIT43
STA TMPPTR
LDA #>PLOTORBIT43
STA TMPPTR+1
JMP PLOT3PEN
PLOT3PEN:
;---------------------------------
;get in-cell offset to point (0-7)
;---------------------------------
LDA PLOTX ;get PLOTX offset from cell topleft
AND #%00000011 ;2 lowest bits = (0-4)
TAX ;put into index register
LDA PLOTY ;get PLOTY offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAY ;put into index register
CLC
TXA
ADC TMPPTR
STA TMPPTR
LDA #0
ADC TMPPTR+1
STA TMPPTR+1
LDY #0
LDA (TMPPTR),Y
STA PLOTOMA
LDA PLOTX
AND #$03
TAX
LDA PLOTANDBIT4,X
STA PLOTAMA
;---------------------------------
;get in-cell offset to point (0-7)
;---------------------------------
LDA PLOTX ;get PLOTX offset from cell topleft
AND #%00000111 ;2 lowest bits = (0-4)
TAX ;put into index register
LDA PLOTY ;get PLOTY offset from cell topleft
AND #%00000111 ;3 lowest bits = (0-7)
TAY
JMP PLOTCOMMON
PLOTCOMMON:
;----------------------------------------------
;depending on PLOTM, routine draws or erases
;----------------------------------------------
LDA PLOTM ;(0 = erase, 1 = set, 2 = get pixel, 3 = get color)
CMP #0
BEQ PLOTE ;if = 0 then branch to clear the point
CMP #1
BEQ PLOTD ;if = 1 then branch to draw the point
CMP #2
BEQ PLOTG ;if = 2 then branch to get the point (0/1)
CMP #3
BEQ PLOTC ;if = 3 then branch to get the color index (0...15)
JMP PLOTP
PLOTD:
;---------
;set point
;---------
LDA (PLOTDEST),y ;get row with point in it
ORA PLOTORBIT,x ;isolate AND set the point
STA (PLOTDEST),y ;write back to $A000
LDY #0
LDA (PLOTCDEST),y ;get row with point in it
AND #$0f ;isolate AND set the point
ORA _PEN ;isolate OR set the point
STA (PLOTCDEST),y ;write back to $A000
LDY #0
LDA (PLOTLDEST),y ;get row with point in it
AND #$0f ;isolate AND set the point
ORA #$30 ;increase luminance
STA (PLOTLDEST),y ;write back to $A000
JMP PLOTP ;skip the erase-point section
;-----------
;erase point
;-----------
PLOTE: ;handled same way as setting a point
LDA (PLOTDEST),y ;just with opposite bit-mask
AND PLOTANDBIT,x ;isolate AND erase the point
STA (PLOTDEST),y ;write back to $A000
LDY #0
LDA #0 ;get row with point in it
STA (PLOTLDEST),y ;write back to $A000
JMP PLOTP
PLOTG:
LDA (PLOTDEST),y
AND PLOTORBIT,x
CMP #0
BEQ PLOTG0
PLOTG1:
LDA #$ff
STA PLOTM
JMP PLOTP
PLOTG0:
LDA #$0
STA PLOTM
JMP PLOTP
PLOTC:
LDY #0
LDA (PLOTCDEST),y ;get row with point in it
LSR A
LSR A
LSR A
LSR A
STA PLOTM
JMP PLOTP
PLOTP:
RTS
;----------------------------------------------------------------
PLOTORBIT:
.byte %10000000
.byte %01000000
.byte %00100000
.byte %00010000
.byte %00001000
.byte %00000100
.byte %00000010
.byte %00000001
PLOTANDBIT:
.byte %01111111
.byte %10111111
.byte %11011111
.byte %11101111
.byte %11110111
.byte %11111011
.byte %11111101
.byte %11111110
PLOTORBIT40:
.byte %00000000
.byte %00000000
.byte %00000000
.byte %00000000
PLOTORBIT41:
.byte %01000000
.byte %00010000
.byte %00000100
.byte %00000001
PLOTORBIT42:
.byte %10000000
.byte %00100000
.byte %00001000
.byte %00000010
PLOTORBIT43:
.byte %11000000
.byte %00110000
.byte %00001100
.byte %00000011
PLOTANDBIT4:
.byte %00111111
.byte %11001111
.byte %11110011
.byte %11111100
|
//
// windows/object_handle_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2012 Christopher M. Kohlhoff (chris at kohlhoff dot com)
// Copyright (c) 2011 Boris Schaeling (boris@highscore.de)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_WINDOWS_OBJECT_HANDLE_SERVICE_HPP
#define BOOST_ASIO_WINDOWS_OBJECT_HANDLE_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_WINDOWS_OBJECT_HANDLE) \
|| defined(GENERATING_DOCUMENTATION)
#include <boost/asio/detail/win_object_handle_service.hpp>
#include <boost/asio/error.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace boost {
namespace asio {
namespace windows {
/// Default service implementation for an object handle.
class object_handle_service
#if defined(GENERATING_DOCUMENTATION)
: public boost::asio::io_service::service
#else
: public boost::asio::detail::service_base<object_handle_service>
#endif
{
public:
#if defined(GENERATING_DOCUMENTATION)
/// The unique service identifier.
static boost::asio::io_service::id id;
#endif
private:
// The type of the platform-specific implementation.
typedef detail::win_object_handle_service service_impl_type;
public:
/// The type of an object handle implementation.
#if defined(GENERATING_DOCUMENTATION)
typedef implementation_defined implementation_type;
#else
typedef service_impl_type::implementation_type implementation_type;
#endif
/// The native handle type.
#if defined(GENERATING_DOCUMENTATION)
typedef implementation_defined native_handle_type;
#else
typedef service_impl_type::native_handle_type native_handle_type;
#endif
/// Construct a new object handle service for the specified io_service.
explicit object_handle_service(boost::asio::io_service& io_service)
: boost::asio::detail::service_base<object_handle_service>(io_service),
service_impl_(io_service)
{
}
/// Construct a new object handle implementation.
void construct(implementation_type& impl)
{
service_impl_.construct(impl);
}
#if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move-construct a new object handle implementation.
void move_construct(implementation_type& impl,
implementation_type& other_impl)
{
service_impl_.move_construct(impl, other_impl);
}
/// Move-assign from another object handle implementation.
void move_assign(implementation_type& impl,
object_handle_service& other_service,
implementation_type& other_impl)
{
service_impl_.move_assign(impl, other_service.service_impl_, other_impl);
}
#endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Destroy an object handle implementation.
void destroy(implementation_type& impl)
{
service_impl_.destroy(impl);
}
/// Assign an existing native handle to an object handle.
boost::system::error_code assign(implementation_type& impl,
const native_handle_type& handle, boost::system::error_code& ec)
{
return service_impl_.assign(impl, handle, ec);
}
/// Determine whether the handle is open.
bool is_open(const implementation_type& impl) const
{
return service_impl_.is_open(impl);
}
/// Close an object handle implementation.
boost::system::error_code close(implementation_type& impl,
boost::system::error_code& ec)
{
return service_impl_.close(impl, ec);
}
/// Get the native handle implementation.
native_handle_type native_handle(implementation_type& impl)
{
return service_impl_.native_handle(impl);
}
/// Cancel all asynchronous operations associated with the handle.
boost::system::error_code cancel(implementation_type& impl,
boost::system::error_code& ec)
{
return service_impl_.cancel(impl, ec);
}
// Wait for a signaled state.
void wait(implementation_type& impl, boost::system::error_code& ec)
{
service_impl_.wait(impl, ec);
}
/// Start an asynchronous wait.
template <typename WaitHandler>
void async_wait(implementation_type& impl,
BOOST_ASIO_MOVE_ARG(WaitHandler) handler)
{
service_impl_.async_wait(impl, BOOST_ASIO_MOVE_CAST(WaitHandler)(handler));
}
private:
// Destroy all user-defined handler objects owned by the service.
void shutdown_service()
{
service_impl_.shutdown_service();
}
// The platform-specific implementation.
service_impl_type service_impl_;
};
} // namespace windows
} // namespace asio
} // namespace boost
#include <boost/asio/detail/pop_options.hpp>
#endif // defined(BOOST_ASIO_HAS_WINDOWS_OBJECT_HANDLE)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_WINDOWS_OBJECT_HANDLE_SERVICE_HPP
|
/**
******************************************************************************
* This file is part of the TouchGFX 4.10.0 distribution.
*
* <h2><center>© Copyright (c) 2018 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef STM32F7INSTRUMENTATION_HPP
#define STM32F7INSTRUMENTATION_HPP
#include <platform/core/MCUInstrumentation.hpp>
#include <stdint.h>
namespace touchgfx
{
class STM32F7Instrumentation: public MCUInstrumentation
{
public:
virtual void init();
virtual unsigned int getElapsedUS(unsigned int start, unsigned int now, unsigned int clockfrequency);
virtual unsigned int getCPUCycles();
virtual void setMCUActive(bool active);
private:
uint32_t m_sysclkRatio;
};
} // namespace touchgfx
#endif // STM32F7INSTRUMENTATION_HPP
|
; A081133: a(n) = n^n*binomial(n+2, 2).
; 1,3,24,270,3840,65625,1306368,29647548,754974720,21308126895,660000000000,22254310307658,811365140791296,31801886192186565,1333440819066961920,59553569091796875000,2822351843277561397248,141458084782563586674267,7475817534306342139330560,415468127688665853716035590,24222105600000000000000000000,1478174515651653577909424478513,94234094152524597841474495709184,6264140399954373610306509873170100,433464127476342340445951478674227200,31175062531474395655095577239990234375
mov $2,$0
pow $2,$0
add $0,2
bin $0,2
mul $0,$2
|
;
; Copyright (c) 2016, Alliance for Open Media. All rights reserved
;
; This source code is subject to the terms of the BSD 2 Clause License and
; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
; was not distributed with this source code in the LICENSE file, you can
; obtain it at www.aomedia.org/license/software. If the Alliance for Open
; Media Patent License 1.0 was not distributed with this source code in the
; PATENTS file, you can obtain it at www.aomedia.org/license/patent.
;
;
%include "aom_ports/x86_abi_support.asm"
;Note: tap3 and tap4 have to be applied and added after other taps to avoid
;overflow.
%macro HIGH_GET_FILTERS_4 0
mov rdx, arg(5) ;filter ptr
mov rcx, 0x00000040
movdqa xmm7, [rdx] ;load filters
pshuflw xmm0, xmm7, 0b ;k0
pshuflw xmm1, xmm7, 01010101b ;k1
pshuflw xmm2, xmm7, 10101010b ;k2
pshuflw xmm3, xmm7, 11111111b ;k3
psrldq xmm7, 8
pshuflw xmm4, xmm7, 0b ;k4
pshuflw xmm5, xmm7, 01010101b ;k5
pshuflw xmm6, xmm7, 10101010b ;k6
pshuflw xmm7, xmm7, 11111111b ;k7
punpcklwd xmm0, xmm6
punpcklwd xmm2, xmm5
punpcklwd xmm3, xmm4
punpcklwd xmm1, xmm7
movdqa k0k6, xmm0
movdqa k2k5, xmm2
movdqa k3k4, xmm3
movdqa k1k7, xmm1
movq xmm6, rcx
pshufd xmm6, xmm6, 0
movdqa krd, xmm6
;Compute max and min values of a pixel
mov rdx, 0x00010001
movsxd rcx, DWORD PTR arg(6) ;bps
movq xmm0, rdx
movq xmm1, rcx
pshufd xmm0, xmm0, 0b
movdqa xmm2, xmm0
psllw xmm0, xmm1
psubw xmm0, xmm2
pxor xmm1, xmm1
movdqa max, xmm0 ;max value (for clamping)
movdqa min, xmm1 ;min value (for clamping)
%endm
%macro HIGH_APPLY_FILTER_4 1
punpcklwd xmm0, xmm6 ;two row in one register
punpcklwd xmm1, xmm7
punpcklwd xmm2, xmm5
punpcklwd xmm3, xmm4
pmaddwd xmm0, k0k6 ;multiply the filter factors
pmaddwd xmm1, k1k7
pmaddwd xmm2, k2k5
pmaddwd xmm3, k3k4
paddd xmm0, xmm1 ;sum
paddd xmm0, xmm2
paddd xmm0, xmm3
paddd xmm0, krd ;rounding
psrad xmm0, 7 ;shift
packssdw xmm0, xmm0 ;pack to word
;clamp the values
pminsw xmm0, max
pmaxsw xmm0, min
%if %1
movq xmm1, [rdi]
pavgw xmm0, xmm1
%endif
movq [rdi], xmm0
%endm
%macro HIGH_GET_FILTERS 0
mov rdx, arg(5) ;filter ptr
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
mov rcx, 0x00000040
movdqa xmm7, [rdx] ;load filters
pshuflw xmm0, xmm7, 0b ;k0
pshuflw xmm1, xmm7, 01010101b ;k1
pshuflw xmm2, xmm7, 10101010b ;k2
pshuflw xmm3, xmm7, 11111111b ;k3
pshufhw xmm4, xmm7, 0b ;k4
pshufhw xmm5, xmm7, 01010101b ;k5
pshufhw xmm6, xmm7, 10101010b ;k6
pshufhw xmm7, xmm7, 11111111b ;k7
punpcklqdq xmm2, xmm2
punpcklqdq xmm3, xmm3
punpcklwd xmm0, xmm1
punpckhwd xmm6, xmm7
punpckhwd xmm2, xmm5
punpckhwd xmm3, xmm4
movdqa k0k1, xmm0 ;store filter factors on stack
movdqa k6k7, xmm6
movdqa k2k5, xmm2
movdqa k3k4, xmm3
movq xmm6, rcx
pshufd xmm6, xmm6, 0
movdqa krd, xmm6 ;rounding
;Compute max and min values of a pixel
mov rdx, 0x00010001
movsxd rcx, DWORD PTR arg(6) ;bps
movq xmm0, rdx
movq xmm1, rcx
pshufd xmm0, xmm0, 0b
movdqa xmm2, xmm0
psllw xmm0, xmm1
psubw xmm0, xmm2
pxor xmm1, xmm1
movdqa max, xmm0 ;max value (for clamping)
movdqa min, xmm1 ;min value (for clamping)
%endm
%macro LOAD_VERT_8 1
movdqu xmm0, [rsi + %1] ;0
movdqu xmm1, [rsi + rax + %1] ;1
movdqu xmm6, [rsi + rdx * 2 + %1] ;6
lea rsi, [rsi + rax]
movdqu xmm7, [rsi + rdx * 2 + %1] ;7
movdqu xmm2, [rsi + rax + %1] ;2
movdqu xmm3, [rsi + rax * 2 + %1] ;3
movdqu xmm4, [rsi + rdx + %1] ;4
movdqu xmm5, [rsi + rax * 4 + %1] ;5
%endm
%macro HIGH_APPLY_FILTER_8 2
movdqu temp, xmm4
movdqa xmm4, xmm0
punpcklwd xmm0, xmm1
punpckhwd xmm4, xmm1
movdqa xmm1, xmm6
punpcklwd xmm6, xmm7
punpckhwd xmm1, xmm7
movdqa xmm7, xmm2
punpcklwd xmm2, xmm5
punpckhwd xmm7, xmm5
movdqu xmm5, temp
movdqu temp, xmm4
movdqa xmm4, xmm3
punpcklwd xmm3, xmm5
punpckhwd xmm4, xmm5
movdqu xmm5, temp
pmaddwd xmm0, k0k1
pmaddwd xmm5, k0k1
pmaddwd xmm6, k6k7
pmaddwd xmm1, k6k7
pmaddwd xmm2, k2k5
pmaddwd xmm7, k2k5
pmaddwd xmm3, k3k4
pmaddwd xmm4, k3k4
paddd xmm0, xmm6
paddd xmm0, xmm2
paddd xmm0, xmm3
paddd xmm5, xmm1
paddd xmm5, xmm7
paddd xmm5, xmm4
paddd xmm0, krd ;rounding
paddd xmm5, krd
psrad xmm0, 7 ;shift
psrad xmm5, 7
packssdw xmm0, xmm5 ;pack back to word
;clamp the values
pminsw xmm0, max
pmaxsw xmm0, min
%if %1
movdqu xmm1, [rdi + %2]
pavgw xmm0, xmm1
%endif
movdqu [rdi + %2], xmm0
%endm
SECTION .text
;void aom_filter_block1d4_v8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d4_v8_sse2) PRIVATE
sym(aom_highbd_filter_block1d4_v8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 7
%define k0k6 [rsp + 16 * 0]
%define k2k5 [rsp + 16 * 1]
%define k3k4 [rsp + 16 * 2]
%define k1k7 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define max [rsp + 16 * 5]
%define min [rsp + 16 * 6]
HIGH_GET_FILTERS_4
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rbx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rbx, [rbx + rbx]
lea rdx, [rax + rax * 2]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
movq xmm0, [rsi] ;load src: row 0
movq xmm1, [rsi + rax] ;1
movq xmm6, [rsi + rdx * 2] ;6
lea rsi, [rsi + rax]
movq xmm7, [rsi + rdx * 2] ;7
movq xmm2, [rsi + rax] ;2
movq xmm3, [rsi + rax * 2] ;3
movq xmm4, [rsi + rdx] ;4
movq xmm5, [rsi + rax * 4] ;5
HIGH_APPLY_FILTER_4 0
lea rdi, [rdi + rbx]
dec rcx
jnz .loop
add rsp, 16 * 7
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void aom_filter_block1d8_v8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d8_v8_sse2) PRIVATE
sym(aom_highbd_filter_block1d8_v8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 8
%define k0k1 [rsp + 16 * 0]
%define k6k7 [rsp + 16 * 1]
%define k2k5 [rsp + 16 * 2]
%define k3k4 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define temp [rsp + 16 * 5]
%define max [rsp + 16 * 6]
%define min [rsp + 16 * 7]
HIGH_GET_FILTERS
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rbx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rbx, [rbx + rbx]
lea rdx, [rax + rax * 2]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
LOAD_VERT_8 0
HIGH_APPLY_FILTER_8 0, 0
lea rdi, [rdi + rbx]
dec rcx
jnz .loop
add rsp, 16 * 8
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void aom_filter_block1d16_v8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pitch,
; unsigned char *output_ptr,
; unsigned int out_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d16_v8_sse2) PRIVATE
sym(aom_highbd_filter_block1d16_v8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
push rbx
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 8
%define k0k1 [rsp + 16 * 0]
%define k6k7 [rsp + 16 * 1]
%define k2k5 [rsp + 16 * 2]
%define k3k4 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define temp [rsp + 16 * 5]
%define max [rsp + 16 * 6]
%define min [rsp + 16 * 7]
HIGH_GET_FILTERS
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rbx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rbx, [rbx + rbx]
lea rdx, [rax + rax * 2]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
LOAD_VERT_8 0
HIGH_APPLY_FILTER_8 0, 0
sub rsi, rax
LOAD_VERT_8 16
HIGH_APPLY_FILTER_8 0, 16
add rdi, rbx
dec rcx
jnz .loop
add rsp, 16 * 8
pop rsp
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void aom_filter_block1d4_h8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d4_h8_sse2) PRIVATE
sym(aom_highbd_filter_block1d4_h8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 7
%define k0k6 [rsp + 16 * 0]
%define k2k5 [rsp + 16 * 1]
%define k3k4 [rsp + 16 * 2]
%define k1k7 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define max [rsp + 16 * 5]
%define min [rsp + 16 * 6]
HIGH_GET_FILTERS_4
mov rsi, arg(0) ;src_ptr
mov rdi, arg(2) ;output_ptr
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rdx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rdx, [rdx + rdx]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
movdqu xmm0, [rsi - 6] ;load src
movdqu xmm4, [rsi + 2]
movdqa xmm1, xmm0
movdqa xmm6, xmm4
movdqa xmm7, xmm4
movdqa xmm2, xmm0
movdqa xmm3, xmm0
movdqa xmm5, xmm4
psrldq xmm1, 2
psrldq xmm6, 4
psrldq xmm7, 6
psrldq xmm2, 4
psrldq xmm3, 6
psrldq xmm5, 2
HIGH_APPLY_FILTER_4 0
lea rsi, [rsi + rax]
lea rdi, [rdi + rdx]
dec rcx
jnz .loop
add rsp, 16 * 7
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void aom_filter_block1d8_h8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d8_h8_sse2) PRIVATE
sym(aom_highbd_filter_block1d8_h8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 8
%define k0k1 [rsp + 16 * 0]
%define k6k7 [rsp + 16 * 1]
%define k2k5 [rsp + 16 * 2]
%define k3k4 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define temp [rsp + 16 * 5]
%define max [rsp + 16 * 6]
%define min [rsp + 16 * 7]
HIGH_GET_FILTERS
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rdx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rdx, [rdx + rdx]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
movdqu xmm0, [rsi - 6] ;load src
movdqu xmm1, [rsi - 4]
movdqu xmm2, [rsi - 2]
movdqu xmm3, [rsi]
movdqu xmm4, [rsi + 2]
movdqu xmm5, [rsi + 4]
movdqu xmm6, [rsi + 6]
movdqu xmm7, [rsi + 8]
HIGH_APPLY_FILTER_8 0, 0
lea rsi, [rsi + rax]
lea rdi, [rdi + rdx]
dec rcx
jnz .loop
add rsp, 16 * 8
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
;void aom_filter_block1d16_h8_sse2
;(
; unsigned char *src_ptr,
; unsigned int src_pixels_per_line,
; unsigned char *output_ptr,
; unsigned int output_pitch,
; unsigned int output_height,
; short *filter
;)
global sym(aom_highbd_filter_block1d16_h8_sse2) PRIVATE
sym(aom_highbd_filter_block1d16_h8_sse2):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
SAVE_XMM 7
push rsi
push rdi
; end prolog
ALIGN_STACK 16, rax
sub rsp, 16 * 8
%define k0k1 [rsp + 16 * 0]
%define k6k7 [rsp + 16 * 1]
%define k2k5 [rsp + 16 * 2]
%define k3k4 [rsp + 16 * 3]
%define krd [rsp + 16 * 4]
%define temp [rsp + 16 * 5]
%define max [rsp + 16 * 6]
%define min [rsp + 16 * 7]
HIGH_GET_FILTERS
movsxd rax, DWORD PTR arg(1) ;pixels_per_line
movsxd rdx, DWORD PTR arg(3) ;out_pitch
lea rax, [rax + rax] ;bytes per line
lea rdx, [rdx + rdx]
movsxd rcx, DWORD PTR arg(4) ;output_height
.loop:
movdqu xmm0, [rsi - 6] ;load src
movdqu xmm1, [rsi - 4]
movdqu xmm2, [rsi - 2]
movdqu xmm3, [rsi]
movdqu xmm4, [rsi + 2]
movdqu xmm5, [rsi + 4]
movdqu xmm6, [rsi + 6]
movdqu xmm7, [rsi + 8]
HIGH_APPLY_FILTER_8 0, 0
movdqu xmm0, [rsi + 10] ;load src
movdqu xmm1, [rsi + 12]
movdqu xmm2, [rsi + 14]
movdqu xmm3, [rsi + 16]
movdqu xmm4, [rsi + 18]
movdqu xmm5, [rsi + 20]
movdqu xmm6, [rsi + 22]
movdqu xmm7, [rsi + 24]
HIGH_APPLY_FILTER_8 0, 16
lea rsi, [rsi + rax]
lea rdi, [rdi + rdx]
dec rcx
jnz .loop
add rsp, 16 * 8
pop rsp
; begin epilog
pop rdi
pop rsi
RESTORE_XMM
UNSHADOW_ARGS
pop rbp
ret
|
; =============================================================================
; Bootable interpreter for a simple yet popular pain-inducing """programming
; language". Fits within a boot sector.
;
; Nice features:
; - Partial line editor (allows for backspace at least, no erasing past
; beginning of line, etc.)
; - I/O reads can be canceled with ^C which allows breaking input-bound loops
; - Memory is zeroed on each re-run
; - Loops are somewhat efficiently implemented, they both check for zero/non-
; zero conditions respectively instead of just one or the other which avoids
; some double-searching.
; =============================================================================
bits 16
org 0x7c00
jmp 0:_start
; =============================================================================
; Text I/O
; =============================================================================
; write the first argument to the stack. clobbers ax
putc:
push bp
mov bp, sp
mov ah, 0x0e
mov al, [bp+4]
; either a cr or lf causes us to go to emit both
cmp al, `\r`
je .cr
cmp al, `\n`
je .cr
; backspace causes overwrite with space
cmp al, `\b`
je .bs
; otherwise just print it
jmp .else
.bs:
mov al, `\b`
int 10h
mov al, ` `
int 10h
mov al, `\b`
jmp .else
.cr:
mov al, `\r`
int 10h
mov al, `\n`
.else:
int 10h
mov sp, bp
pop bp
ret
; Write a string pointed to by the first argument to the stack
puts:
push bp
mov bp, sp
push si
push bx
mov bx, [bp+4]
xor si, si
mov al, [bx+si]
; for the edge case where the first character is the null byte, just
; give up right away
test al, al
jz .end
.write:
push ax
call putc
add sp, 2
inc si
mov al, [bx+si]
test al, al
jnz .write
.end:
pop bx
pop si
mov sp, bp
pop bp
ret
; get a single character of input, no echo!
getc:
xor ah, ah
int 16h
xor ah, ah
ret
; get a full line of input. stored in the buffer pointed to by the first argument
gets:
push bp
mov bp, sp
push bx
push si
mov bx, [bp+4]
xor si, si
.in_loop:
call getc
; if this is a backspace, then we need to only allow it if there is
; something to backspace available
cmp al, `\b`
jne .no_bs
test si, si
jz .in_loop ; disallow because there's nothing to remove
sub si, 1
jmp .echo
.no_bs:
mov BYTE [bx+si], al
inc si
.echo:
push ax
call putc
pop ax
; enter finishes input
cmp al, `\r`
jne .in_loop
; overwrite the enter with a null byte
dec si
mov BYTE [bx+si], 0
pop si
pop bx
mov sp, bp
pop bp
ret
; clear the screen. clobbers ax
clear_screen:
mov ah, 0x00
mov al, 0x03
int 10h
ret
; =============================================================================
; Interpreter
;
; This handles the interpretation of the entire program.
;
; It is given a string containing the instructions, and then it will operate
; on the tape as per the instructions given.
; =============================================================================
; interpret the program.
;
; the only argument is the pointer to the program. all registers are preserved.
interpret:
push bp
mov bp, sp
pusha
; clear out the first 30,000 memory locations
xor ax, ax
mov di, memory
mov cx, 16000
rep stosw
mov di, [bp+4] ; the program
mov bx, memory ; the memory
mov si, 0 ; "data pointer"
.op:
; get the character to work on
xor ax, ax
mov al, [di]
; if this is the null byte, then we've finished the entire program
test al, al
jz .end
; for debugging: print out the op being executed
; push ax
; call putc
; pop ax
; check what instruction this is. could possibly be worth doing this in
; a sparse jump table somewhere?
cmp al, "<"
je .left
cmp al, ">"
je .right
cmp al, "+"
je .add
cmp al, "-"
je .sub
cmp al, "."
je .out
cmp al, ","
je .in
cmp al, "["
je .loop_fwd
cmp al, "]"
je .loop_bwd
; didn't know what this, so we just ignore it. ignoring non-instruction
; chars allows us to have """comments"""
jmp .op_end
; pointer shift ops
.left: dec si
jmp .op_end
.right: inc si
jmp .op_end
; pointer modification ops. byte sized, so we get wrap-around.
.add: mov al, [bx+si]
inc al
mov [bx+si], al
jmp .op_end
.sub: mov al, [bx+si]
dec al
mov [bx+si], al
jmp .op_end
; I/O ops. note: in has no implicit echo
.in: call getc
; exit immediately if this is ^C
cmp al, `\x03`
je .end
mov [bx+si], al
jmp .op_end
.out: mov al, [bx+si]
push ax
call putc
add sp, 2
; forward and backward loops
;
; as mentioned at the top, these are implemented with checks for the
; cells content, so we avoid some double searching.
;
; essentially for both we just keep track of the parens we've
; encountered and keep going until we get to 0 indicating that we're
; at the matching paren, noting that .op_end will increment di so
; we take care to leave it in a sensible place.
.loop_fwd:
; if the value isn't zero, then we don't loop
mov al, [bx+si]
test al, al
jnz .op_end
xor cx, cx ; count of brackets passed
dec di
.fwd_next:
inc di
mov al, [di]
; if it is an opening bracket, count it
cmp al, "["
je .fwd_open
cmp al, "]"
je .fwd_close
jmp .fwd_next
.fwd_open:
inc cx
jmp .fwd_next
.fwd_close:
dec cx
jnz .fwd_next
jmp .op_end
.loop_bwd:
; zero value means no loop
mov al, [bx+si]
test al, al
jz .op_end
xor cx, cx ; count of brackets passed
inc di ; increment di so that we count the first bracket
.bwd_next:
dec di
mov al, [di]
cmp al, "["
je .bwd_open
cmp al, "]"
je .bwd_close
jmp .bwd_next
.bwd_close:
inc cx
jmp .bwd_next
.bwd_open:
dec cx
jnz .bwd_next
dec di
jmp .op_end
.op_end:
inc di
jmp .op
.end:
popa
mov sp, bp
pop bp
ret
; =============================================================================
; Program entry point and REPL
; =============================================================================
_start:
call clear_screen
push banner
call puts
add sp, 2
; loop, printing the prompt, getting input and interpreting it forever
.repl:
push prompt
call puts
add sp, 2
push inbuf
call gets
add sp, 2
push inbuf
call interpret
sub sp, 2
push `\r`
push sp
call puts
add sp, 4
jmp .repl
; we have an unconditional jump above, so we should never get here, but
; just in case we halt forever and if that somehow doesn't work we just
; loop infinitely.
;
; you'd hope one of those would work :)
cli
hlt
jmp $
banner: db `i386bf interpreter\n`, 0
prompt: db `bf > `, 0
; the input buffer into which programs are input
inbuf equ 0x500
; the memory that the interpreter will use to work on
memory equ 0x7e00
times 510 - ($ - $$) db 0
dw 0xaa55
|
# FILE: $File$
# AUTHOR: P. White
# CONTRIBUTORS: M. Reek, W. Carithers
# Alexander Kellermann Nieves
#
# DESCRIPTION:
# In this experiment, you will write some code in a pair of
# functions that are used to simplify a fraction.
#
# ARGUMENTS:
# None
#
# INPUT:
# The numerator and denominator of a fraction
#
# OUTPUT:
# The fraction in simplified form (ie 210/50 would be simplified
# to "4 and 1/5")
#
# REVISION HISTORY:
# Dec 13, 04 - P. White, created program
#
#
# CONSTANT DECLARATIONS
#
PRINT_INT = 1 # code for syscall to print integer
PRINT_STRING = 4 # code for syscall to print a string
READ_INT = 5 # code for syscall to read an int
#
# DATA DECLARATIONS
#
.data
into_msg:
.ascii "\n*************************\n"
.ascii "** Fraction Simplifier **\n"
.asciiz "*************************\n\n"
newline:
.asciiz "\n"
input_error:
.asciiz "\nError with previous input, try again.\n"
num_string:
.asciiz "\nEnter the Numerator of the fraction: "
den_string:
.asciiz "\nEnter the Denominator of the fraction: "
res_string:
.asciiz "\nThe simplified fraction is: "
and_string:
.asciiz " and "
div_string:
.asciiz "/"
#
# MAIN PROGRAM
#
.text
.align 2
.globl main
main:
addi $sp, $sp, -16 # space for return address/doubleword aligned
sw $ra, 12($sp) # store the ra on the stack
sw $s2, 8($sp)
sw $s1, 4($sp)
sw $s0, 0($sp)
la $a0, into_msg
jal print_string
ask_for_num:
la $a0, num_string
jal print_string
la $v0, READ_INT
syscall
move $s0, $v0 # s0 will be the numerator
slti $t0, $v0, 0
beq $t0, $zero, ask_for_den
la $a0, input_error
jal print_string
j ask_for_num
ask_for_den:
la $a0, den_string
jal print_string
la $v0, READ_INT
syscall
move $a1, $v0 # a1 will be the denominator
slti $t0, $v0, 1
beq $t0, $zero, den_good
la $a0, input_error
jal print_string
j ask_for_den
den_good:
move $a0, $s0 # copy the numerator into a0
jal simplify
move $s0, $v0 # save the numerator
move $s1, $v1 # save the denominator
move $s2, $t9 # save the integer part
la $a0, res_string
jal print_string
move $a0, $s2
li $v0, PRINT_INT
syscall
la $a0, and_string
jal print_string
move $a0, $s0
li $v0, PRINT_INT
syscall
la $a0, div_string
jal print_string
move $a0, $s1
li $v0, PRINT_INT
syscall
la $a0, newline
jal print_string
#
# Now exit the program.
#
lw $ra, 12($sp) # clean up stack
lw $s2, 8($sp)
lw $s1, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 16
jr $ra
#
# Name: simplify
#
# Description: Simplify a fraction.
#
# Arguments: a0: the original numerator
# a1: the original denominator
# Returns: v0: the simplified numerator
# v1: the simplified denominator
# t9: the simplified integer part
#
#######################################################################
# NOTE: this function uses a non-standard return register
# t9 will contain the integer part of the
# simplified fraction
#######################################################################
#
#
simplify:
addi $sp, $sp, -40 # allocate stack frame (on doubleword boundary)
sw $ra, 32($sp) # store the ra & s reg's on the stack
sw $s7, 28($sp)
sw $s6, 24($sp)
sw $s5, 20($sp)
sw $s4, 16($sp)
sw $s3, 12($sp)
sw $s2, 8($sp)
sw $s1, 4($sp)
sw $s0, 0($sp)
# ######################################
# ##### BEGIN STUDENT CODE BLOCK 1 #####
li $t9, 0 # Start the integer value at 0
add $s0, $a0, $zero # numerator stored in s0
add $s1, $a1, $zero # denominator store in s1
denominatorGreaterThanNumBegin:
slt $s7, $s1, $s0 # s7 is 1 when the denominator is less than the
# numerator
beq $s7, $zero, finishSimplifing
# This should break out of the loop when the
# denominator is no longer bigger than the
# numerator
sub $s0, $s0, $s1
addi $t9, 1
j denominatorGreaterThanNumBegin
finishSimplifing:
add $v0, $s0, $zero
add $v1, $s1, $zero
jal find_gcd # jump to our find_gcd function
beq $v0, $v1, oneOverOne
div $v1, $v0 # use our GCD to calculate a simplified answer
mflo $v1 # denominator
div $v0, $v0
mflo $v0 # numerator
j done
oneOverOne:
addi $t9, 1 # We know that we need to increment
li $v0, 0 # the counter by 1 since it's 1/1
li $v1, 1
j done # finish execution
done:
# ###### END STUDENT CODE BLOCK 1 ######
# ######################################
simplify_done:
lw $ra, 32($sp) # restore the ra & s reg's from the stack
lw $s7, 28($sp)
lw $s6, 24($sp)
lw $s5, 20($sp)
lw $s4, 16($sp)
lw $s3, 12($sp)
lw $s2, 8($sp)
lw $s1, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 40 # clean up stack
jr $ra
#
# Name: find_gcd
#
# Description: computes the GCD of the two inputed numbers
# Arguments: a0 The first number
# a1 The second number
# Returns: v0 The GCD of a0 and a1.
#
find_gcd:
addi $sp, $sp, -40 # allocate stackframe (doubleword aligned)
sw $ra, 32($sp) # store the ra & s reg's on the stack
sw $s7, 28($sp)
sw $s6, 24($sp)
sw $s5, 20($sp)
sw $s4, 16($sp)
sw $s3, 12($sp)
sw $s2, 8($sp)
sw $s1, 4($sp)
sw $s0, 0($sp)
# ######################################
# ##### BEGIN STUDENT CODE BLOCK 2 #####
put_in_safety:
move $s1, $a1 # s1 contains denominator
move $s0, $a0 # s0 contains numerator
li $s3, -1 # store -1 for multiplication
find_gcdstart:
beq $s0, $s1, gcdloopfinish # finish if two nums are the same
sub $t5, $s1, $s0 # t5 = s0 - s1
slt $t6, $t5, $zero # t6 is 0 when t5 is negative
bne $t6, $zero, gcd_make_po # t5 will now be positive
gcd_middle:
slt $t7, $s1, $s0 # is num 2 < num 1
bne $t7, $zero, gcd_set_s0 #
move $s1, $t5 # num 2 = D
j find_gcdstart
gcd_set_s0:
move $s0, $t5 # num 1 = D
j find_gcdstart
gcd_make_po:
mul $t5, $s3 # turn number positive ($s3 = -1)
j gcd_middle # jump back to middle of loop
gcdloopfinish:
move $v0, $s0 # exits
# ###### END STUDENT CODE BLOCK 2 ######
# ######################################
find_gcd_done:
lw $ra, 32($sp) # restore the ra & s reg's from the stack
lw $s7, 28($sp)
lw $s6, 24($sp)
lw $s5, 20($sp)
lw $s4, 16($sp)
lw $s3, 12($sp)
lw $s2, 8($sp)
lw $s1, 4($sp)
lw $s0, 0($sp)
addi $sp, $sp, 40 # clean up the stack
jr $ra
#
# Name; print_number
#
# Description: This routine reads a number then a newline to stdout
# Arguments: a0: the number to print
# Returns: nothing
#
print_number:
li $v0, PRINT_INT
syscall #print a0
la $a0, newline
li $v0, PRINT_STRING
syscall #print a newline
jr $ra
#
# Name; print_string
#
# Description: This routine prints out a string pointed to by a0
# Arguments: a0: a pointer to the string to print
# Returns: nothing
#
print_string:
li $v0, PRINT_STRING
syscall #print a0
jr $ra
|
//=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include <Elastos.CoreLibrary.IO.h>
#include "Elastos.Droid.Content.h"
#include "elastos/droid/ext/frameworkdef.h"
#include "elastos/droid/os/CEnvironment.h"
#include "elastos/droid/os/Environment.h"
namespace Elastos {
namespace Droid {
namespace Os {
CAR_INTERFACE_IMPL(CEnvironment, Singleton, IEnvironment)
CAR_SINGLETON_IMPL(CEnvironment)
ECode CEnvironment::GetRootDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetRootDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetOemDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetOemDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetVendorDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetVendorDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetPrebundledDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetPrebundledDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetSystemSecureDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetSystemSecureDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetSecureDataDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetSecureDataDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetMediaStorageDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetMediaStorageDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetUserSystemDirectory(
/* [in] */ Int32 userId,
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetUserSystemDirectory(userId);
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetUserConfigDirectory(
/* [in] */ Int32 userId,
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetUserConfigDirectory(userId);
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::IsEncryptedFilesystemEnabled(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result)
*result = Environment::IsEncryptedFilesystemEnabled();
return NOERROR;
}
ECode CEnvironment::GetDataDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetDataDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetExternalStorageDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetExternalStorageDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetSecondaryStorageDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetSecondaryStorageDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetLegacyExternalStorageDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetLegacyExternalStorageDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetLegacyExternalStorageObbDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetLegacyExternalStorageObbDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetEmulatedStorageSource(
/* [in] */ Int32 userId,
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetEmulatedStorageSource(userId);
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetEmulatedStorageObbSource(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetEmulatedStorageObbSource();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetExternalStoragePublicDirectory(
/* [in] */ const String& type,
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetExternalStoragePublicDirectory(type);
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAndroidDataDirs(
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAndroidDataDirs();
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAppDataDirs(
/* [in] */ const String& packageName,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAppDataDirs(packageName);
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAppMediaDirs(
/* [in] */ const String& packageName,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAppMediaDirs(packageName);
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAppObbDirs(
/* [in] */ const String& packageName,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAppObbDirs(packageName);
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAppFilesDirs(
/* [in] */ const String& packageName,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAppFilesDirs(packageName);
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildExternalStorageAppCacheDirs(
/* [in] */ const String& packageName,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr< ArrayOf<IFile*> > f = Environment::BuildExternalStorageAppCacheDirs(packageName);
*files = f;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::GetDownloadCacheDirectory(
/* [out] */ IFile** dir)
{
VALIDATE_NOT_NULL(dir)
AutoPtr<IFile> f = Environment::GetDownloadCacheDirectory();
*dir = f;
REFCOUNT_ADD(*dir)
return NOERROR;
}
ECode CEnvironment::GetExternalStorageState(
/* [out] */ String* state)
{
VALIDATE_NOT_NULL(state)
*state = Environment::GetExternalStorageState();
return NOERROR;
}
ECode CEnvironment::GetStorageState(
/* [in] */ IFile* path,
/* [out] */ String* state)
{
VALIDATE_NOT_NULL(state)
*state = Environment::GetStorageState(path);
return NOERROR;
}
ECode CEnvironment::GetSecondaryStorageState(
/* [out] */ String* state)
{
VALIDATE_NOT_NULL(state)
*state = Environment::GetSecondaryStorageState();
return NOERROR;
}
ECode CEnvironment::GetExternalStorageState(
/* [in] */ IFile* path,
/* [out] */ String* state)
{
VALIDATE_NOT_NULL(state)
*state = Environment::GetExternalStorageState(path);
return NOERROR;
}
ECode CEnvironment::IsExternalStorageRemovable(
/* [in] */ IFile* path,
/* [out] */ Boolean* isRemovable)
{
VALIDATE_NOT_NULL(isRemovable)
*isRemovable = Environment::IsExternalStorageRemovable(path);
return NOERROR;
}
ECode CEnvironment::IsNoEmulatedStorageExist(
/* [out] */ Boolean* isExist)
{
VALIDATE_NOT_NULL(isExist)
*isExist = Environment::IsNoEmulatedStorageExist();
return NOERROR;
}
ECode CEnvironment::IsExternalStorageRemovable(
/* [out] */ Boolean* isRemovable)
{
VALIDATE_NOT_NULL(isRemovable)
*isRemovable = Environment::IsExternalStorageRemovable();
return NOERROR;
}
ECode CEnvironment::IsExternalStorageEmulated(
/* [out] */ Boolean* isEmulated)
{
VALIDATE_NOT_NULL(isEmulated)
*isEmulated = Environment::IsExternalStorageEmulated();
return NOERROR;
}
ECode CEnvironment::IsExternalStorageEmulated(
/* [in] */ IFile* path,
/* [out] */ Boolean* isEmulated)
{
VALIDATE_NOT_NULL(isEmulated)
*isEmulated = Environment::IsExternalStorageEmulated(path);
return NOERROR;
}
ECode CEnvironment::SetUserRequired(
/* [in] */ Boolean userRequired)
{
return Environment::SetUserRequired(userRequired);
}
ECode CEnvironment::BuildPaths(
/* [in] */ ArrayOf<IFile*>* base,
/* [in] */ ArrayOf<String>* segments,
/* [out, callee] */ ArrayOf<IFile*>** files)
{
VALIDATE_NOT_NULL(files)
AutoPtr<ArrayOf<IFile*> > tmp = Environment::BuildPaths(base, segments);
*files = tmp;
REFCOUNT_ADD(*files)
return NOERROR;
}
ECode CEnvironment::BuildPath(
/* [in] */ IFile* base,
/* [in] */ ArrayOf<String>* segments,
/* [out] */ IFile** file)
{
VALIDATE_NOT_NULL(file)
AutoPtr<IFile> tmp = Environment::BuildPath(base, segments);
*file = tmp;
REFCOUNT_ADD(*file)
return NOERROR;
}
ECode CEnvironment::MaybeTranslateEmulatedPathToInternal(
/* [in] */ IFile* path,
/* [out] */ IFile** file)
{
VALIDATE_NOT_NULL(file)
AutoPtr<IFile> tmp = Environment::MaybeTranslateEmulatedPathToInternal(path);
*file = tmp;
REFCOUNT_ADD(*file)
return NOERROR;
}
} // namespace Os
} // namespace Droid
} // namespace Elastos
|
#include <range/v3/core.hpp>
#include <range/v3/view/tokenize.hpp>
#include "../simple_test.hpp"
#include "../test_utils.hpp"
int main()
{
using namespace ranges;
std::string txt{"abc\ndef\tghi"};
const std::regex rx{R"delim(([\w]+))delim"};
auto&& rng = txt | view::tokenize(rx,1);
const auto& crng = txt | view::tokenize(rx,1);
::check_equal(rng, {"abc","def","ghi"});
::check_equal(crng, {"abc","def","ghi"});
::has_type<const std::sub_match<std::string::iterator>&>(*ranges::begin(rng));
::has_type<const std::sub_match<std::string::iterator>&>(*ranges::begin(crng));
::models<concepts::BoundedRange>(rng);
::models<concepts::ForwardRange>(rng);
::models_not<concepts::BidirectionalRange>(rng);
::models_not<concepts::SizedRange>(rng);
::models_not<concepts::OutputRange>(rng);
::models<concepts::BoundedRange>(crng);
::models<concepts::ForwardRange>(crng);
::models_not<concepts::BidirectionalRange>(crng);
::models_not<concepts::SizedRange>(crng);
::models_not<concepts::OutputRange>(crng);
// ::models<concepts::View>(rng);
// ::models<concepts::View>(crng);
return test_result();
}
|
db 0 ; species ID placeholder
db 90, 100, 90, 90, 125, 85
; hp atk def spd sat sdf
db FIRE, FLYING ; type
db 3 ; catch rate
db 217 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_UNKNOWN ; gender ratio
db 100 ; unknown 1
db 80 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/moltres/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_NONE, EGG_NONE ; egg groups
; tm/hm learnset
tmhm CURSE, ROAR, TOXIC, ROCK_SMASH, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SANDSTORM, FIRE_BLAST, SWIFT, DETECT, REST, STEEL_WING, FLY, FLAMETHROWER
; end
|
// Copyright 2020 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* This header must be included by all rclcpp headers which declare symbols
* which are defined in the rclcpp library. When not building the rclcpp
* library, i.e. when using the headers in other package's code, the contents
* of this header change the visibility of certain symbols which the rclcpp
* library cannot have, but the consuming code must have inorder to link.
*/
#ifndef RCLCPP_COMPONENTS__VISIBILITY_CONTROL_HPP_
#define RCLCPP_COMPONENTS__VISIBILITY_CONTROL_HPP_
// This logic was borrowed (then namespaced) from the examples on the gcc wiki:
// https://gcc.gnu.org/wiki/Visibility
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define RCLCPP_COMPONENTS_EXPORT __attribute__ ((dllexport))
#define RCLCPP_COMPONENTS_IMPORT __attribute__ ((dllimport))
#else
#define RCLCPP_COMPONENTS_EXPORT __declspec(dllexport)
#define RCLCPP_COMPONENTS_IMPORT __declspec(dllimport)
#endif
#ifdef RCLCPP_COMPONENTS_BUILDING_LIBRARY
#define RCLCPP_COMPONENTS_PUBLIC RCLCPP_COMPONENTS_EXPORT
#else
#define RCLCPP_COMPONENTS_PUBLIC RCLCPP_COMPONENTS_IMPORT
#endif
#define RCLCPP_COMPONENTS_PUBLIC_TYPE RCLCPP_COMPONENTS_PUBLIC
#define RCLCPP_COMPONENTS_LOCAL
#else
#define RCLCPP_COMPONENTS_EXPORT __attribute__ ((visibility("default")))
#define RCLCPP_COMPONENTS_IMPORT
#if __GNUC__ >= 4
#define RCLCPP_COMPONENTS_PUBLIC __attribute__ ((visibility("default")))
#define RCLCPP_COMPONENTS_LOCAL __attribute__ ((visibility("hidden")))
#else
#define RCLCPP_COMPONENTS_PUBLIC
#define RCLCPP_COMPONENTS_LOCAL
#endif
#define RCLCPP_COMPONENTS_PUBLIC_TYPE
#endif
#endif // RCLCPP_COMPONENTS__VISIBILITY_CONTROL_HPP_
|
/*
* Copyright 2018-2021 Mahdi Khanalizadeh
*
* 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.
*/
.intel_syntax noprefix
.global linux_syscall5
linux_syscall5:
push edi
push esi
push ebx
mov eax, [esp+36] # arg6 -> #
mov edi, [esp+32] # arg5 -> arg5
mov esi, [esp+28] # arg4 -> arg4
mov edx, [esp+24] # arg3 -> arg3
mov ecx, [esp+20] # arg2 -> arg2
mov ebx, [esp+16] # arg1 -> arg1
int 0x80
pop ebx
pop esi
pop edi
ret
|
;==============================================================================
; Constants
PlayerFrame = 1
PlayerHorizontalSpeed = 2
PlayerVerticalSpeed = 1
PlayerXMinHigh = 0 ; 0*256 + 24 = 24 minX
PlayerXMinLow = 24
PlayerXMaxHigh = 1 ; 1*256 + 64 = 320 maxX
PlayerXMaxLow = 64
PlayerYMin = 180
PlayerYMax = 229
;===============================================================================
; Variables
playerSprite byte 0
playerXHigh byte 0
playerXLow byte 175
playerY byte 229
playerXChar byte 0
playerXOffset byte 0
playerYChar byte 0
playerYOffset byte 0
;===============================================================================
; Macros/Subroutines
gamePlayerInit
LIBSPRITE_ENABLE_AV playerSprite, True
LIBSPRITE_SETFRAME_AV playerSprite, PlayerFrame
LIBSPRITE_SETCOLOR_AV playerSprite, LightGray
LIBSPRITE_MULTICOLORENABLE_AV playerSprite, True
rts
;===============================================================================
gamePlayerUpdate
jsr gamePlayerUpdatePosition
jsr gamePlayerUpdateFiring
rts
;==============================================================================
gamePlayerUpdateFiring
; do fire after the ship has been clamped to position
; so that the bullet lines up
LIBINPUT_GETFIREPRESSED
bne gPUFNofire
GAMEBULLETS_FIRE_AAAVV playerXChar, playerXOffset, playerYChar, White, True
gPUFNofire
rts
;===============================================================================
gamePlayerUpdatePosition
LIBINPUT_GETHELD GameportLeftMask
bne gPUPRight
LIBMATH_SUB16BIT_AAVVAA playerXHigh, PlayerXLow, 0, PlayerHorizontalSpeed, playerXHigh, PlayerXLow
gPUPRight
LIBINPUT_GETHELD GameportRightMask
bne gPUPUp
LIBMATH_ADD16BIT_AAVVAA playerXHigh, PlayerXLow, 0, PlayerHorizontalSpeed, playerXHigh, PlayerXLow
gPUPUp
LIBINPUT_GETHELD GameportUpMask
bne gPUPDown
LIBMATH_SUB8BIT_AVA PlayerY, PlayerVerticalSpeed, PlayerY
gPUPDown
LIBINPUT_GETHELD GameportDownMask
bne gPUPEndmove
LIBMATH_ADD8BIT_AVA PlayerY, PlayerVerticalSpeed, PlayerY
gPUPEndmove
; clamp the player x position
LIBMATH_MIN16BIT_AAVV playerXHigh, playerXLow, PlayerXMaxHigh, PLayerXMaxLow
LIBMATH_MAX16BIT_AAVV playerXHigh, playerXLow, PlayerXMinHigh, PLayerXMinLow
; clamp the player y position
LIBMATH_MIN8BIT_AV playerY, PlayerYMax
LIBMATH_MAX8BIT_AV playerY, PlayerYMin
; set the sprite position
LIBSPRITE_SETPOSITION_AAAA playerSprite, playerXHigh, PlayerXLow, PlayerY
; update the player char positions
LIBSCREEN_PIXELTOCHAR_AAVAVAAAA playerXHigh, playerXLow, 12, playerY, 40, playerXChar, playerXOffset, playerYChar, playerYOffset
rts
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/browser/aw_browser_context.h"
#include "android_webview/browser/aw_contents.h"
#include "android_webview/browser/aw_contents_io_thread_client.h"
#include "android_webview/browser/aw_safe_browsing_config_helper.h"
#include "android_webview/browser/aw_safe_browsing_whitelist_manager.h"
#include "android_webview/browser/net/aw_url_request_context_getter.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "base/callback.h"
#include "components/google/core/browser/google_util.h"
#include "components/security_interstitials/core/urls.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/url_constants.h"
#include "jni/AwContentsStatics_jni.h"
#include "net/cert/cert_database.h"
using base::android::AttachCurrentThread;
using base::android::ConvertJavaStringToUTF8;
using base::android::JavaParamRef;
using base::android::JavaRef;
using base::android::ScopedJavaGlobalRef;
using base::android::ScopedJavaLocalRef;
using content::BrowserThread;
namespace android_webview {
namespace {
void ClientCertificatesCleared(const JavaRef<jobject>& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
Java_AwContentsStatics_clientCertificatesCleared(env, callback);
}
void NotifyClientCertificatesChanged() {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
net::CertDatabase::GetInstance()->NotifyObserversCertDBChanged();
}
void SafeBrowsingWhitelistAssigned(const JavaRef<jobject>& callback,
bool success) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
JNIEnv* env = AttachCurrentThread();
Java_AwContentsStatics_safeBrowsingWhitelistAssigned(env, callback, success);
}
} // namespace
// static
ScopedJavaLocalRef<jstring>
JNI_AwContentsStatics_GetSafeBrowsingPrivacyPolicyUrl(
JNIEnv* env,
const JavaParamRef<jclass>&) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
GURL privacy_policy_url(
security_interstitials::kSafeBrowsingPrivacyPolicyUrl);
std::string locale =
AwBrowserContext::GetDefault()->GetSafeBrowsingUIManager()->app_locale();
privacy_policy_url =
google_util::AppendGoogleLocaleParam(privacy_policy_url, locale);
return base::android::ConvertUTF8ToJavaString(env, privacy_policy_url.spec());
}
// static
void JNI_AwContentsStatics_ClearClientCertPreferences(
JNIEnv* env,
const JavaParamRef<jclass>&,
const JavaParamRef<jobject>& callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
BrowserThread::PostTaskAndReply(
BrowserThread::IO, FROM_HERE,
base::BindOnce(&NotifyClientCertificatesChanged),
base::BindOnce(&ClientCertificatesCleared,
ScopedJavaGlobalRef<jobject>(env, callback)));
}
// static
ScopedJavaLocalRef<jstring> JNI_AwContentsStatics_GetUnreachableWebDataUrl(
JNIEnv* env,
const JavaParamRef<jclass>&) {
return base::android::ConvertUTF8ToJavaString(
env, content::kUnreachableWebDataURL);
}
// static
ScopedJavaLocalRef<jstring> JNI_AwContentsStatics_GetProductVersion(
JNIEnv* env,
const JavaParamRef<jclass>&) {
return base::android::ConvertUTF8ToJavaString(
env, version_info::GetVersionNumber());
}
// static
jboolean JNI_AwContentsStatics_GetSafeBrowsingEnabledByManifest(
JNIEnv* env,
const JavaParamRef<jclass>&) {
return AwSafeBrowsingConfigHelper::GetSafeBrowsingEnabledByManifest();
}
// static
void JNI_AwContentsStatics_SetSafeBrowsingEnabledByManifest(
JNIEnv* env,
const JavaParamRef<jclass>&,
jboolean enable) {
AwSafeBrowsingConfigHelper::SetSafeBrowsingEnabledByManifest(enable);
}
// static
void JNI_AwContentsStatics_SetSafeBrowsingWhitelist(
JNIEnv* env,
const JavaParamRef<jclass>&,
const JavaParamRef<jobjectArray>& jrules,
const JavaParamRef<jobject>& callback) {
std::vector<std::string> rules;
base::android::AppendJavaStringArrayToStringVector(env, jrules, &rules);
AwSafeBrowsingWhitelistManager* whitelist_manager =
AwBrowserContext::GetDefault()->GetSafeBrowsingWhitelistManager();
whitelist_manager->SetWhitelistOnUIThread(
std::move(rules),
base::BindOnce(&SafeBrowsingWhitelistAssigned,
ScopedJavaGlobalRef<jobject>(env, callback)));
}
// static
void JNI_AwContentsStatics_SetServiceWorkerIoThreadClient(
JNIEnv* env,
const JavaParamRef<jclass>&,
const base::android::JavaParamRef<jobject>& io_thread_client,
const base::android::JavaParamRef<jobject>& browser_context) {
AwContentsIoThreadClient::SetServiceWorkerIoThreadClient(io_thread_client,
browser_context);
}
// static
void JNI_AwContentsStatics_SetCheckClearTextPermitted(
JNIEnv* env,
const JavaParamRef<jclass>&,
jboolean permitted) {
AwURLRequestContextGetter::set_check_cleartext_permitted(permitted);
}
} // namespace android_webview
|
#include <odyssey/protocol/asset.hpp>
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
/*
The bounds on asset serialization are as follows:
index : field
0 : decimals
1..6 : symbol
7 : \0
*/
namespace odyssey { namespace protocol {
typedef boost::multiprecision::int128_t int128_t;
uint8_t asset::decimals()const
{
auto a = (const char*)&symbol;
uint8_t result = uint8_t( a[0] );
FC_ASSERT( result < 15 );
return result;
}
void asset::set_decimals(uint8_t d)
{
FC_ASSERT( d < 15 );
auto a = (char*)&symbol;
a[0] = d;
}
std::string asset::symbol_name()const
{
auto a = (const char*)&symbol;
FC_ASSERT( a[7] == 0 );
return &a[1];
}
int64_t asset::precision()const
{
static int64_t table[] = {
1, 10, 100, 1000, 10000,
100000, 1000000, 10000000, 100000000ll,
1000000000ll, 10000000000ll,
100000000000ll, 1000000000000ll,
10000000000000ll, 100000000000000ll
};
uint8_t d = decimals();
return table[ d ];
}
string asset::to_string()const
{
int64_t prec = precision();
string result = fc::to_string(amount.value / prec);
if( prec > 1 )
{
auto fract = amount.value % prec;
// prec is a power of ten, so for example when working with
// 7.005 we have fract = 5, prec = 1000. So prec+fract=1005
// has the correct number of zeros and we can simply trim the
// leading 1.
result += "." + fc::to_string(prec + fract).erase(0,1);
}
return result + " " + symbol_name();
}
asset asset::from_string( const string& from )
{
try
{
string s = fc::trim( from );
auto space_pos = s.find( " " );
auto dot_pos = s.find( "." );
FC_ASSERT( space_pos != std::string::npos );
asset result;
result.symbol = uint64_t(0);
auto sy = (char*)&result.symbol;
if( dot_pos != std::string::npos )
{
FC_ASSERT( space_pos > dot_pos );
auto intpart = s.substr( 0, dot_pos );
auto fractpart = "1" + s.substr( dot_pos + 1, space_pos - dot_pos - 1 );
result.set_decimals( fractpart.size() - 1 );
result.amount = fc::to_int64( intpart );
result.amount.value *= result.precision();
result.amount.value += fc::to_int64( fractpart );
result.amount.value -= result.precision();
}
else
{
auto intpart = s.substr( 0, space_pos );
result.amount = fc::to_int64( intpart );
result.set_decimals( 0 );
}
auto symbol = s.substr( space_pos + 1 );
size_t symbol_size = symbol.size();
if( symbol_size > 0 )
{
FC_ASSERT( symbol_size <= 6 );
memcpy( sy+1, symbol.c_str(), symbol_size );
}
return result;
}
FC_CAPTURE_AND_RETHROW( (from) )
}
bool operator == ( const price& a, const price& b )
{
if( std::tie( a.base.symbol, a.quote.symbol ) != std::tie( b.base.symbol, b.quote.symbol ) )
return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult == bmult;
}
bool operator < ( const price& a, const price& b )
{
if( a.base.symbol < b.base.symbol ) return true;
if( a.base.symbol > b.base.symbol ) return false;
if( a.quote.symbol < b.quote.symbol ) return true;
if( a.quote.symbol > b.quote.symbol ) return false;
const auto amult = uint128_t( b.quote.amount.value ) * a.base.amount.value;
const auto bmult = uint128_t( a.quote.amount.value ) * b.base.amount.value;
return amult < bmult;
}
bool operator <= ( const price& a, const price& b )
{
return (a == b) || (a < b);
}
bool operator != ( const price& a, const price& b )
{
return !(a == b);
}
bool operator > ( const price& a, const price& b )
{
return !(a <= b);
}
bool operator >= ( const price& a, const price& b )
{
return !(a < b);
}
asset operator * ( const asset& a, const price& b )
{
if( a.symbol_name() == b.base.symbol_name() )
{
FC_ASSERT( b.base.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.quote.amount.value)/b.base.amount.value;
FC_ASSERT( result.hi == 0 );
return asset( result.to_uint64(), b.quote.symbol );
}
else if( a.symbol_name() == b.quote.symbol_name() )
{
FC_ASSERT( b.quote.amount.value > 0 );
uint128_t result = (uint128_t(a.amount.value) * b.base.amount.value)/b.quote.amount.value;
FC_ASSERT( result.hi == 0 );
return asset( result.to_uint64(), b.base.symbol );
}
FC_THROW_EXCEPTION( fc::assert_exception, "invalid asset * price", ("asset",a)("price",b) );
}
price operator / ( const asset& base, const asset& quote )
{ try {
FC_ASSERT( base.symbol_name() != quote.symbol_name() );
return price{ base, quote };
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
price price::max( asset_symbol_type base, asset_symbol_type quote ) { return asset( share_type(ODYSSEY_MAX_SHARE_SUPPLY), base ) / asset( share_type(1), quote); }
price price::min( asset_symbol_type base, asset_symbol_type quote ) { return asset( 1, base ) / asset( ODYSSEY_MAX_SHARE_SUPPLY, quote); }
bool price::is_null() const { return *this == price(); }
void price::validate() const
{ try {
FC_ASSERT( base.amount > share_type(0) );
FC_ASSERT( quote.amount > share_type(0) );
FC_ASSERT( base.symbol_name() != quote.symbol_name() );
} FC_CAPTURE_AND_RETHROW( (base)(quote) ) }
} } // odyssey::protocol
|
; ----- void __CALLEE__ xordrawb(int x, int y, int h, int v)
IF !__CPU_INTEL__ & !__CPU_GBZ80__
SECTION code_graphics
PUBLIC xordrawb
PUBLIC _xordrawb
EXTERN asm_xordrawb
.xordrawb
._xordrawb
push ix
ld ix,2
add ix,sp
ld c,(ix+2)
ld b,(ix+4)
ld l,(ix+6)
ld h,(ix+8)
pop ix
jp asm_xordrawb
ENDIF
|
;
; Jupiter ACE pseudo graphics routines
; Version for the 2x3 graphics symbols (UDG redefined)
;
;
; Written by Stefano Bodrato 2014
;
;
; Get pixel at (x,y) coordinate.
;
;
; $Id: pointxy.asm,v 1.2 2016-11-21 11:18:38 stefano Exp $
;
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC pointxy
EXTERN div3
EXTERN __gfx_coords
;EXTERN base_graphics
.pointxy
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
dec a
dec a
push bc
push de
push hl
ld (__gfx_coords),hl
;push bc
ld c,a ; y
ld b,h ; x
push bc
ld hl,div3
ld d,0
ld e,c
inc e
add hl,de
ld a,(hl)
ld c,a ; y/3
srl b ; x/2
ld a,c
ld c,b ; !!
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
;ld hl,(base_graphics)
ld hl,$F000
ld b,a ; keep y/3
and a
jr z,r_zero
ld de,maxx/2 ; microbee is 64 columns
.r_loop
add hl,de
dec a
jr nz,r_loop
.r_zero ld d,0
ld e,c
add hl,de
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
ld a,(hl) ; get current symbol from screen
cp 128
jr nc,noblank
ld a,128
.noblank
sub 128
ld e,a ; ..and its copy
pop hl ; restore x,y (y=h, x=l)
ld a,l
inc a
inc a
sub b
sub b
sub b ; we get the remainder of y/3
ld l,a
ld a,1 ; the pixel we want to draw
jr z,iszero
bit 0,l
jr nz,is1
add a,a
add a,a
.is1
add a,a
add a,a
.iszero
bit 0,h
jr nz,evenrow
add a,a ; move down the bit
.evenrow
and e
pop hl
pop de
pop bc
ret
|
COMMENT @----------------------------------------------------------------------
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: GeoWrite
FILE: Main/mainManager.asm
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 2/92 Initial version
DESCRIPTION:
This file contains the process class for the GeoWrite application.
$Id: mainManager.asm,v 1.1 97/04/04 15:57:05 newdeal Exp $
------------------------------------------------------------------------------@
;------------------------------------------------------------------------------
; Common GEODE stuff
;------------------------------------------------------------------------------
include writeGeode.def
include writeConstant.def
include writeProcess.def
include writeDocument.def
include writeApplication.def
include writeArticle.def
if _BATCH_RTF
include writeBatchExport.def
include writeSuperImpex.def
endif
include flowRegion.def
include initfile.def
include timedate.def ; TimerGetDateAndTime
include Objects/Text/tCtrlC.def
;------------------------------------------------------------------------------
; Code
;------------------------------------------------------------------------------
include mainProcess.asm
include mainApp.asm
include mainAppUI.asm
if _ABBREVIATED_PHRASE
include mainAbbrev.asm
endif
|
; ----------------------------------------------------------------------------------------
; Writes "Hello, World" to the console using only system calls. Runs on 64-bit Linux only.
; To assemble and run:
;
; nasm -felf64 hello.asm && ld hello.o && ./a.out
; ----------------------------------------------------------------------------------------
global _start
section .text
_start: mov rax, 1 ; system call for write
mov rdi, 1 ; file handle 1 is stdout
mov rsi, message ; address of string to output
mov rdx, 13 ; number of bytes
syscall ; invoke operating system to do the write
mov rax, 60 ; system call for exit
xor rdi, rdi ; exit code 0
syscall ; invoke operating system to exit
section .data
message: db "Hello, World", 10 ; note the newline at the end |
; [FORMAT "WCOFF"]
[BITS 32]
GLOBAL io_hlt ; 程序中包含函数名
[SECTION .text]
io_hlt: ; void io_hlt(void);
HLT
RET
|
#include "engine.h"
#define MAXLIGHTMAPTASKS 4096
#define LIGHTMAPBUFSIZE (2*1024*1024)
struct lightmapinfo;
struct lightmaptask;
struct lightmapworker
{
uchar *buf;
int bufstart, bufused;
lightmapinfo *firstlightmap, *lastlightmap, *curlightmaps;
cube *c;
cubeext *ext;
uchar *colorbuf;
bvec *raybuf;
uchar *ambient, *blur;
vec *colordata, *raydata;
int type, bpp, w, h, orient, rotate;
VSlot *vslot;
Slot *slot;
vector<const extentity *> lights;
ShadowRayCache *shadowraycache;
BlendMapCache *blendmapcache;
bool needspace, doneworking;
SDL_cond *spacecond;
SDL_Thread *thread;
lightmapworker();
~lightmapworker();
void reset();
bool setupthread();
void cleanupthread();
static int work(void *data);
};
struct lightmapinfo
{
lightmapinfo *next;
cube *c;
uchar *colorbuf;
bvec *raybuf;
bool packed;
int type, w, h, bpp, bufsize, surface, layers;
};
struct lightmaptask
{
ivec o;
int size, usefaces, progress;
cube *c;
cubeext *ext;
lightmapinfo *lightmaps;
lightmapworker *worker;
};
struct lightmapext
{
cube *c;
cubeext *ext;
};
static vector<lightmapworker *> lightmapworkers;
static vector<lightmaptask> lightmaptasks[2];
static vector<lightmapext> lightmapexts;
static int packidx = 0, allocidx = 0;
static SDL_mutex *lightlock = NULL, *tasklock = NULL;
static SDL_cond *fullcond = NULL, *emptycond = NULL;
int lightmapping = 0;
vector<LightMap> lightmaps;
VARR(lightprecision, 1, 32, 1024);
VARR(lighterror, 1, 8, 16);
VARR(bumperror, 1, 3, 16);
VARR(lightlod, 0, 0, 10);
bvec ambientcolor(0x19, 0x19, 0x19), skylightcolor(0, 0, 0);
HVARFR(ambient, 1, 0x191919, 0xFFFFFF,
{
if(ambient <= 255) ambient |= (ambient<<8) | (ambient<<16);
ambientcolor = bvec((ambient>>16)&0xFF, (ambient>>8)&0xFF, ambient&0xFF);
});
HVARFR(skylight, 0, 0, 0xFFFFFF,
{
if(skylight <= 255) skylight |= (skylight<<8) | (skylight<<16);
skylightcolor = bvec((skylight>>16)&0xFF, (skylight>>8)&0xFF, skylight&0xFF);
});
extern void setupsunlight();
bvec sunlightcolor(0, 0, 0);
HVARFR(sunlight, 0, 0, 0xFFFFFF,
{
if(sunlight <= 255) sunlight |= (sunlight<<8) | (sunlight<<16);
sunlightcolor = bvec((sunlight>>16)&0xFF, (sunlight>>8)&0xFF, sunlight&0xFF);
setupsunlight();
});
FVARFR(sunlightscale, 0, 1, 16, setupsunlight());
vec sunlightdir(0, 0, 1);
extern void setsunlightdir();
VARFR(sunlightyaw, 0, 0, 360, setsunlightdir());
VARFR(sunlightpitch, -90, 90, 90, setsunlightdir());
void setsunlightdir()
{
sunlightdir = vec(sunlightyaw*RAD, sunlightpitch*RAD);
loopk(3) if(fabs(sunlightdir[k]) < 1e-5f) sunlightdir[k] = 0;
sunlightdir.normalize();
setupsunlight();
}
entity sunlightent;
void setupsunlight()
{
memset(&sunlightent, 0, sizeof(sunlightent));
sunlightent.type = ET_LIGHT;
sunlightent.attr1 = 0;
sunlightent.attr2 = int(sunlightcolor.x*sunlightscale);
sunlightent.attr3 = int(sunlightcolor.y*sunlightscale);
sunlightent.attr4 = int(sunlightcolor.z*sunlightscale);
float dist = min(min(sunlightdir.x ? 1/fabs(sunlightdir.x) : 1e16f, sunlightdir.y ? 1/fabs(sunlightdir.y) : 1e16f), sunlightdir.z ? 1/fabs(sunlightdir.z) : 1e16f);
sunlightent.o = vec(sunlightdir).mul(dist*worldsize).add(vec(worldsize/2, worldsize/2, worldsize/2));
}
VARR(skytexturelight, 0, 1, 1);
static const surfaceinfo brightsurfaces[6] =
{
brightsurface,
brightsurface,
brightsurface,
brightsurface,
brightsurface,
brightsurface
};
void brightencube(cube &c)
{
if(!c.ext) newcubeext(c, 0, false);
memcpy(c.ext->surfaces, brightsurfaces, sizeof(brightsurfaces));
}
void setsurfaces(cube &c, const surfaceinfo *surfs, const vertinfo *verts, int numverts)
{
if(!c.ext || c.ext->maxverts < numverts) newcubeext(c, numverts, false);
memcpy(c.ext->surfaces, surfs, sizeof(c.ext->surfaces));
memcpy(c.ext->verts(), verts, numverts*sizeof(vertinfo));
}
void setsurface(cube &c, int orient, const surfaceinfo &src, const vertinfo *srcverts, int numsrcverts)
{
int dstoffset = 0;
if(!c.ext) newcubeext(c, numsrcverts, true);
else
{
int numbefore = 0, beforeoffset = 0;
loopi(orient)
{
surfaceinfo &surf = c.ext->surfaces[i];
int numverts = surf.totalverts();
if(!numverts) continue;
numbefore += numverts;
beforeoffset = surf.verts + numverts;
}
int numafter = 0, afteroffset = c.ext->maxverts;
for(int i = 5; i > orient; i--)
{
surfaceinfo &surf = c.ext->surfaces[i];
int numverts = surf.totalverts();
if(!numverts) continue;
numafter += numverts;
afteroffset = surf.verts;
}
if(afteroffset - beforeoffset >= numsrcverts) dstoffset = beforeoffset;
else
{
cubeext *ext = c.ext;
if(numbefore + numsrcverts + numafter > c.ext->maxverts)
{
ext = growcubeext(c.ext, numbefore + numsrcverts + numafter);
memcpy(ext->surfaces, c.ext->surfaces, sizeof(ext->surfaces));
}
int offset = 0;
if(numbefore == beforeoffset)
{
if(numbefore && c.ext != ext) memcpy(ext->verts(), c.ext->verts(), numbefore*sizeof(vertinfo));
offset = numbefore;
}
else loopi(orient)
{
surfaceinfo &surf = ext->surfaces[i];
int numverts = surf.totalverts();
if(!numverts) continue;
memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo));
surf.verts = offset;
offset += numverts;
}
dstoffset = offset;
offset += numsrcverts;
if(numafter && offset > afteroffset)
{
offset += numafter;
for(int i = 5; i > orient; i--)
{
surfaceinfo &surf = ext->surfaces[i];
int numverts = surf.totalverts();
if(!numverts) continue;
offset -= numverts;
memmove(ext->verts() + offset, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo));
surf.verts = offset;
}
}
if(c.ext != ext) setcubeext(c, ext);
}
}
surfaceinfo &dst = c.ext->surfaces[orient];
dst = src;
dst.verts = dstoffset;
if(srcverts) memcpy(c.ext->verts() + dstoffset, srcverts, numsrcverts*sizeof(vertinfo));
}
// quality parameters, set by the calclight arg
VARN(lmshadows, lmshadows_, 0, 2, 2);
VARN(lmaa, lmaa_, 0, 3, 3);
VARN(lerptjoints, lerptjoints_, 0, 1, 1);
static int lmshadows = 2, lmaa = 3, lerptjoints = 1;
static uint progress = 0, taskprogress = 0;
static GLuint progresstex = 0;
static int progresstexticks = 0, progresslightmap = -1;
bool calclight_canceled = false;
volatile bool check_calclight_progress = false;
void check_calclight_canceled()
{
if(interceptkey(SDLK_ESCAPE))
{
calclight_canceled = true;
loopv(lightmapworkers) lightmapworkers[i]->doneworking = true;
}
if(!calclight_canceled) check_calclight_progress = false;
}
void show_calclight_progress()
{
float bar1 = float(progress) / float(allocnodes);
defformatstring(text1, "%d%% using %d textures", int(bar1 * 100), lightmaps.length());
if(LM_PACKW <= hwtexsize && !progresstex)
{
glGenTextures(1, &progresstex);
createtexture(progresstex, LM_PACKW, LM_PACKH, NULL, 3, 1, GL_RGB);
}
// only update once a sec (4 * 250 ms ticks) to not kill performance
if(progresstex && !calclight_canceled && progresslightmap >= 0 && !(progresstexticks++ % 4))
{
if(tasklock) SDL_LockMutex(tasklock);
LightMap &lm = lightmaps[progresslightmap];
uchar *data = lm.data;
int bpp = lm.bpp;
if(tasklock) SDL_UnlockMutex(tasklock);
glBindTexture(GL_TEXTURE_2D, progresstex);
glPixelStorei(GL_UNPACK_ALIGNMENT, texalign(data, LM_PACKW, bpp));
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, LM_PACKW, LM_PACKH, bpp > 3 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data);
}
renderprogress(bar1, text1, progresstexticks ? progresstex : 0);
}
#define CHECK_PROGRESS_LOCKED(exit, before, after) CHECK_CALCLIGHT_PROGRESS_LOCKED(exit, show_calclight_progress, before, after)
#define CHECK_PROGRESS(exit) CHECK_PROGRESS_LOCKED(exit, , )
bool PackNode::insert(ushort &tx, ushort &ty, ushort tw, ushort th)
{
if((available < tw && available < th) || w < tw || h < th)
return false;
if(child1)
{
bool inserted = child1->insert(tx, ty, tw, th) ||
child2->insert(tx, ty, tw, th);
available = max(child1->available, child2->available);
if(!available) clear();
return inserted;
}
if(w == tw && h == th)
{
available = 0;
tx = x;
ty = y;
return true;
}
if(w - tw > h - th)
{
child1 = new PackNode(x, y, tw, h);
child2 = new PackNode(x + tw, y, w - tw, h);
}
else
{
child1 = new PackNode(x, y, w, th);
child2 = new PackNode(x, y + th, w, h - th);
}
bool inserted = child1->insert(tx, ty, tw, th);
available = max(child1->available, child2->available);
return inserted;
}
bool LightMap::insert(ushort &tx, ushort &ty, uchar *src, ushort tw, ushort th)
{
if((type&LM_TYPE) != LM_BUMPMAP1 && !packroot.insert(tx, ty, tw, th))
return false;
copy(tx, ty, src, tw, th);
return true;
}
void LightMap::copy(ushort tx, ushort ty, uchar *src, ushort tw, ushort th)
{
uchar *dst = data + bpp * tx + ty * bpp * LM_PACKW;
loopi(th)
{
memcpy(dst, src, bpp * tw);
dst += bpp * LM_PACKW;
src += bpp * tw;
}
++lightmaps;
lumels += tw * th;
}
static void insertunlit(int i)
{
LightMap &l = lightmaps[i];
if((l.type&LM_TYPE) == LM_BUMPMAP1)
{
l.unlitx = l.unlity = -1;
return;
}
ushort x, y;
uchar unlit[4] = { ambientcolor[0], ambientcolor[1], ambientcolor[2], 255 };
if(l.insert(x, y, unlit, 1, 1))
{
if((l.type&LM_TYPE) == LM_BUMPMAP0)
{
bvec front(128, 128, 255);
ASSERT(lightmaps[i+1].insert(x, y, front.v, 1, 1));
}
l.unlitx = x;
l.unlity = y;
}
}
struct layoutinfo
{
ushort x, y, lmid;
uchar w, h;
};
static void insertlightmap(lightmapinfo &li, layoutinfo &si)
{
loopv(lightmaps)
{
if(lightmaps[i].type == li.type && lightmaps[i].insert(si.x, si.y, li.colorbuf, si.w, si.h))
{
si.lmid = i + LMID_RESERVED;
if((li.type&LM_TYPE) == LM_BUMPMAP0) ASSERT(lightmaps[i+1].insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h));
return;
}
}
progresslightmap = lightmaps.length();
si.lmid = lightmaps.length() + LMID_RESERVED;
LightMap &l = lightmaps.add();
l.type = li.type;
l.bpp = li.bpp;
l.data = new uchar[li.bpp*LM_PACKW*LM_PACKH];
memset(l.data, 0, li.bpp*LM_PACKW*LM_PACKH);
ASSERT(l.insert(si.x, si.y, li.colorbuf, si.w, si.h));
if((li.type&LM_TYPE) == LM_BUMPMAP0)
{
LightMap &r = lightmaps.add();
r.type = LM_BUMPMAP1 | (li.type&~LM_TYPE);
r.bpp = 3;
r.data = new uchar[3*LM_PACKW*LM_PACKH];
memset(r.data, 0, 3*LM_PACKW*LM_PACKH);
ASSERT(r.insert(si.x, si.y, (uchar *)li.raybuf, si.w, si.h));
}
}
static void copylightmap(lightmapinfo &li, layoutinfo &si)
{
lightmaps[si.lmid-LMID_RESERVED].copy(si.x, si.y, li.colorbuf, si.w, si.h);
if((li.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(si.lmid+1-LMID_RESERVED))
lightmaps[si.lmid+1-LMID_RESERVED].copy(si.x, si.y, (uchar *)li.raybuf, si.w, si.h);
}
static inline bool htcmp(const lightmapinfo &k, const layoutinfo &v)
{
int kw = k.w, kh = k.h;
if(kw != v.w || kh != v.h) return false;
LightMap &vlm = lightmaps[v.lmid - LMID_RESERVED];
int ktype = k.type;
if(ktype != vlm.type) return false;
int kbpp = k.bpp;
const uchar *kcolor = k.colorbuf, *vcolor = vlm.data + kbpp*(v.x + v.y*LM_PACKW);
loopi(kh)
{
if(memcmp(kcolor, vcolor, kbpp*kw)) return false;
kcolor += kbpp*kw;
vcolor += kbpp*LM_PACKW;
}
if((ktype&LM_TYPE) != LM_BUMPMAP0) return true;
const bvec *kdir = k.raybuf, *vdir = (const bvec *)lightmaps[v.lmid+1 - LMID_RESERVED].data;
loopi(kh)
{
if(memcmp(kdir, vdir, kw*sizeof(bvec))) return false;
kdir += kw;
vdir += LM_PACKW;
}
return true;
}
static inline uint hthash(const lightmapinfo &k)
{
int kw = k.w, kh = k.h, kbpp = k.bpp;
uint hash = kw + (kh<<8);
const uchar *color = k.colorbuf;
loopi(kw*kh)
{
hash ^= color[0] + (color[1] << 4) + (color[2] << 8);
color += kbpp;
}
return hash;
}
static hashset<layoutinfo> compressed;
VAR(lightcompress, 0, 3, 6);
static bool packlightmap(lightmapinfo &l, layoutinfo &surface)
{
surface.w = l.w;
surface.h = l.h;
if((int)l.w <= lightcompress && (int)l.h <= lightcompress)
{
layoutinfo *val = compressed.access(l);
if(!val)
{
insertlightmap(l, surface);
compressed[l] = surface;
}
else
{
surface.x = val->x;
surface.y = val->y;
surface.lmid = val->lmid;
return false;
}
}
else insertlightmap(l, surface);
return true;
}
static void updatelightmap(const layoutinfo &surface)
{
if(max(LM_PACKW, LM_PACKH) > hwtexsize) return;
LightMap &lm = lightmaps[surface.lmid-LMID_RESERVED];
if(lm.tex < 0)
{
lm.offsetx = lm.offsety = 0;
lm.tex = lightmaptexs.length();
LightMapTexture &tex = lightmaptexs.add();
tex.type = lm.type;
tex.w = LM_PACKW;
tex.h = LM_PACKH;
tex.unlitx = lm.unlitx;
tex.unlity = lm.unlity;
glGenTextures(1, &tex.id);
createtexture(tex.id, tex.w, tex.h, NULL, 3, 1, tex.type&LM_ALPHA ? GL_RGBA : GL_RGB);
if((lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED))
{
LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED];
lm2.offsetx = lm2.offsety = 0;
lm2.tex = lightmaptexs.length();
LightMapTexture &tex2 = lightmaptexs.add();
tex2.type = (lm.type&~LM_TYPE) | LM_BUMPMAP0;
tex2.w = LM_PACKW;
tex2.h = LM_PACKH;
tex2.unlitx = lm2.unlitx;
tex2.unlity = lm2.unlity;
glGenTextures(1, &tex2.id);
createtexture(tex2.id, tex2.w, tex2.h, NULL, 3, 1, GL_RGB);
}
}
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_UNPACK_ROW_LENGTH, LM_PACKW);
glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm.tex].id);
glTexSubImage2D(GL_TEXTURE_2D, 0, lm.offsetx + surface.x, lm.offsety + surface.y, surface.w, surface.h, lm.type&LM_ALPHA ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, &lm.data[(surface.y*LM_PACKW + surface.x)*lm.bpp]);
if((lm.type&LM_TYPE)==LM_BUMPMAP0 && lightmaps.inrange(surface.lmid+1-LMID_RESERVED))
{
LightMap &lm2 = lightmaps[surface.lmid+1-LMID_RESERVED];
glBindTexture(GL_TEXTURE_2D, lightmaptexs[lm2.tex].id);
glTexSubImage2D(GL_TEXTURE_2D, 0, lm2.offsetx + surface.x, lm2.offsety + surface.y, surface.w, surface.h, GL_RGB, GL_UNSIGNED_BYTE, &lm2.data[(surface.y*LM_PACKW + surface.x)*3]);
}
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
static uint generatelumel(lightmapworker *w, const float tolerance, uint lightmask, const vector<const extentity *> &lights, const vec &target, const vec &normal, vec &sample, int x, int y)
{
vec avgray(0, 0, 0);
float r = 0, g = 0, b = 0;
uint lightused = 0;
loopv(lights)
{
if(lightmask&(1<<i)) continue;
const extentity &light = *lights[i];
vec ray = target;
ray.sub(light.o);
float mag = ray.magnitude();
if(!mag) continue;
float attenuation = 1;
if(light.attr1)
{
attenuation -= mag / float(light.attr1);
if(attenuation <= 0) continue;
}
ray.mul(1.0f / mag);
float angle = -ray.dot(normal);
if(angle <= 0) continue;
if(light.attached && light.attached->type==ET_SPOTLIGHT)
{
vec spot = vec(light.attached->o).sub(light.o).normalize();
float maxatten = sincos360[clamp(int(light.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten);
if(spotatten <= 0) continue;
attenuation *= spotatten;
}
if(lmshadows && mag)
{
float dist = shadowray(w->shadowraycache, light.o, ray, mag - tolerance, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0));
if(dist < mag - tolerance) continue;
}
lightused |= 1<<i;
float intensity;
switch(w->type&LM_TYPE)
{
case LM_BUMPMAP0:
intensity = attenuation;
avgray.add(ray.mul(-attenuation));
break;
default:
intensity = angle * attenuation;
break;
}
r += intensity * float(light.attr2);
g += intensity * float(light.attr3);
b += intensity * float(light.attr4);
}
if(sunlight)
{
float angle = sunlightdir.dot(normal);
if(angle > 0 &&
(!lmshadows ||
shadowray(w->shadowraycache, vec(sunlightdir).mul(tolerance).add(target), sunlightdir, 1e16f, RAY_SHADOW | (lmshadows > 1 ? RAY_ALPHAPOLY : 0) | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f))
{
float intensity;
switch(w->type&LM_TYPE)
{
case LM_BUMPMAP0:
intensity = 1;
avgray.add(sunlightdir);
break;
default:
intensity = angle;
break;
}
r += intensity * (sunlightcolor.x*sunlightscale);
g += intensity * (sunlightcolor.y*sunlightscale);
b += intensity * (sunlightcolor.z*sunlightscale);
}
}
switch(w->type&LM_TYPE)
{
case LM_BUMPMAP0:
if(avgray.iszero()) break;
// transform to tangent space
extern vec orientation_tangent[6][3];
extern vec orientation_bitangent[6][3];
vec S(orientation_tangent[w->rotate][dimension(w->orient)]),
T(orientation_bitangent[w->rotate][dimension(w->orient)]);
normal.orthonormalize(S, T);
avgray.normalize();
w->raydata[y*w->w+x].add(vec(S.dot(avgray)/S.magnitude(), T.dot(avgray)/T.magnitude(), normal.dot(avgray)));
break;
}
sample.x = min(255.0f, max(r, float(ambientcolor[0])));
sample.y = min(255.0f, max(g, float(ambientcolor[1])));
sample.z = min(255.0f, max(b, float(ambientcolor[2])));
return lightused;
}
static bool lumelsample(const vec &sample, int aasample, int stride)
{
if(sample.x >= int(ambientcolor[0])+1 || sample.y >= int(ambientcolor[1])+1 || sample.z >= int(ambientcolor[2])+1) return true;
#define NCHECK(n) \
if((n).x >= int(ambientcolor[0])+1 || (n).y >= int(ambientcolor[1])+1 || (n).z >= int(ambientcolor[2])+1) \
return true;
const vec *n = &sample - stride - aasample;
NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]);
n += stride;
NCHECK(n[0]); NCHECK(n[2*aasample]);
n += stride;
NCHECK(n[0]); NCHECK(n[aasample]); NCHECK(n[2*aasample]);
return false;
}
static void calcskylight(lightmapworker *w, const vec &o, const vec &normal, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL)
{
static const vec rays[17] =
{
vec(cosf(21*RAD)*cosf(50*RAD), sinf(21*RAD)*cosf(50*RAD), sinf(50*RAD)),
vec(cosf(111*RAD)*cosf(50*RAD), sinf(111*RAD)*cosf(50*RAD), sinf(50*RAD)),
vec(cosf(201*RAD)*cosf(50*RAD), sinf(201*RAD)*cosf(50*RAD), sinf(50*RAD)),
vec(cosf(291*RAD)*cosf(50*RAD), sinf(291*RAD)*cosf(50*RAD), sinf(50*RAD)),
vec(cosf(66*RAD)*cosf(70*RAD), sinf(66*RAD)*cosf(70*RAD), sinf(70*RAD)),
vec(cosf(156*RAD)*cosf(70*RAD), sinf(156*RAD)*cosf(70*RAD), sinf(70*RAD)),
vec(cosf(246*RAD)*cosf(70*RAD), sinf(246*RAD)*cosf(70*RAD), sinf(70*RAD)),
vec(cosf(336*RAD)*cosf(70*RAD), sinf(336*RAD)*cosf(70*RAD), sinf(70*RAD)),
vec(0, 0, 1),
vec(cosf(43*RAD)*cosf(60*RAD), sinf(43*RAD)*cosf(60*RAD), sinf(60*RAD)),
vec(cosf(133*RAD)*cosf(60*RAD), sinf(133*RAD)*cosf(60*RAD), sinf(60*RAD)),
vec(cosf(223*RAD)*cosf(60*RAD), sinf(223*RAD)*cosf(60*RAD), sinf(60*RAD)),
vec(cosf(313*RAD)*cosf(60*RAD), sinf(313*RAD)*cosf(60*RAD), sinf(60*RAD)),
vec(cosf(88*RAD)*cosf(80*RAD), sinf(88*RAD)*cosf(80*RAD), sinf(80*RAD)),
vec(cosf(178*RAD)*cosf(80*RAD), sinf(178*RAD)*cosf(80*RAD), sinf(80*RAD)),
vec(cosf(268*RAD)*cosf(80*RAD), sinf(268*RAD)*cosf(80*RAD), sinf(80*RAD)),
vec(cosf(358*RAD)*cosf(80*RAD), sinf(358*RAD)*cosf(80*RAD), sinf(80*RAD)),
};
flags |= RAY_SHADOW;
if(skytexturelight) flags |= RAY_SKIPSKY;
int hit = 0;
if(w) loopi(17)
{
if(normal.dot(rays[i])>=0 && shadowray(w->shadowraycache, vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++;
}
else loopi(17)
{
if(normal.dot(rays[i])>=0 && shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++;
}
loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/17.0f);
}
static inline bool hasskylight()
{
return skylightcolor[0]>ambientcolor[0] || skylightcolor[1]>ambientcolor[1] || skylightcolor[2]>ambientcolor[2];
}
VARR(blurlms, 0, 0, 2);
VARR(blurskylight, 0, 0, 2);
static inline void generatealpha(lightmapworker *w, float tolerance, const vec &pos, uchar &alpha)
{
alpha = lookupblendmap(w->blendmapcache, pos);
if(w->slot->layermask)
{
static const int sdim[] = { 1, 0, 0 }, tdim[] = { 2, 2, 1 };
int dim = dimension(w->orient);
float k = 8.0f/w->vslot->scale,
s = (pos[sdim[dim]] * k - w->vslot->offset.y) / w->slot->layermaskscale,
t = (pos[tdim[dim]] * (dim <= 1 ? -k : k) - w->vslot->offset.y) / w->slot->layermaskscale;
if((w->rotate&5)==1) swap(s, t);
if(w->rotate>=2 && w->rotate<=4) s = -s;
if((w->rotate>=1 && w->rotate<=2) || w->rotate==5) t = -t;
const ImageData &mask = *w->slot->layermask;
int mx = int(floor(s))%mask.w, my = int(floor(t))%mask.h;
if(mx < 0) mx += mask.w;
if(my < 0) my += mask.h;
uchar maskval = mask.data[mask.bpp*(mx + 1) - 1 + mask.pitch*my];
switch(w->slot->layermaskmode)
{
case 2: alpha = min(alpha, maskval); break;
case 3: alpha = max(alpha, maskval); break;
case 4: alpha = min(alpha, uchar(0xFF - maskval)); break;
case 5: alpha = max(alpha, uchar(0xFF - maskval)); break;
default: alpha = maskval; break;
}
}
}
VAR(edgetolerance, 1, 4, 64);
VAR(adaptivesample, 0, 2, 2);
enum
{
NO_SURFACE = 0,
SURFACE_AMBIENT_BOTTOM,
SURFACE_AMBIENT_TOP,
SURFACE_LIGHTMAP_BOTTOM,
SURFACE_LIGHTMAP_TOP,
SURFACE_LIGHTMAP_BLEND
};
#define SURFACE_AMBIENT SURFACE_AMBIENT_BOTTOM
#define SURFACE_LIGHTMAP SURFACE_LIGHTMAP_BOTTOM
static bool generatelightmap(lightmapworker *w, float lpu, const lerpvert *lv, int numv, vec origin1, const vec &xstep1, const vec &ystep1, vec origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep)
{
static const float aacoords[8][2] =
{
{0.0f, 0.0f},
{-0.5f, -0.5f},
{0.0f, -0.5f},
{-0.5f, 0.0f},
{0.3f, -0.6f},
{0.6f, 0.3f},
{-0.3f, 0.6f},
{-0.6f, -0.3f},
};
float tolerance = 0.5 / lpu;
uint lightmask = 0, lightused = 0;
vec offsets1[8], offsets2[8];
loopi(8)
{
offsets1[i] = vec(xstep1).mul(aacoords[i][0]).add(vec(ystep1).mul(aacoords[i][1]));
offsets2[i] = vec(xstep2).mul(aacoords[i][0]).add(vec(ystep2).mul(aacoords[i][1]));
}
if((w->type&LM_TYPE) == LM_BUMPMAP0) memset(w->raydata, 0, (LM_MAXW + 4)*(LM_MAXH + 4)*sizeof(vec));
origin1.sub(vec(ystep1).add(xstep1).mul(blurlms));
origin2.sub(vec(ystep2).add(xstep2).mul(blurlms));
int aasample = min(1 << lmaa, 4);
int stride = aasample*(w->w+1);
vec *sample = w->colordata;
uchar *skylight = w->ambient;
lerpbounds start, end;
initlerpbounds(-blurlms, -blurlms, lv, numv, start, end);
float sidex = side0 + blurlms*sidestep;
for(int y = 0; y < w->h; ++y, sidex += sidestep)
{
vec normal, nstep;
lerpnormal(-blurlms, y - blurlms, lv, numv, start, end, normal, nstep);
for(int x = 0; x < w->w; ++x, normal.add(nstep), skylight += w->bpp)
{
#define EDGE_TOLERANCE(x, y) \
(x < blurlms \
|| x+1 > w->w - blurlms \
|| y < blurlms \
|| y+1 > w->h - blurlms \
? edgetolerance : 1)
float t = EDGE_TOLERANCE(x, y) * tolerance;
vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2);
lightused |= generatelumel(w, t, 0, w->lights, u, vec(normal).normalize(), *sample, x, y);
if(hasskylight())
{
if((w->type&LM_TYPE)==LM_BUMPMAP0 || !adaptivesample || sample->x<skylightcolor[0] || sample->y<skylightcolor[1] || sample->z<skylightcolor[2])
calcskylight(w, u, normal, t, skylight, lmshadows > 1 ? RAY_ALPHAPOLY : 0);
else loopk(3) skylight[k] = max(skylightcolor[k], ambientcolor[k]);
}
else loopk(3) skylight[k] = ambientcolor[k];
if(w->type&LM_ALPHA) generatealpha(w, t, u, skylight[3]);
sample += aasample;
}
sample += aasample;
}
if(adaptivesample > 1 && min(w->w, w->h) >= 2) lightmask = ~lightused;
sample = w->colordata;
initlerpbounds(-blurlms, -blurlms, lv, numv, start, end);
sidex = side0 + blurlms*sidestep;
for(int y = 0; y < w->h; ++y, sidex += sidestep)
{
vec normal, nstep;
lerpnormal(-blurlms, y - blurlms, lv, numv, start, end, normal, nstep);
for(int x = 0; x < w->w; ++x, normal.add(nstep))
{
vec ¢er = *sample++;
if(adaptivesample && x > 0 && x+1 < w->w && y > 0 && y+1 < w->h && !lumelsample(center, aasample, stride))
loopi(aasample-1) *sample++ = center;
else
{
#define AA_EDGE_TOLERANCE(x, y, i) EDGE_TOLERANCE(x + aacoords[i][0], y + aacoords[i][1])
vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2);
const vec *offsets = x < sidex ? offsets1 : offsets2;
vec n = vec(normal).normalize();
loopi(aasample-1)
generatelumel(w, AA_EDGE_TOLERANCE(x, y, i+1) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+1]), n, *sample++, x, y);
if(lmaa == 3)
{
loopi(4)
{
vec s;
generatelumel(w, AA_EDGE_TOLERANCE(x, y, i+4) * tolerance, lightmask, w->lights, vec(u).add(offsets[i+4]), n, s, x, y);
center.add(s);
}
center.div(5);
}
}
}
if(aasample > 1)
{
vec u = w->w < sidex ? vec(xstep1).mul(w->w).add(vec(ystep1).mul(y)).add(origin1) : vec(xstep2).mul(w->w).add(vec(ystep2).mul(y)).add(origin2);
const vec *offsets = w->w < sidex ? offsets1 : offsets2;
vec n = vec(normal).normalize();
generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], w->w-1, y);
if(aasample > 2)
generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[3]), n, sample[3], w->w-1, y);
}
sample += aasample;
}
if(aasample > 1)
{
vec normal, nstep;
lerpnormal(-blurlms, w->h - blurlms, lv, numv, start, end, normal, nstep);
for(int x = 0; x <= w->w; ++x, normal.add(nstep))
{
vec u = x < sidex ? vec(xstep1).mul(x).add(vec(ystep1).mul(w->h)).add(origin1) : vec(xstep2).mul(x).add(vec(ystep2).mul(w->h)).add(origin2);
const vec *offsets = x < sidex ? offsets1 : offsets2;
vec n = vec(normal).normalize();
generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[1]), n, sample[1], min(x, w->w-1), w->h-1);
if(aasample > 2)
generatelumel(w, edgetolerance * tolerance, lightmask, w->lights, vec(u).add(offsets[2]), n, sample[2], min(x, w->w-1), w->h-1);
sample += aasample;
}
}
return true;
}
static int finishlightmap(lightmapworker *w)
{
if(hasskylight() && blurskylight && (w->w>1 || w->h>1))
{
blurtexture(blurskylight, w->bpp, w->w, w->h, w->blur, w->ambient);
swap(w->blur, w->ambient);
}
vec *sample = w->colordata;
int aasample = min(1 << lmaa, 4), stride = aasample*(w->w+1);
float weight = 1.0f / (1.0f + 4.0f*lmaa),
cweight = weight * (lmaa == 3 ? 5.0f : 1.0f);
uchar *skylight = w->ambient;
vec *ray = w->raydata;
uchar *dstcolor = blurlms && (w->w > 1 || w->h > 1) ? w->blur : w->colorbuf;
uchar mincolor[4] = { 255, 255, 255, 255 }, maxcolor[4] = { 0, 0, 0, 0 };
bvec *dstray = blurlms && (w->w > 1 || w->h > 1) ? (bvec *)w->raydata : w->raybuf;
bvec minray(255, 255, 255), maxray(0, 0, 0);
loop(y, w->h)
{
loop(x, w->w)
{
vec l(0, 0, 0);
const vec ¢er = *sample++;
loopi(aasample-1) l.add(*sample++);
if(aasample > 1)
{
l.add(sample[1]);
if(aasample > 2) l.add(sample[3]);
}
vec *next = sample + stride - aasample;
if(aasample > 1)
{
l.add(next[1]);
if(aasample > 2) l.add(next[2]);
l.add(next[aasample+1]);
}
int r = int(center.x*cweight + l.x*weight),
g = int(center.y*cweight + l.y*weight),
b = int(center.z*cweight + l.z*weight),
ar = skylight[0], ag = skylight[1], ab = skylight[2];
dstcolor[0] = max(ar, r);
dstcolor[1] = max(ag, g);
dstcolor[2] = max(ab, b);
loopk(3)
{
mincolor[k] = min(mincolor[k], dstcolor[k]);
maxcolor[k] = max(maxcolor[k], dstcolor[k]);
}
if(w->type&LM_ALPHA)
{
dstcolor[3] = skylight[3];
mincolor[3] = min(mincolor[3], dstcolor[3]);
maxcolor[3] = max(maxcolor[3], dstcolor[3]);
}
if((w->type&LM_TYPE) == LM_BUMPMAP0)
{
if(ray->iszero()) dstray[0] = bvec(128, 128, 255);
else
{
// bias the normals towards the amount of ambient/skylight in the lumel
// this is necessary to prevent the light values in shaders from dropping too far below the skylight (to the ambient) if N.L is small
ray->normalize();
int l = max(r, max(g, b)), a = max(ar, max(ag, ab));
ray->mul(max(l-a, 0));
ray->z += a;
dstray[0] = bvec(ray->normalize());
}
loopk(3)
{
minray[k] = min(minray[k], dstray[0][k]);
maxray[k] = max(maxray[k], dstray[0][k]);
}
ray++;
dstray++;
}
dstcolor += w->bpp;
skylight += w->bpp;
}
sample += aasample;
}
if(int(maxcolor[0]) - int(mincolor[0]) <= lighterror &&
int(maxcolor[1]) - int(mincolor[1]) <= lighterror &&
int(maxcolor[2]) - int(mincolor[2]) <= lighterror &&
mincolor[3] >= maxcolor[3])
{
uchar color[3];
loopk(3) color[k] = (int(maxcolor[k]) + int(mincolor[k])) / 2;
if(color[0] <= int(ambientcolor[0]) + lighterror &&
color[1] <= int(ambientcolor[1]) + lighterror &&
color[2] <= int(ambientcolor[2]) + lighterror &&
(maxcolor[3]==0 || mincolor[3]==255))
return mincolor[3]==255 ? SURFACE_AMBIENT_TOP : SURFACE_AMBIENT_BOTTOM;
if((w->type&LM_TYPE) != LM_BUMPMAP0 ||
(int(maxray.x) - int(minray.x) <= bumperror &&
int(maxray.y) - int(minray.z) <= bumperror &&
int(maxray.z) - int(minray.z) <= bumperror))
{
memcpy(w->colorbuf, color, 3);
if(w->type&LM_ALPHA) w->colorbuf[3] = mincolor[3];
if((w->type&LM_TYPE) == LM_BUMPMAP0)
{
loopk(3) w->raybuf[0][k] = uchar((int(maxray[k])+int(minray[k]))/2);
}
w->lastlightmap->w = w->w = 1;
w->lastlightmap->h = w->h = 1;
}
}
if(blurlms && (w->w>1 || w->h>1))
{
blurtexture(blurlms, w->bpp, w->w, w->h, w->colorbuf, w->blur, blurlms);
if((w->type&LM_TYPE) == LM_BUMPMAP0) blurnormals(blurlms, w->w, w->h, w->raybuf, (const bvec *)w->raydata, blurlms);
w->lastlightmap->w = (w->w -= 2*blurlms);
w->lastlightmap->h = (w->h -= 2*blurlms);
}
if(mincolor[3]==255) return SURFACE_LIGHTMAP_TOP;
else if(maxcolor[3]==0) return SURFACE_LIGHTMAP_BOTTOM;
else return SURFACE_LIGHTMAP_BLEND;
}
static int previewlightmapalpha(lightmapworker *w, float lpu, const vec &origin1, const vec &xstep1, const vec &ystep1, const vec &origin2, const vec &xstep2, const vec &ystep2, float side0, float sidestep)
{
extern int fullbrightlevel;
float tolerance = 0.5 / lpu;
uchar *dst = w->colorbuf;
uchar minalpha = 255, maxalpha = 0;
float sidex = side0;
for(int y = 0; y < w->h; ++y, sidex += sidestep)
{
for(int x = 0; x < w->w; ++x, dst += 4)
{
vec u = x < sidex ?
vec(xstep1).mul(x).add(vec(ystep1).mul(y)).add(origin1) :
vec(xstep2).mul(x).add(vec(ystep2).mul(y)).add(origin2);
loopk(3) dst[k] = fullbrightlevel;
generatealpha(w, tolerance, u, dst[3]);
minalpha = min(minalpha, dst[3]);
maxalpha = max(maxalpha, dst[3]);
}
}
if(minalpha==255) return SURFACE_AMBIENT_TOP;
if(maxalpha==0) return SURFACE_AMBIENT_BOTTOM;
if(minalpha==maxalpha) w->w = w->h = 1;
if((w->type&LM_TYPE) == LM_BUMPMAP0) loopi(w->w*w->h) w->raybuf[i] = bvec(128, 128, 255);
return SURFACE_LIGHTMAP_BLEND;
}
static void clearsurfaces(cube *c)
{
loopi(8)
{
if(c[i].ext)
{
loopj(6)
{
surfaceinfo &surf = c[i].ext->surfaces[j];
if(!surf.used()) continue;
surf.clear();
int numverts = surf.numverts&MAXFACEVERTS;
if(numverts)
{
if(!(c[i].merged&(1<<j))) { surf.numverts &= ~MAXFACEVERTS; continue; }
vertinfo *verts = c[i].ext->verts() + surf.verts;
loopk(numverts)
{
vertinfo &v = verts[k];
v.u = 0;
v.v = 0;
v.norm = 0;
}
}
}
}
if(c[i].children) clearsurfaces(c[i].children);
}
}
#define LIGHTCACHESIZE 1024
static struct lightcacheentry
{
int x, y;
vector<int> lights;
} lightcache[LIGHTCACHESIZE];
#define LIGHTCACHEHASH(x, y) (((((x)^(y))<<5) + (((x)^(y))>>5)) & (LIGHTCACHESIZE - 1))
VARF(lightcachesize, 4, 6, 12, clearlightcache());
void clearlightcache(int id)
{
if(id >= 0)
{
const extentity &light = *entities::getents()[id];
int radius = light.attr1;
if(radius)
{
for(int x = int(max(light.o.x-radius, 0.0f))>>lightcachesize, ex = int(min(light.o.x+radius, worldsize-1.0f))>>lightcachesize; x <= ex; x++)
for(int y = int(max(light.o.y-radius, 0.0f))>>lightcachesize, ey = int(min(light.o.y+radius, worldsize-1.0f))>>lightcachesize; y <= ey; y++)
{
lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)];
if(lce.x != x || lce.y != y) continue;
lce.x = -1;
lce.lights.setsize(0);
}
return;
}
}
for(lightcacheentry *lce = lightcache; lce < &lightcache[LIGHTCACHESIZE]; lce++)
{
lce->x = -1;
lce->lights.setsize(0);
}
}
const vector<int> &checklightcache(int x, int y)
{
x >>= lightcachesize;
y >>= lightcachesize;
lightcacheentry &lce = lightcache[LIGHTCACHEHASH(x, y)];
if(lce.x == x && lce.y == y) return lce.lights;
lce.lights.setsize(0);
int csize = 1<<lightcachesize, cx = x<<lightcachesize, cy = y<<lightcachesize;
const vector<extentity *> &ents = entities::getents();
loopv(ents)
{
const extentity &light = *ents[i];
switch(light.type)
{
case ET_LIGHT:
{
int radius = light.attr1;
if(radius > 0)
{
if(light.o.x + radius < cx || light.o.x - radius > cx + csize ||
light.o.y + radius < cy || light.o.y - radius > cy + csize)
continue;
}
break;
}
default: continue;
}
lce.lights.add(i);
}
lce.x = x;
lce.y = y;
return lce.lights;
}
static inline void addlight(lightmapworker *w, const extentity &light, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv)
{
int radius = light.attr1;
if(radius > 0)
{
if(light.o.x + radius < cx || light.o.x - radius > cx + size ||
light.o.y + radius < cy || light.o.y - radius > cy + size ||
light.o.z + radius < cz || light.o.z - radius > cz + size)
return;
}
loopi(4)
{
vec p(light.o);
p.sub(v[i]);
float dist = p.dot(n[i]);
if(dist >= 0 && (!radius || dist < radius))
{
w->lights.add(&light);
break;
}
}
}
static bool findlights(lightmapworker *w, int cx, int cy, int cz, int size, const vec *v, const vec *n, int numv, const Slot &slot, const VSlot &vslot)
{
w->lights.setsize(0);
const vector<extentity *> &ents = entities::getents();
static volatile bool usinglightcache = false;
if(size <= 1<<lightcachesize && (!lightlock || !usinglightcache))
{
if(lightlock) { SDL_LockMutex(lightlock); usinglightcache = true; }
const vector<int> &lights = checklightcache(cx, cy);
loopv(lights)
{
const extentity &light = *ents[lights[i]];
switch(light.type)
{
case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break;
}
}
if(lightlock) { usinglightcache = false; SDL_UnlockMutex(lightlock); }
}
else loopv(ents)
{
const extentity &light = *ents[i];
switch(light.type)
{
case ET_LIGHT: addlight(w, light, cx, cy, cz, size, v, n, numv); break;
}
}
if(vslot.layer && (setblendmaporigin(w->blendmapcache, ivec(cx, cy, cz), size) || slot.layermask)) return true;
return w->lights.length() || hasskylight() || sunlight;
}
static int packlightmaps(lightmapworker *w = NULL)
{
int numpacked = 0;
for(; packidx < lightmaptasks[0].length(); packidx++, numpacked++)
{
lightmaptask &t = lightmaptasks[0][packidx];
if(!t.lightmaps) break;
if(t.ext && t.c->ext != t.ext)
{
lightmapext &e = lightmapexts.add();
e.c = t.c;
e.ext = t.ext;
}
progress = t.progress;
lightmapinfo *l = t.lightmaps;
if(l == (lightmapinfo *)-1) continue;
int space = 0;
for(; l && l->c == t.c; l = l->next)
{
l->packed = true;
space += l->bufsize;
if(l->surface < 0 || !t.ext) continue;
surfaceinfo &surf = t.ext->surfaces[l->surface];
layoutinfo layout;
packlightmap(*l, layout);
int numverts = surf.numverts&MAXFACEVERTS;
vertinfo *verts = t.ext->verts() + surf.verts;
if(l->layers&LAYER_DUP)
{
if(l->type&LM_ALPHA) surf.lmid[0] = layout.lmid;
else { surf.lmid[1] = layout.lmid; verts += numverts; }
}
else
{
if(l->layers&LAYER_TOP) surf.lmid[0] = layout.lmid;
if(l->layers&LAYER_BOTTOM) surf.lmid[1] = layout.lmid;
}
ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH);
loopk(numverts)
{
vertinfo &v = verts[k];
v.u += offsetx;
v.v += offsety;
}
}
if(t.worker == w)
{
w->bufused -= space;
w->bufstart = (w->bufstart + space)%LIGHTMAPBUFSIZE;
w->firstlightmap = l;
if(!l)
{
w->lastlightmap = NULL;
w->bufstart = w->bufused = 0;
}
}
if(t.worker->needspace) SDL_CondSignal(t.worker->spacecond);
}
return numpacked;
}
static lightmapinfo *alloclightmap(lightmapworker *w)
{
int needspace1 = sizeof(lightmapinfo) + w->w*w->h*w->bpp,
needspace2 = (w->type&LM_TYPE) == LM_BUMPMAP0 ? w->w*w->h*3 : 0,
needspace = needspace1 + needspace2,
bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE,
availspace = LIGHTMAPBUFSIZE - w->bufused,
availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend),
availspace2 = min(availspace, w->bufstart);
if(availspace < needspace || (max(availspace1, availspace2) < needspace && (availspace1 < needspace1 || availspace2 < needspace2)))
{
if(tasklock) SDL_LockMutex(tasklock);
while(!w->doneworking)
{
lightmapinfo *l = w->firstlightmap;
for(; l && l->packed; l = l->next)
{
w->bufused -= l->bufsize;
w->bufstart = (w->bufstart + l->bufsize)%LIGHTMAPBUFSIZE;
}
w->firstlightmap = l;
if(!l)
{
w->lastlightmap = NULL;
w->bufstart = w->bufused = 0;
}
bufend = (w->bufstart + w->bufused)%LIGHTMAPBUFSIZE;
availspace = LIGHTMAPBUFSIZE - w->bufused;
availspace1 = min(availspace, LIGHTMAPBUFSIZE - bufend);
availspace2 = min(availspace, w->bufstart);
if(availspace >= needspace && (max(availspace1, availspace2) >= needspace || (availspace1 >= needspace1 && availspace2 >= needspace2))) break;
if(packlightmaps(w)) continue;
if(!w->spacecond || !tasklock) break;
w->needspace = true;
SDL_CondWait(w->spacecond, tasklock);
w->needspace = false;
}
if(tasklock) SDL_UnlockMutex(tasklock);
}
int usedspace = needspace;
lightmapinfo *l = NULL;
if(availspace1 >= needspace1)
{
l = (lightmapinfo *)&w->buf[bufend];
w->colorbuf = (uchar *)(l + 1);
if((w->type&LM_TYPE) != LM_BUMPMAP0) w->raybuf = NULL;
else if(availspace1 >= needspace) w->raybuf = (bvec *)&w->buf[bufend + needspace1];
else
{
w->raybuf = (bvec *)w->buf;
usedspace += availspace1 - needspace1;
}
}
else if(availspace2 >= needspace)
{
usedspace += availspace1;
l = (lightmapinfo *)w->buf;
w->colorbuf = (uchar *)(l + 1);
w->raybuf = (w->type&LM_TYPE) == LM_BUMPMAP0 ? (bvec *)&w->buf[needspace1] : NULL;
}
else return NULL;
w->bufused += usedspace;
l->next = NULL;
l->c = w->c;
l->type = w->type;
l->w = w->w;
l->h = w->h;
l->bpp = w->bpp;
l->colorbuf = w->colorbuf;
l->raybuf = w->raybuf;
l->packed = false;
l->bufsize = usedspace;
l->surface = -1;
l->layers = 0;
if(!w->firstlightmap) w->firstlightmap = l;
if(w->lastlightmap) w->lastlightmap->next = l;
w->lastlightmap = l;
if(!w->curlightmaps) w->curlightmaps = l;
return l;
}
static void freelightmap(lightmapworker *w)
{
lightmapinfo *l = w->lastlightmap;
if(!l || l->surface >= 0) return;
if(w->firstlightmap == w->lastlightmap)
{
w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL;
w->bufstart = w->bufused = 0;
}
else
{
w->bufused -= l->bufsize - sizeof(lightmapinfo);
l->bufsize = sizeof(lightmapinfo);
l->packed = true;
}
if(w->curlightmaps == l) w->curlightmaps = NULL;
}
static int setupsurface(lightmapworker *w, plane planes[2], int numplanes, const vec *p, const vec *n, int numverts, vertinfo *litverts, bool preview = false)
{
vec u, v, t;
vec2 c[MAXFACEVERTS];
u = vec(p[2]).sub(p[0]).normalize();
v.cross(planes[0], u);
c[0] = vec2(0, 0);
if(numplanes >= 2) t.cross(planes[1], u); else t = v;
vec r1 = vec(p[1]).sub(p[0]);
c[1] = vec2(r1.dot(u), min(r1.dot(v), 0.0f));
c[2] = vec2(vec(p[2]).sub(p[0]).dot(u), 0);
for(int i = 3; i < numverts; i++)
{
vec r = vec(p[i]).sub(p[0]);
c[i] = vec2(r.dot(u), max(r.dot(t), 0.0f));
}
float carea = 1e16f;
vec2 cx(0, 0), cy(0, 0), co(0, 0), cmin(0, 0), cmax(0, 0);
loopi(numverts)
{
vec2 px = vec2(c[i+1 < numverts ? i+1 : 0]).sub(c[i]);
float len = px.squaredlen();
if(!len) continue;
px.mul(1/sqrtf(len));
vec2 py(-px.y, px.x), pmin(0, 0), pmax(0, 0);
if(numplanes >= 2 && (i == 0 || i >= 3)) px.neg();
loopj(numverts)
{
vec2 rj = vec2(c[j]).sub(c[i]), pj(rj.dot(px), rj.dot(py));
pmin.x = min(pmin.x, pj.x);
pmin.y = min(pmin.y, pj.y);
pmax.x = max(pmax.x, pj.x);
pmax.y = max(pmax.y, pj.y);
}
float area = (pmax.x-pmin.x)*(pmax.y-pmin.y);
if(area < carea) { carea = area; cx = px; cy = py; co = c[i]; cmin = pmin; cmax = pmax; }
}
int scale = int(min(cmax.x - cmin.x, cmax.y - cmin.y));
float lpu = 16.0f / float(lightlod && scale < (1 << lightlod) ? max(lightprecision / 2, 1) : lightprecision);
int lw = clamp(int(ceil((cmax.x - cmin.x + 1)*lpu)), LM_MINW, LM_MAXW), lh = clamp(int(ceil((cmax.y - cmin.y + 1)*lpu)), LM_MINH, LM_MAXH);
w->w = lw;
w->h = lh;
if(!preview)
{
w->w += 2*blurlms;
w->h += 2*blurlms;
}
if(!alloclightmap(w)) return NO_SURFACE;
vec2 cscale = vec2(cmax).sub(cmin).div(vec2(lw-1, lh-1)),
comin = vec2(cx).mul(cmin.x).add(vec2(cy).mul(cmin.y)).add(co);
loopi(numverts)
{
vec2 ri = vec2(c[i]).sub(comin);
c[i] = vec2(ri.dot(cx)/cscale.x, ri.dot(cy)/cscale.y);
}
vec xstep1 = vec(v).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x),
ystep1 = vec(v).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y),
origin1 = vec(v).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]),
xstep2 = xstep1, ystep2 = ystep1, origin2 = origin1;
float side0 = LM_MAXW + 1, sidestep = 0;
if(numplanes >= 2)
{
xstep2 = vec(t).mul(cx.y).add(vec(u).mul(cx.x)).mul(cscale.x);
ystep2 = vec(t).mul(cy.y).add(vec(u).mul(cy.x)).mul(cscale.y);
origin2 = vec(t).mul(comin.y).add(vec(u).mul(comin.x)).add(p[0]);
if(cx.y) { side0 = comin.y/-(cx.y*cscale.x); sidestep = cy.y*cscale.y/-(cx.y*cscale.x); }
else if(cy.y) { side0 = ceil(comin.y/-(cy.y*cscale.y))*(LM_MAXW + 1); sidestep = -(LM_MAXW + 1); if(cy.y < 0) { side0 = (LM_MAXW + 1) - side0; sidestep = -sidestep; } }
else side0 = comin.y <= 0 ? LM_MAXW + 1 : -1;
}
int surftype = NO_SURFACE;
if(preview)
{
surftype = previewlightmapalpha(w, lpu, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep);
}
else
{
lerpvert lv[MAXFACEVERTS];
int numv = numverts;
calclerpverts(c, n, lv, numv);
if(!generatelightmap(w, lpu, lv, numv, origin1, xstep1, ystep1, origin2, xstep2, ystep2, side0, sidestep)) return NO_SURFACE;
surftype = finishlightmap(w);
}
if(surftype<SURFACE_LIGHTMAP) return surftype;
vec2 texscale(float(USHRT_MAX+1)/LM_PACKW, float(USHRT_MAX+1)/LM_PACKH);
if(lw != w->w) texscale.x *= float(w->w - 1) / (lw - 1);
if(lh != w->h) texscale.y *= float(w->h - 1) / (lh - 1);
loopk(numverts)
{
litverts[k].u = ushort(floor(clamp(c[k].x*texscale.x, 0.0f, float(USHRT_MAX))));
litverts[k].v = ushort(floor(clamp(c[k].y*texscale.y, 0.0f, float(USHRT_MAX))));
}
return surftype;
}
static void removelmalpha(lightmapworker *w)
{
if(!(w->type&LM_ALPHA)) return;
for(uchar *dst = w->colorbuf, *src = w->colorbuf, *end = &src[w->w*w->h*4];
src < end;
dst += 3, src += 4)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
}
w->type &= ~LM_ALPHA;
w->bpp = 3;
w->lastlightmap->type = w->type;
w->lastlightmap->bpp = w->bpp;
}
static lightmapinfo *setupsurfaces(lightmapworker *w, lightmaptask &task)
{
cube &c = *task.c;
const ivec &co = task.o;
int size = task.size, usefacemask = task.usefaces;
w->curlightmaps = NULL;
w->c = &c;
surfaceinfo surfaces[6];
vertinfo litverts[6*2*MAXFACEVERTS];
int numlitverts = 0;
memset(surfaces, 0, sizeof(surfaces));
loopi(6)
{
int usefaces = usefacemask&0xF;
usefacemask >>= 4;
if(!usefaces)
{
if(!c.ext) continue;
surfaceinfo &surf = surfaces[i];
surf = c.ext->surfaces[i];
int numverts = surf.totalverts();
if(numverts)
{
memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo));
surf.verts = numlitverts;
numlitverts += numverts;
}
continue;
}
VSlot &vslot = lookupvslot(c.texture[i], false),
*layer = vslot.layer && !(c.material&MAT_ALPHA) ? &lookupvslot(vslot.layer, false) : NULL;
Shader *shader = vslot.slot->shader;
int shadertype = shader->type;
if(layer) shadertype |= layer->slot->shader->type;
surfaceinfo &surf = surfaces[i];
vertinfo *curlitverts = &litverts[numlitverts];
int numverts = c.ext ? c.ext->surfaces[i].numverts&MAXFACEVERTS : 0;
ivec mo(co);
int msz = size, convex = 0;
if(numverts)
{
vertinfo *verts = c.ext->verts() + c.ext->surfaces[i].verts;
loopj(numverts) curlitverts[j].set(verts[j].getxyz());
if(c.merged&(1<<i))
{
msz = 1<<calcmergedsize(i, mo, size, verts, numverts);
mo.mask(~(msz-1));
if(!(surf.numverts&MAXFACEVERTS))
{
surf.verts = numlitverts;
surf.numverts |= numverts;
numlitverts += numverts;
}
}
else if(!flataxisface(c, i)) convex = faceconvexity(verts, numverts, size);
}
else
{
ivec v[4];
genfaceverts(c, i, v);
if(!flataxisface(c, i)) convex = faceconvexity(v);
int order = usefaces&4 || convex < 0 ? 1 : 0;
ivec vo = ivec(co).mask(0xFFF).shl(3);
curlitverts[numverts++].set(v[order].mul(size).add(vo));
if(usefaces&1) curlitverts[numverts++].set(v[order+1].mul(size).add(vo));
curlitverts[numverts++].set(v[order+2].mul(size).add(vo));
if(usefaces&2) curlitverts[numverts++].set(v[(order+3)&3].mul(size).add(vo));
}
vec pos[MAXFACEVERTS], n[MAXFACEVERTS], po(ivec(co).mask(~0xFFF));
loopj(numverts) pos[j] = vec(curlitverts[j].getxyz()).mul(1.0f/8).add(po);
plane planes[2];
int numplanes = 0;
planes[numplanes++].toplane(pos[0], pos[1], pos[2]);
if(numverts < 4 || !convex) loopk(numverts) findnormal(pos[k], planes[0], n[k]);
else
{
planes[numplanes++].toplane(pos[0], pos[2], pos[3]);
vec avg = vec(planes[0]).add(planes[1]).normalize();
findnormal(pos[0], avg, n[0]);
findnormal(pos[1], planes[0], n[1]);
findnormal(pos[2], avg, n[2]);
for(int k = 3; k < numverts; k++) findnormal(pos[k], planes[1], n[k]);
}
if(shadertype&(SHADER_NORMALSLMS | SHADER_ENVMAP))
{
loopk(numverts) curlitverts[k].norm = encodenormal(n[k]);
if(!(surf.numverts&MAXFACEVERTS))
{
surf.verts = numlitverts;
surf.numverts |= numverts;
numlitverts += numverts;
}
}
if(!findlights(w, mo.x, mo.y, mo.z, msz, pos, n, numverts, *vslot.slot, vslot))
{
if(surf.numverts&MAXFACEVERTS) surf.numverts |= LAYER_TOP;
continue;
}
w->slot = vslot.slot;
w->vslot = &vslot;
w->type = shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE;
if(layer) w->type |= LM_ALPHA;
w->bpp = w->type&LM_ALPHA ? 4 : 3;
w->orient = i;
w->rotate = vslot.rotation;
int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts);
switch(surftype)
{
case SURFACE_LIGHTMAP_BOTTOM:
if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS ||
(shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation))
{
freelightmap(w);
break;
}
// fall through
case SURFACE_LIGHTMAP_BLEND:
case SURFACE_LIGHTMAP_TOP:
{
if(!(surf.numverts&MAXFACEVERTS))
{
surf.verts = numlitverts;
surf.numverts |= numverts;
numlitverts += numverts;
}
w->lastlightmap->surface = i;
w->lastlightmap->layers = (surftype==SURFACE_LIGHTMAP_BOTTOM ? LAYER_BOTTOM : LAYER_TOP);
if(surftype==SURFACE_LIGHTMAP_BLEND)
{
surf.numverts |= LAYER_BLEND;
w->lastlightmap->layers = LAYER_TOP;
if((shader->type^layer->slot->shader->type)&SHADER_NORMALSLMS ||
(shader->type&SHADER_NORMALSLMS && vslot.rotation!=layer->rotation))
break;
w->lastlightmap->layers |= LAYER_BOTTOM;
}
else
{
if(surftype==SURFACE_LIGHTMAP_BOTTOM)
{
surf.numverts |= LAYER_BOTTOM;
w->lastlightmap->layers = LAYER_BOTTOM;
}
else
{
surf.numverts |= LAYER_TOP;
w->lastlightmap->layers = LAYER_TOP;
}
if(w->type&LM_ALPHA) removelmalpha(w);
}
continue;
}
case SURFACE_AMBIENT_BOTTOM:
freelightmap(w);
surf.numverts |= layer ? LAYER_BOTTOM : LAYER_TOP;
continue;
case SURFACE_AMBIENT_TOP:
freelightmap(w);
surf.numverts |= LAYER_TOP;
continue;
default:
freelightmap(w);
continue;
}
w->slot = layer->slot;
w->vslot = layer;
w->type = layer->slot->shader->type&SHADER_NORMALSLMS ? LM_BUMPMAP0 : LM_DIFFUSE;
w->bpp = 3;
w->rotate = layer->rotation;
vertinfo *blendverts = surf.numverts&MAXFACEVERTS ? &curlitverts[numverts] : curlitverts;
switch(setupsurface(w, planes, numplanes, pos, n, numverts, blendverts))
{
case SURFACE_LIGHTMAP_TOP:
{
if(!(surf.numverts&MAXFACEVERTS))
{
surf.verts = numlitverts;
surf.numverts |= numverts;
numlitverts += numverts;
}
else if(!(surf.numverts&LAYER_DUP))
{
surf.numverts |= LAYER_DUP;
w->lastlightmap->layers |= LAYER_DUP;
loopk(numverts)
{
vertinfo &src = curlitverts[k];
vertinfo &dst = blendverts[k];
dst.setxyz(src.getxyz());
dst.norm = src.norm;
}
numlitverts += numverts;
}
surf.numverts |= LAYER_BOTTOM;
w->lastlightmap->layers |= LAYER_BOTTOM;
w->lastlightmap->surface = i;
break;
}
case SURFACE_AMBIENT_TOP:
{
freelightmap(w);
surf.numverts |= LAYER_BOTTOM;
break;
}
default: freelightmap(w); break;
}
}
loopk(6)
{
surfaceinfo &surf = surfaces[k];
if(surf.used())
{
cubeext *ext = c.ext && c.ext->maxverts >= numlitverts ? c.ext : growcubeext(c.ext, numlitverts);
memcpy(ext->surfaces, surfaces, sizeof(ext->surfaces));
memcpy(ext->verts(), litverts, numlitverts*sizeof(vertinfo));
task.ext = ext;
break;
}
}
return w->curlightmaps ? w->curlightmaps : (lightmapinfo *)-1;
}
int lightmapworker::work(void *data)
{
lightmapworker *w = (lightmapworker *)data;
SDL_LockMutex(tasklock);
while(!w->doneworking)
{
if(allocidx < lightmaptasks[0].length())
{
lightmaptask &t = lightmaptasks[0][allocidx++];
t.worker = w;
SDL_UnlockMutex(tasklock);
lightmapinfo *l = setupsurfaces(w, t);
SDL_LockMutex(tasklock);
t.lightmaps = l;
packlightmaps(w);
}
else
{
if(packidx >= lightmaptasks[0].length()) SDL_CondSignal(emptycond);
SDL_CondWait(fullcond, tasklock);
}
}
SDL_UnlockMutex(tasklock);
return 0;
}
static bool processtasks(bool finish = false)
{
if(tasklock) SDL_LockMutex(tasklock);
while(finish || lightmaptasks[1].length())
{
if(packidx >= lightmaptasks[0].length())
{
if(lightmaptasks[1].empty()) break;
lightmaptasks[0].setsize(0);
lightmaptasks[0].move(lightmaptasks[1]);
packidx = allocidx = 0;
if(fullcond) SDL_CondBroadcast(fullcond);
}
else if(lightmapping > 1)
{
SDL_CondWaitTimeout(emptycond, tasklock, 250);
CHECK_PROGRESS_LOCKED({ SDL_UnlockMutex(tasklock); return false; }, SDL_UnlockMutex(tasklock), SDL_LockMutex(tasklock));
}
else
{
while(allocidx < lightmaptasks[0].length())
{
lightmaptask &t = lightmaptasks[0][allocidx++];
t.worker = lightmapworkers[0];
t.lightmaps = setupsurfaces(lightmapworkers[0], t);
packlightmaps(lightmapworkers[0]);
CHECK_PROGRESS(return false);
}
}
}
if(tasklock) SDL_UnlockMutex(tasklock);
return true;
}
static void generatelightmaps(cube *c, const ivec &co, int size)
{
CHECK_PROGRESS(return);
taskprogress++;
loopi(8)
{
ivec o(i, co, size);
if(c[i].children)
generatelightmaps(c[i].children, o, size >> 1);
else if(!isempty(c[i]))
{
if(c[i].ext)
{
loopj(6)
{
surfaceinfo &surf = c[i].ext->surfaces[j];
if(surf.lmid[0] >= LMID_RESERVED || surf.lmid[1] >= LMID_RESERVED) goto nextcube;
surf.clear();
}
}
int usefacemask = 0;
loopj(6) if(c[i].texture[j] != DEFAULT_SKY && (!(c[i].merged&(1<<j)) || (c[i].ext && c[i].ext->surfaces[j].numverts&MAXFACEVERTS)))
{
usefacemask |= visibletris(c[i], j, o, size)<<(4*j);
}
if(usefacemask)
{
lightmaptask &t = lightmaptasks[1].add();
t.o = o;
t.size = size;
t.usefaces = usefacemask;
t.c = &c[i];
t.ext = NULL;
t.lightmaps = NULL;
t.progress = taskprogress;
if(lightmaptasks[1].length() >= MAXLIGHTMAPTASKS && !processtasks()) return;
}
}
nextcube:;
}
}
static bool previewblends(lightmapworker *w, cube &c, const ivec &co, int size)
{
if(isempty(c) || c.material&MAT_ALPHA) return false;
int usefacemask = 0;
loopi(6) if(c.texture[i] != DEFAULT_SKY && lookupvslot(c.texture[i], false).layer)
usefacemask |= visibletris(c, i, co, size)<<(4*i);
if(!usefacemask) return false;
if(!setblendmaporigin(w->blendmapcache, co, size))
{
if(!c.ext) return false;
bool blends = false;
loopi(6) if(c.ext->surfaces[i].numverts&LAYER_BOTTOM)
{
c.ext->surfaces[i].brighten();
blends = true;
}
return blends;
}
w->firstlightmap = w->lastlightmap = w->curlightmaps = NULL;
w->bufstart = w->bufused = 0;
w->c = &c;
surfaceinfo surfaces[6];
vertinfo litverts[6*2*MAXFACEVERTS];
int numlitverts = 0;
memcpy(surfaces, c.ext ? c.ext->surfaces : brightsurfaces, sizeof(surfaces));
loopi(6)
{
int usefaces = usefacemask&0xF;
usefacemask >>= 4;
if(!usefaces)
{
surfaceinfo &surf = surfaces[i];
int numverts = surf.totalverts();
if(numverts)
{
memcpy(&litverts[numlitverts], c.ext->verts() + surf.verts, numverts*sizeof(vertinfo));
surf.verts = numlitverts;
numlitverts += numverts;
}
continue;
}
VSlot &vslot = lookupvslot(c.texture[i], false),
&layer = lookupvslot(vslot.layer, false);
Shader *shader = vslot.slot->shader;
int shadertype = shader->type | layer.slot->shader->type;
vertinfo *curlitverts = &litverts[numlitverts];
int numverts = 0;
ivec v[4];
genfaceverts(c, i, v);
int convex = flataxisface(c, i) ? 0 : faceconvexity(v),
order = usefaces&4 || convex < 0 ? 1 : 0;
ivec vo = ivec(co).mask(0xFFF).shl(3);
curlitverts[numverts++].set(v[order].mul(size).add(vo));
if(usefaces&1) curlitverts[numverts++].set(v[order+1].mul(size).add(vo));
curlitverts[numverts++].set(v[order+2].mul(size).add(vo));
if(usefaces&2) curlitverts[numverts++].set(v[(order+3)&3].mul(size).add(vo));
vec pos[4], n[4], po(ivec(co).mask(~0xFFF));
loopj(numverts) pos[j] = vec(curlitverts[j].getxyz()).mul(1.0f/8).add(po);
plane planes[2];
int numplanes = 0;
planes[numplanes++].toplane(pos[0], pos[1], pos[2]);
if(numverts < 4 || !convex) loopk(numverts) n[k] = planes[0];
else
{
planes[numplanes++].toplane(pos[0], pos[2], pos[3]);
vec avg = vec(planes[0]).add(planes[1]).normalize();
n[0] = avg;
n[1] = planes[0];
n[2] = avg;
for(int k = 3; k < numverts; k++) n[k] = planes[1];
}
surfaceinfo &surf = surfaces[i];
w->slot = vslot.slot;
w->vslot = &vslot;
w->type = shadertype&SHADER_NORMALSLMS ? LM_BUMPMAP0|LM_ALPHA : LM_DIFFUSE|LM_ALPHA;
w->bpp = 4;
w->orient = i;
w->rotate = vslot.rotation;
int surftype = setupsurface(w, planes, numplanes, pos, n, numverts, curlitverts, true);
switch(surftype)
{
case SURFACE_AMBIENT_TOP:
surf = brightsurface;
continue;
case SURFACE_AMBIENT_BOTTOM:
surf = brightbottomsurface;
continue;
case SURFACE_LIGHTMAP_BLEND:
{
if(surf.numverts == (LAYER_BLEND|numverts) &&
surf.lmid[0] == surf.lmid[1] &&
(surf.numverts&MAXFACEVERTS) == numverts &&
!memcmp(curlitverts, c.ext->verts() + surf.verts, numverts*sizeof(vertinfo)) &&
lightmaps.inrange(surf.lmid[0]-LMID_RESERVED) &&
lightmaps[surf.lmid[0]-LMID_RESERVED].type==w->type)
{
vertinfo *oldverts = c.ext->verts() + surf.verts;
layoutinfo layout;
layout.w = w->w;
layout.h = w->h;
layout.x = (oldverts[0].x - curlitverts[0].x)/((USHRT_MAX+1)/LM_PACKW);
layout.y = (oldverts[0].y - curlitverts[0].y)/((USHRT_MAX+1)/LM_PACKH);
if(LM_PACKW - layout.x >= w->w && LM_PACKH - layout.y >= w->h)
{
layout.lmid = surf.lmid[0];
copylightmap(*w->lastlightmap, layout);
updatelightmap(layout);
surf.verts = numlitverts;
numlitverts += numverts;
continue;
}
}
surf.verts = numlitverts;
surf.numverts = LAYER_BLEND|numverts;
numlitverts += numverts;
layoutinfo layout;
if(packlightmap(*w->lastlightmap, layout)) updatelightmap(layout);
surf.lmid[0] = surf.lmid[1] = layout.lmid;
ushort offsetx = layout.x*((USHRT_MAX+1)/LM_PACKW), offsety = layout.y*((USHRT_MAX+1)/LM_PACKH);
loopk(numverts)
{
vertinfo &v = curlitverts[k];
v.u += offsetx;
v.v += offsety;
}
continue;
}
}
}
setsurfaces(c, surfaces, litverts, numlitverts);
return true;
}
static bool previewblends(lightmapworker *w, cube *c, const ivec &co, int size, const ivec &bo, const ivec &bs)
{
bool changed = false;
loopoctabox(co, size, bo, bs)
{
ivec o(i, co, size);
cubeext *ext = c[i].ext;
if(ext && ext->va && ext->va->hasmerges)
{
changed = true;
destroyva(ext->va);
ext->va = NULL;
invalidatemerges(c[i], co, size, true);
}
if(c[i].children ? previewblends(w, c[i].children, o, size/2, bo, bs) : previewblends(w, c[i], o, size))
{
changed = true;
ext = c[i].ext;
if(ext && ext->va)
{
destroyva(ext->va);
ext->va = NULL;
}
}
}
return changed;
}
void previewblends(const ivec &bo, const ivec &bs)
{
loadlayermasks();
if(lightmapworkers.empty()) lightmapworkers.add(new lightmapworker);
lightmapworkers[0]->reset();
if(previewblends(lightmapworkers[0], worldroot, ivec(0, 0, 0), worldsize/2, bo, bs))
commitchanges(true);
}
void cleanuplightmaps()
{
loopv(lightmaps)
{
LightMap &lm = lightmaps[i];
lm.tex = lm.offsetx = lm.offsety = -1;
}
loopv(lightmaptexs) glDeleteTextures(1, &lightmaptexs[i].id);
lightmaptexs.shrink(0);
if(progresstex) { glDeleteTextures(1, &progresstex); progresstex = 0; }
}
void resetlightmaps(bool fullclean)
{
cleanuplightmaps();
lightmaps.shrink(0);
compressed.clear();
clearlightcache();
if(fullclean) while(lightmapworkers.length()) delete lightmapworkers.pop();
}
lightmapworker::lightmapworker()
{
buf = new uchar[LIGHTMAPBUFSIZE];
bufstart = bufused = 0;
firstlightmap = lastlightmap = curlightmaps = NULL;
ambient = new uchar[4*(LM_MAXW + 4)*(LM_MAXH + 4)];
blur = new uchar[4*(LM_MAXW + 4)*(LM_MAXH + 4)];
colordata = new vec[4*(LM_MAXW+1 + 4)*(LM_MAXH+1 + 4)];
raydata = new vec[(LM_MAXW + 4)*(LM_MAXH + 4)];
shadowraycache = newshadowraycache();
blendmapcache = newblendmapcache();
needspace = doneworking = false;
spacecond = NULL;
thread = NULL;
}
lightmapworker::~lightmapworker()
{
cleanupthread();
delete[] buf;
delete[] ambient;
delete[] blur;
delete[] colordata;
delete[] raydata;
freeshadowraycache(shadowraycache);
freeblendmapcache(blendmapcache);
}
void lightmapworker::cleanupthread()
{
if(spacecond) { SDL_DestroyCond(spacecond); spacecond = NULL; }
thread = NULL;
}
void lightmapworker::reset()
{
bufstart = bufused = 0;
firstlightmap = lastlightmap = curlightmaps = NULL;
needspace = doneworking = false;
resetshadowraycache(shadowraycache);
}
bool lightmapworker::setupthread()
{
if(!spacecond) spacecond = SDL_CreateCond();
if(!spacecond) return false;
thread = SDL_CreateThread(work, "lightmap worker", this);
return thread!=NULL;
}
static Uint32 calclighttimer(Uint32 interval, void *param)
{
check_calclight_progress = true;
return interval;
}
bool setlightmapquality(int quality)
{
switch(quality)
{
case 1: lmshadows = 2; lmaa = 3; lerptjoints = 1; break;
case 0: lmshadows = lmshadows_; lmaa = lmaa_; lerptjoints = lerptjoints_; break;
case -1: lmshadows = 1; lmaa = 0; lerptjoints = 0; break;
default: return false;
}
return true;
}
VARP(lightthreads, 0, 0, 16);
#define ALLOCLOCK(name, init) { if(lightmapping > 1) name = init(); if(!name) lightmapping = 1; }
#define FREELOCK(name, destroy) { if(name) { destroy(name); name = NULL; } }
static void cleanuplocks()
{
FREELOCK(lightlock, SDL_DestroyMutex);
FREELOCK(tasklock, SDL_DestroyMutex);
FREELOCK(fullcond, SDL_DestroyCond);
FREELOCK(emptycond, SDL_DestroyCond);
}
static void setupthreads(int numthreads)
{
loopi(2) lightmaptasks[i].setsize(0);
lightmapexts.setsize(0);
packidx = allocidx = 0;
lightmapping = numthreads;
if(lightmapping > 1)
{
ALLOCLOCK(lightlock, SDL_CreateMutex);
ALLOCLOCK(tasklock, SDL_CreateMutex);
ALLOCLOCK(fullcond, SDL_CreateCond);
ALLOCLOCK(emptycond, SDL_CreateCond);
}
while(lightmapworkers.length() < lightmapping) lightmapworkers.add(new lightmapworker);
loopi(lightmapping)
{
lightmapworker *w = lightmapworkers[i];
w->reset();
if(lightmapping <= 1 || w->setupthread()) continue;
w->cleanupthread();
lightmapping = i >= 1 ? max(i, 2) : 1;
break;
}
if(lightmapping <= 1) cleanuplocks();
}
static void cleanupthreads()
{
processtasks(true);
if(lightmapping > 1)
{
SDL_LockMutex(tasklock);
loopv(lightmapworkers) lightmapworkers[i]->doneworking = true;
SDL_CondBroadcast(fullcond);
loopv(lightmapworkers)
{
lightmapworker *w = lightmapworkers[i];
if(w->needspace && w->spacecond) SDL_CondSignal(w->spacecond);
}
SDL_UnlockMutex(tasklock);
loopv(lightmapworkers)
{
lightmapworker *w = lightmapworkers[i];
if(w->thread) SDL_WaitThread(w->thread, NULL);
}
}
loopv(lightmapexts)
{
lightmapext &e = lightmapexts[i];
setcubeext(*e.c, e.ext);
}
loopv(lightmapworkers) lightmapworkers[i]->cleanupthread();
cleanuplocks();
lightmapping = 0;
}
void calclight(int *quality)
{
if(!setlightmapquality(*quality))
{
conoutf(CON_ERROR, "valid range for calclight quality is -1..1");
return;
}
renderbackground("computing lightmaps... (esc to abort)");
mpremip(true);
optimizeblendmap();
loadlayermasks();
int numthreads = lightthreads > 0 ? lightthreads : numcpus;
if(numthreads > 1) preloadusedmapmodels(false, true);
resetlightmaps(false);
clearsurfaces(worldroot);
taskprogress = progress = 0;
progresstexticks = 0;
progresslightmap = -1;
calclight_canceled = false;
check_calclight_progress = false;
SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL);
Uint32 start = SDL_GetTicks();
calcnormals(lerptjoints > 0);
show_calclight_progress();
setupthreads(numthreads);
generatelightmaps(worldroot, ivec(0, 0, 0), worldsize >> 1);
cleanupthreads();
clearnormals();
Uint32 end = SDL_GetTicks();
if(timer) SDL_RemoveTimer(timer);
uint total = 0, lumels = 0;
loopv(lightmaps)
{
insertunlit(i);
if(!editmode) lightmaps[i].finalize();
total += lightmaps[i].lightmaps;
lumels += lightmaps[i].lumels;
}
if(!editmode) compressed.clear();
initlights();
renderbackground("lighting done...");
allchanged();
if(calclight_canceled)
conoutf("calclight aborted");
else
conoutf("generated %d lightmaps using %d%% of %d textures (%.1f seconds)",
total,
lightmaps.length() ? lumels * 100 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0,
lightmaps.length(),
(end - start) / 1000.0f);
}
COMMAND(calclight, "i");
VAR(patchnormals, 0, 0, 1);
void patchlight(int *quality)
{
if(noedit(true)) return;
if(!setlightmapquality(*quality))
{
conoutf(CON_ERROR, "valid range for patchlight quality is -1..1");
return;
}
renderbackground("patching lightmaps... (esc to abort)");
loadlayermasks();
int numthreads = lightthreads > 0 ? lightthreads : numcpus;
if(numthreads > 1) preloadusedmapmodels(false, true);
cleanuplightmaps();
taskprogress = progress = 0;
progresstexticks = 0;
progresslightmap = -1;
int total = 0, lumels = 0;
loopv(lightmaps)
{
if((lightmaps[i].type&LM_TYPE) != LM_BUMPMAP1) progresslightmap = i;
total -= lightmaps[i].lightmaps;
lumels -= lightmaps[i].lumels;
}
calclight_canceled = false;
check_calclight_progress = false;
SDL_TimerID timer = SDL_AddTimer(250, calclighttimer, NULL);
if(patchnormals) renderprogress(0, "computing normals...");
Uint32 start = SDL_GetTicks();
if(patchnormals) calcnormals(lerptjoints > 0);
show_calclight_progress();
setupthreads(numthreads);
generatelightmaps(worldroot, ivec(0, 0, 0), worldsize >> 1);
cleanupthreads();
if(patchnormals) clearnormals();
Uint32 end = SDL_GetTicks();
if(timer) SDL_RemoveTimer(timer);
loopv(lightmaps)
{
total += lightmaps[i].lightmaps;
lumels += lightmaps[i].lumels;
}
initlights();
renderbackground("lighting done...");
allchanged();
if(calclight_canceled)
conoutf("patchlight aborted");
else
conoutf("patched %d lightmaps using %d%% of %d textures (%.1f seconds)",
total,
lightmaps.length() ? lumels * 100 / (lightmaps.length() * LM_PACKW * LM_PACKH) : 0,
lightmaps.length(),
(end - start) / 1000.0f);
}
COMMAND(patchlight, "i");
void clearlightmaps()
{
if(noedit(true)) return;
renderprogress(0, "clearing lightmaps...");
resetlightmaps(false);
clearsurfaces(worldroot);
initlights();
allchanged();
}
COMMAND(clearlightmaps, "");
void setfullbrightlevel(int fullbrightlevel)
{
if(lightmaptexs.length() > LMID_BRIGHT)
{
uchar bright[3] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(fullbrightlevel) };
createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1);
}
initlights();
}
VARF(fullbright, 0, 0, 1, if(lightmaptexs.length()) { initlights(); lightents(); });
VARF(fullbrightlevel, 0, 128, 255, setfullbrightlevel(fullbrightlevel));
vector<LightMapTexture> lightmaptexs;
static void rotatenormals(LightMap &lmlv, int x, int y, int w, int h, int rotate)
{
bool flipx = rotate>=2 && rotate<=4,
flipy = (rotate>=1 && rotate<=2) || rotate==5,
swapxy = (rotate&5)==1;
uchar *lv = lmlv.data + 3*(y*LM_PACKW + x);
int stride = 3*(LM_PACKW-w);
loopi(h)
{
loopj(w)
{
if(flipx) lv[0] = 255 - lv[0];
if(flipy) lv[1] = 255 - lv[1];
if(swapxy) swap(lv[0], lv[1]);
lv += 3;
}
lv += stride;
}
}
static void rotatenormals(cube *c)
{
loopi(8)
{
cube &ch = c[i];
if(ch.children)
{
rotatenormals(ch.children);
continue;
}
else if(!ch.ext) continue;
loopj(6) if(lightmaps.inrange(ch.ext->surfaces[j].lmid[0]+1-LMID_RESERVED))
{
VSlot &vslot = lookupvslot(ch.texture[j], false);
if(!vslot.rotation) continue;
surfaceinfo &surface = ch.ext->surfaces[j];
int numverts = surface.numverts&MAXFACEVERTS;
if(!numverts) continue;
LightMap &lmlv = lightmaps[surface.lmid[0]+1-LMID_RESERVED];
if((lmlv.type&LM_TYPE)!=LM_BUMPMAP1) continue;
ushort x1 = USHRT_MAX, y1 = USHRT_MAX, x2 = 0, y2 = 0;
vertinfo *verts = ch.ext->verts() + surface.verts;
loopk(numverts)
{
vertinfo &v = verts[k];
x1 = min(x1, v.u);
y1 = min(y1, v.u);
x2 = max(x2, v.u);
y2 = max(y2, v.v);
}
if(x1 > x2 || y1 > y2) continue;
x1 /= (USHRT_MAX+1)/LM_PACKW;
y1 /= (USHRT_MAX+1)/LM_PACKH;
x2 /= (USHRT_MAX+1)/LM_PACKW;
y2 /= (USHRT_MAX+1)/LM_PACKH;
rotatenormals(lmlv, x1, y1, x2-x1, y1-y1, vslot.rotation < 4 ? 4-vslot.rotation : vslot.rotation);
}
}
}
void fixlightmapnormals()
{
rotatenormals(worldroot);
}
void fixrotatedlightmaps(cube &c, const ivec &co, int size)
{
if(c.children)
{
loopi(8) fixrotatedlightmaps(c.children[i], ivec(i, co, size>>1), size>>1);
return;
}
if(!c.ext) return;
loopi(6)
{
if(c.merged&(1<<i)) continue;
surfaceinfo &surf = c.ext->surfaces[i];
int numverts = surf.numverts&MAXFACEVERTS;
if(numverts!=4 || (surf.lmid[0] < LMID_RESERVED && surf.lmid[1] < LMID_RESERVED)) continue;
vertinfo *verts = c.ext->verts() + surf.verts;
int vis = visibletris(c, i, co, size);
if(!vis || vis==3) continue;
if((verts[0].u != verts[1].u || verts[0].v != verts[1].v) &&
(verts[0].u != verts[3].u || verts[0].v != verts[3].v) &&
(verts[2].u != verts[1].u || verts[2].v != verts[1].v) &&
(verts[2].u != verts[3].u || verts[2].v != verts[3].v))
continue;
if(vis&4)
{
vertinfo tmp = verts[0];
verts[0].x = verts[1].x; verts[0].y = verts[1].y; verts[0].z = verts[1].z;
verts[1].x = verts[2].x; verts[1].y = verts[2].y; verts[1].z = verts[2].z;
verts[2].x = verts[3].x; verts[2].y = verts[3].y; verts[2].z = verts[3].z;
verts[3].x = tmp.x; verts[3].y = tmp.y; verts[3].z = tmp.z;
if(surf.numverts&LAYER_DUP) loopk(4)
{
vertinfo &v = verts[k], &b = verts[k+4];
b.x = v.x;
b.y = v.y;
b.z = v.z;
}
}
surf.numverts = (surf.numverts & ~MAXFACEVERTS) | 3;
if(vis&2)
{
verts[1] = verts[2]; verts[2] = verts[3];
if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[6]; verts[5] = verts[7]; }
}
else if(surf.numverts&LAYER_DUP) { verts[3] = verts[4]; verts[4] = verts[5]; verts[5] = verts[6]; }
}
}
void fixrotatedlightmaps()
{
loopi(8) fixrotatedlightmaps(worldroot[i], ivec(i, ivec(0, 0, 0), worldsize>>1), worldsize>>1);
}
static void copylightmap(LightMap &lm, uchar *dst, size_t stride)
{
const uchar *c = lm.data;
loopi(LM_PACKH)
{
memcpy(dst, c, lm.bpp*LM_PACKW);
c += lm.bpp*LM_PACKW;
dst += stride;
}
}
void genreservedlightmaptexs()
{
while(lightmaptexs.length() < LMID_RESERVED)
{
LightMapTexture &tex = lightmaptexs.add();
tex.type = lightmaptexs.length()&1 ? LM_DIFFUSE : LM_BUMPMAP1;
glGenTextures(1, &tex.id);
}
uchar unlit[3] = { ambientcolor[0], ambientcolor[1], ambientcolor[2] };
createtexture(lightmaptexs[LMID_AMBIENT].id, 1, 1, unlit, 0, 1);
bvec front(128, 128, 255);
createtexture(lightmaptexs[LMID_AMBIENT1].id, 1, 1, &front, 0, 1);
uchar bright[3] = { uchar(fullbrightlevel), uchar(fullbrightlevel), uchar(fullbrightlevel) };
createtexture(lightmaptexs[LMID_BRIGHT].id, 1, 1, bright, 0, 1);
createtexture(lightmaptexs[LMID_BRIGHT1].id, 1, 1, &front, 0, 1);
uchar dark[3] = { 0, 0, 0 };
createtexture(lightmaptexs[LMID_DARK].id, 1, 1, dark, 0, 1);
createtexture(lightmaptexs[LMID_DARK1].id, 1, 1, &front, 0, 1);
}
static void findunlit(int i)
{
LightMap &lm = lightmaps[i];
if(lm.unlitx>=0) return;
else if((lm.type&LM_TYPE)==LM_BUMPMAP0)
{
if(i+1>=lightmaps.length() || (lightmaps[i+1].type&LM_TYPE)!=LM_BUMPMAP1) return;
}
else if((lm.type&LM_TYPE)!=LM_DIFFUSE) return;
uchar *data = lm.data;
loop(y, 2) loop(x, LM_PACKW)
{
if(!data[0] && !data[1] && !data[2])
{
memcpy(data, ambientcolor.v, 3);
if((lm.type&LM_TYPE)==LM_BUMPMAP0) ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] = bvec(128, 128, 255);
lm.unlitx = x;
lm.unlity = y;
return;
}
if(data[0]==ambientcolor[0] && data[1]==ambientcolor[1] && data[2]==ambientcolor[2])
{
if((lm.type&LM_TYPE)!=LM_BUMPMAP0 || ((bvec *)lightmaps[i+1].data)[y*LM_PACKW + x] == bvec(128, 128, 255))
{
lm.unlitx = x;
lm.unlity = y;
return;
}
}
data += lm.bpp;
}
}
VARF(roundlightmaptex, 0, 4, 16, { cleanuplightmaps(); initlights(); allchanged(); });
VARF(batchlightmaps, 0, 4, 256, { cleanuplightmaps(); initlights(); allchanged(); });
void genlightmaptexs(int flagmask, int flagval)
{
if(lightmaptexs.length() < LMID_RESERVED) genreservedlightmaptexs();
int remaining[3] = { 0, 0, 0 }, total = 0;
loopv(lightmaps)
{
LightMap &lm = lightmaps[i];
if(lm.tex >= 0 || (lm.type&flagmask)!=flagval) continue;
int type = lm.type&LM_TYPE;
remaining[type]++;
total++;
if(lm.unlitx < 0) findunlit(i);
}
int sizelimit = (maxtexsize ? min(maxtexsize, hwtexsize) : hwtexsize)/max(LM_PACKW, LM_PACKH);
sizelimit = min(batchlightmaps, sizelimit*sizelimit);
while(total)
{
int type = LM_DIFFUSE;
LightMap *firstlm = NULL;
loopv(lightmaps)
{
LightMap &lm = lightmaps[i];
if(lm.tex >= 0 || (lm.type&flagmask) != flagval) continue;
type = lm.type&LM_TYPE;
firstlm = &lm;
break;
}
if(!firstlm) break;
int used = 0, uselimit = min(remaining[type], sizelimit);
do used++; while((1<<used) <= uselimit);
used--;
int oldval = remaining[type];
remaining[type] -= 1<<used;
if(remaining[type] && (2<<used) <= min(roundlightmaptex, sizelimit))
{
remaining[type] -= min(remaining[type], 1<<used);
used++;
}
total -= oldval - remaining[type];
LightMapTexture &tex = lightmaptexs.add();
tex.type = firstlm->type;
tex.w = LM_PACKW<<((used+1)/2);
tex.h = LM_PACKH<<(used/2);
int bpp = firstlm->bpp;
uchar *data = used ? new uchar[bpp*tex.w*tex.h] : NULL;
int offsetx = 0, offsety = 0;
loopv(lightmaps)
{
LightMap &lm = lightmaps[i];
if(lm.tex >= 0 || (lm.type&flagmask) != flagval || (lm.type&LM_TYPE) != type) continue;
lm.tex = lightmaptexs.length()-1;
lm.offsetx = offsetx;
lm.offsety = offsety;
if(tex.unlitx < 0 && lm.unlitx >= 0)
{
tex.unlitx = offsetx + lm.unlitx;
tex.unlity = offsety + lm.unlity;
}
if(data) copylightmap(lm, &data[bpp*(offsety*tex.w + offsetx)], bpp*tex.w);
offsetx += LM_PACKW;
if(offsetx >= tex.w) { offsetx = 0; offsety += LM_PACKH; }
if(offsety >= tex.h) break;
}
glGenTextures(1, &tex.id);
createtexture(tex.id, tex.w, tex.h, data ? data : firstlm->data, 3, 1, bpp==4 ? GL_RGBA : GL_RGB);
if(data) delete[] data;
}
}
bool brightengeom = false, shouldlightents = false;
void clearlights()
{
clearlightcache();
const vector<extentity *> &ents = entities::getents();
loopv(ents)
{
extentity &e = *ents[i];
e.light.color = vec(1, 1, 1);
e.light.dir = vec(0, 0, 1);
}
shouldlightents = false;
genlightmaptexs(LM_ALPHA, 0);
genlightmaptexs(LM_ALPHA, LM_ALPHA);
brightengeom = true;
}
void lightent(extentity &e, float height)
{
if(e.type==ET_LIGHT) return;
float ambient = 0.0f;
if(e.type==ET_MAPMODEL)
{
model *m = loadmodel(NULL, e.attr2);
if(m) height = m->above()*0.75f;
}
else if(e.type>=ET_GAMESPECIFIC) ambient = 0.4f;
vec target(e.o.x, e.o.y, e.o.z + height);
lightreaching(target, e.light.color, e.light.dir, false, &e, ambient);
}
void lightents(bool force)
{
if(!force && !shouldlightents) return;
const vector<extentity *> &ents = entities::getents();
loopv(ents) lightent(*ents[i]);
shouldlightents = false;
}
void initlights()
{
if((fullbright && editmode) || lightmaps.empty())
{
clearlights();
return;
}
clearlightcache();
genlightmaptexs(LM_ALPHA, 0);
genlightmaptexs(LM_ALPHA, LM_ALPHA);
brightengeom = false;
shouldlightents = true;
}
static inline void fastskylight(const vec &o, float tolerance, uchar *skylight, int flags = RAY_ALPHAPOLY, extentity *t = NULL, bool fast = false)
{
flags |= RAY_SHADOW;
if(skytexturelight) flags |= RAY_SKIPSKY;
if(fast)
{
static const vec ray(0, 0, 1);
if(shadowray(vec(ray).mul(tolerance).add(o), ray, 1e16f, flags, t)>1e15f)
memcpy(skylight, skylightcolor.v, 3);
else memcpy(skylight, ambientcolor.v, 3);
}
else
{
static const vec rays[5] =
{
vec(cosf(66*RAD)*cosf(65*RAD), sinf(66*RAD)*cosf(65*RAD), sinf(65*RAD)),
vec(cosf(156*RAD)*cosf(65*RAD), sinf(156*RAD)*cosf(65*RAD), sinf(65*RAD)),
vec(cosf(246*RAD)*cosf(65*RAD), sinf(246*RAD)*cosf(65*RAD), sinf(65*RAD)),
vec(cosf(336*RAD)*cosf(65*RAD), sinf(336*RAD)*cosf(65*RAD), sinf(65*RAD)),
vec(0, 0, 1),
};
int hit = 0;
loopi(5) if(shadowray(vec(rays[i]).mul(tolerance).add(o), rays[i], 1e16f, flags, t)>1e15f) hit++;
loopk(3) skylight[k] = uchar(ambientcolor[k] + (max(skylightcolor[k], ambientcolor[k]) - ambientcolor[k])*hit/5.0f);
}
}
void lightreaching(const vec &target, vec &color, vec &dir, bool fast, extentity *t, float ambient)
{
if((fullbright && editmode) || lightmaps.empty())
{
color = vec(1, 1, 1);
dir = vec(0, 0, 1);
return;
}
color = dir = vec(0, 0, 0);
const vector<extentity *> &ents = entities::getents();
const vector<int> &lights = checklightcache(int(target.x), int(target.y));
loopv(lights)
{
extentity &e = *ents[lights[i]];
if(e.type != ET_LIGHT)
continue;
vec ray(target);
ray.sub(e.o);
float mag = ray.magnitude();
if(e.attr1 && mag >= float(e.attr1))
continue;
if(mag < 1e-4f) ray = vec(0, 0, -1);
else
{
ray.div(mag);
if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY, t) < mag)
continue;
}
float intensity = 1;
if(e.attr1)
intensity -= mag / float(e.attr1);
if(e.attached && e.attached->type==ET_SPOTLIGHT)
{
vec spot = vec(e.attached->o).sub(e.o).normalize();
float maxatten = sincos360[clamp(int(e.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten);
if(spotatten <= 0) continue;
intensity *= spotatten;
}
//if(target==player->o)
//{
// conoutf(CON_DEBUG, "%d - %f %f", i, intensity, mag);
//}
vec lightcol = vec(e.attr2, e.attr3, e.attr4).mul(1.0f/255);
color.add(vec(lightcol).mul(intensity));
dir.add(vec(ray).mul(-intensity*lightcol.x*lightcol.y*lightcol.z));
}
if(sunlight && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0), t) > 1e15f)
{
vec lightcol = vec(sunlightcolor.x, sunlightcolor.y, sunlightcolor.z).mul(sunlightscale/255);
color.add(lightcol);
dir.add(vec(sunlightdir).mul(lightcol.x*lightcol.y*lightcol.z));
}
if(hasskylight())
{
uchar skylight[3];
if(t) calcskylight(NULL, target, vec(0, 0, 0), 0.5f, skylight, RAY_POLY, t);
else fastskylight(target, 0.5f, skylight, RAY_POLY, t, fast);
loopk(3) color[k] = min(1.5f, max(max(skylight[k]/255.0f, ambient), color[k]));
}
else loopk(3) color[k] = min(1.5f, max(max(ambientcolor[k]/255.0f, ambient), color[k]));
if(dir.iszero()) dir = vec(0, 0, 1);
else dir.normalize();
}
entity *brightestlight(const vec &target, const vec &dir)
{
if(sunlight && sunlightdir.dot(dir) > 0 && shadowray(target, sunlightdir, 1e16f, RAY_SHADOW | RAY_POLY | (skytexturelight ? RAY_SKIPSKY : 0)) > 1e15f)
return &sunlightent;
const vector<extentity *> &ents = entities::getents();
const vector<int> &lights = checklightcache(int(target.x), int(target.y));
extentity *brightest = NULL;
float bintensity = 0;
loopv(lights)
{
extentity &e = *ents[lights[i]];
if(e.type != ET_LIGHT || vec(e.o).sub(target).dot(dir)<0)
continue;
vec ray(target);
ray.sub(e.o);
float mag = ray.magnitude();
if(e.attr1 && mag >= float(e.attr1))
continue;
ray.div(mag);
if(shadowray(e.o, ray, mag, RAY_SHADOW | RAY_POLY) < mag)
continue;
float intensity = 1;
if(e.attr1)
intensity -= mag / float(e.attr1);
if(e.attached && e.attached->type==ET_SPOTLIGHT)
{
vec spot = vec(e.attached->o).sub(e.o).normalize();
float maxatten = sincos360[clamp(int(e.attached->attr1), 1, 89)].x, spotatten = (ray.dot(spot) - maxatten) / (1 - maxatten);
if(spotatten <= 0) continue;
intensity *= spotatten;
}
if(!brightest || intensity > bintensity)
{
brightest = &e;
bintensity = intensity;
}
}
return brightest;
}
void dumplms()
{
loopv(lightmaps)
{
ImageData temp(LM_PACKW, LM_PACKH, lightmaps[i].bpp, lightmaps[i].data);
const char *map = game::getclientmap(), *name = strrchr(map, '/');
defformatstring(buf, "lightmap_%s_%d.png", name ? name+1 : map, i);
savepng(buf, temp, true);
}
}
COMMAND(dumplms, "");
|
; BEGIN_LEGAL
; Intel Open Source License
;
; Copyright (c) 2002-2017 Intel Corporation. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are
; met:
;
; Redistributions of source code must retain the above copyright notice,
; this list of conditions and the following disclaimer. Redistributions
; in binary form must reproduce the above copyright notice, this list of
; conditions and the following disclaimer in the documentation and/or
; other materials provided with the distribution. Neither the name of
; the Intel Corporation nor the names of its contributors may be used to
; endorse or promote products derived from this software without
; specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
; ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
; END_LEGAL
PUBLIC TestDfByMovsd
.686
.model flat, c
extern source:word
extern dest:word
.code
TestDfByMovsd PROC
push esi
push edi
lea esi, source+4
lea edi, dest+4
movsd
movsd
pop edi
pop esi
ret
TestDfByMovsd ENDP
end |
; A183314: Number of n X 2 binary arrays with an element zero only if there are an even number of ones to its left and an even number of ones above it.
; Submitted by Christian Krause
; 3,6,13,27,57,119,250,523,1097,2297,4815,10086,21137,44283,92793,194419,407378,853559,1788481,3747361,7851867,16451910,34471669,72228171,151339401,317100335,664418698,1392152131,2916968489,6111905849,12806240487,26832837414,56222684537,117803050443,246832026153,517185655531,1083655999010,2270577889007,4757528204353,9968420216833,20886770941875,43763925499014,91698289903453,192134875241787,402579048511257,843521458834151,1767425439222682,3703275891972091,7759451702294729,16258332480154169
lpb $0
sub $0,1
sub $3,$4
add $3,1
add $1,$3
add $4,1
add $4,$2
add $2,$3
mov $5,$4
mov $4,$2
mov $2,$3
add $4,$1
add $5,$4
mov $3,$5
lpe
mov $0,$3
add $0,3
|
.data
msg1: .asciiz "Give a number: "
list: .space 400
.text
.globl main
main:
li $v0, 4
la $a0, msg1
syscall # print msg
li $v0, 5
syscall # read an int
add $a0, $v0, $zero # move to $a0
addi $s1,$a0,0
la $t0,list
li $t6,1
sw $t6,0($t0)
sw $t6,4($t0)
jal fb
addi $a0,$a0,-1
sll $a0,$a0,2
add $t0,$t0,$a0
lw $a0,($t0)
li $v0, 1
syscall
li $v0, 10
syscall
fb:
addi $sp,$sp,-8
sw $ra,0($sp)
sw $a0,4($sp)
beq $a0,0,fbout
addi $a0,$a0,-1
jal fb
fbout:
lw $ra,0($sp)
lw $t2,4($sp)
addi $sp,$sp,8
addi $a0,$t2,0 # keep $a0 as input
addi $t1,$t0,0
sll $t2,$t2,2
add $t1,$t1,$t2 #a[i]
lw $t3,0($t1)
addi $t1,$t1,4 #a[i+1]
lw $t4,0($t1)
add $t5,$t3,$t4 #a[i+2]=a[i]+a[i+1]
addi $t1,$t1,4
sw $t5,($t1)
jr $ra
|
; SPIR-V
; Version: 1.0
; Generator: Khronos Glslang Reference Front End; 10
; Bound: 81
; Schema: 0
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %4 "main" %62
OpExecutionMode %4 OriginUpperLeft
OpSource ESSL 320
OpName %4 "main"
OpName %8 "f0"
OpName %12 "buf0"
OpMemberName %12 0 "_GLF_uniform_float_values"
OpName %14 ""
OpName %20 "f1"
OpName %28 "f2"
OpName %34 "f3"
OpName %38 "buf2"
OpMemberName %38 0 "one"
OpName %40 ""
OpName %50 "buf1"
OpMemberName %50 0 "_GLF_uniform_int_values"
OpName %52 ""
OpName %62 "_GLF_color"
OpDecorate %11 ArrayStride 16
OpMemberDecorate %12 0 Offset 0
OpDecorate %12 Block
OpDecorate %14 DescriptorSet 0
OpDecorate %14 Binding 0
OpMemberDecorate %38 0 Offset 0
OpDecorate %38 Block
OpDecorate %40 DescriptorSet 0
OpDecorate %40 Binding 2
OpDecorate %49 ArrayStride 16
OpMemberDecorate %50 0 Offset 0
OpDecorate %50 Block
OpDecorate %52 DescriptorSet 0
OpDecorate %52 Binding 1
OpDecorate %62 Location 0
%2 = OpTypeVoid
%3 = OpTypeFunction %2
%6 = OpTypeFloat 32
%7 = OpTypePointer Function %6
%9 = OpTypeInt 32 0
%10 = OpConstant %9 2
%11 = OpTypeArray %6 %10
%12 = OpTypeStruct %11
%13 = OpTypePointer Uniform %12
%14 = OpVariable %13 Uniform
%15 = OpTypeInt 32 1
%16 = OpConstant %15 0
%17 = OpTypePointer Uniform %6
%21 = OpConstant %15 1
%25 = OpConstant %6 4
%38 = OpTypeStruct %6
%39 = OpTypePointer Uniform %38
%40 = OpVariable %39 Uniform
%49 = OpTypeArray %15 %10
%50 = OpTypeStruct %49
%51 = OpTypePointer Uniform %50
%52 = OpVariable %51 Uniform
%53 = OpTypePointer Uniform %15
%56 = OpTypeBool
%60 = OpTypeVector %6 4
%61 = OpTypePointer Output %60
%62 = OpVariable %61 Output
%4 = OpFunction %2 None %3
%5 = OpLabel
%8 = OpVariable %7 Function
%20 = OpVariable %7 Function
%28 = OpVariable %7 Function
%34 = OpVariable %7 Function
%18 = OpAccessChain %17 %14 %16 %16
%19 = OpLoad %6 %18
OpStore %8 %19
%22 = OpAccessChain %17 %14 %16 %21
%23 = OpLoad %6 %22
%24 = OpLoad %6 %8
%26 = OpExtInst %6 %1 Pow %24 %25
%27 = OpFMul %6 %23 %26
OpStore %20 %27
%29 = OpAccessChain %17 %14 %16 %21
%30 = OpLoad %6 %29
%31 = OpLoad %6 %8
%32 = OpExtInst %6 %1 Pow %31 %25
%33 = OpFMul %6 %30 %32
OpStore %28 %33
%35 = OpLoad %6 %20
%36 = OpLoad %6 %28
%37 = OpFSub %6 %35 %36
%41 = OpAccessChain %17 %40 %16
%42 = OpLoad %6 %41
%43 = OpFSub %6 %37 %42
%44 = OpLoad %6 %8
%45 = OpFAdd %6 %43 %44
%46 = OpExtInst %6 %1 Sqrt %45
OpStore %34 %46
%47 = OpLoad %6 %34
%48 = OpConvertFToS %15 %47
%54 = OpAccessChain %53 %52 %16 %16
%55 = OpLoad %15 %54
%57 = OpIEqual %56 %48 %55
OpSelectionMerge %59 None
OpBranchConditional %57 %58 %76
%58 = OpLabel
%63 = OpAccessChain %53 %52 %16 %16
%64 = OpLoad %15 %63
%65 = OpConvertSToF %6 %64
%66 = OpAccessChain %53 %52 %16 %21
%67 = OpLoad %15 %66
%68 = OpConvertSToF %6 %67
%69 = OpAccessChain %53 %52 %16 %21
%70 = OpLoad %15 %69
%71 = OpConvertSToF %6 %70
%72 = OpAccessChain %53 %52 %16 %16
%73 = OpLoad %15 %72
%74 = OpConvertSToF %6 %73
%75 = OpCompositeConstruct %60 %65 %68 %71 %74
OpStore %62 %75
OpBranch %59
%76 = OpLabel
%77 = OpAccessChain %53 %52 %16 %21
%78 = OpLoad %15 %77
%79 = OpConvertSToF %6 %78
%80 = OpCompositeConstruct %60 %79 %79 %79 %79
OpStore %62 %80
OpBranch %59
%59 = OpLabel
OpReturn
OpFunctionEnd
|
; A111052: Numbers n such that 3*n^2 + 4 is prime.
; Submitted by Simon Strandgaard
; 1,3,5,7,11,19,21,25,31,33,37,39,45,49,53,73,75,77,81,89,91,93,107,115,119,129,131,135,137,145,157,185,187,193,203,205,207,213,215,221,227,229,231,249,259,261,263,271,283,291,297,299,301,317,325,327,331,343,345,357,359,361,387,395,397,401,413,415,417,423,429,439,441,471,481,497,501,509,513,515,521,525,527,549,551,585,593,613,619,621,639,647,649,663,681,683,691,703,705,707
mov $2,332202
lpb $2
add $6,6
mov $3,$6
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,24
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,18
add $5,$1
mov $6,$5
lpe
mov $0,$1
div $0,12
add $0,1
|
; A294629: Partial sums of A294628.
; 4,16,28,56,68,120,132,192,228,296,308,440,452,536,612,736,748,920,932,1112,1204,1320,1332,1624,1676,1808,1916,2144,2156,2496,2508,2760,2884,3048,3156,3600,3612,3792,3932,4336,4348,4784,4796,5120,5388,5600,5612,6224,6292,6640,6812,7184,7196,7728,7868,8384,8572,8832,8844,9712,9724,10000,10332,10840,10996,11624,11636,12104,12324,12920,12932,13920,13932,14256,14652,15168,15324,16048,16060,16912,17236,17592,17604,18728,18916,19288,19556,20296,20308,21464,21636,22248,22532,22936,23140,24392,24404
mov $3,$0
seq $0,244049 ; Sum of all proper divisors of all positive integers <= n.
mul $0,2
add $0,1
mov $2,$3
mul $2,3
add $0,$2
mul $0,4
|
#include "Platform.inc"
#include "FarCalls.inc"
#include "Lcd.inc"
#include "../../../../firmware/Platform/Lcd/Isr.inc"
#include "TestFixture.inc"
radix decimal
LcdFlagsAreAllClearedTest code
global testArrange
testArrange:
banksel TMR0
movf TMR0, W
banksel lcdFlags
movwf lcdFlags
testAct:
fcall initialiseLcd
testAssert:
banksel lcdFlags
.assert "lcdFlags == 0, 'Expected all lcdFlags to be cleared.'"
return
end
|
; A187272: a(n) = (n/4)*2^(n/2)*((1+sqrt(2))^2 + (-1)^n*(1-sqrt(2))^2).
; 0,2,6,12,24,40,72,112,192,288,480,704,1152,1664,2688,3840,6144,8704,13824,19456,30720,43008,67584,94208,147456,204800,319488,442368,688128,950272,1474560,2031616,3145728,4325376,6684672,9175040,14155776,19398656,29884416,40894464,62914560,85983232,132120576,180355072,276824064,377487360,578813952,788529152,1207959552,1644167168,2516582400,3422552064,5234491392,7113539584,10871635968,14763950080,22548578304,30601641984,46707769344,63350767616,96636764160,130996502528,199715979264,270582939648,412316860416,558345748480,850403524608,1151051235328,1752346656768,2370821947392,3607772528640,4879082848256,7421703487488,10033043603456,15255723835392,20615843020800,31336081391616,42331197669376,64321430224896,86861418594304,131941395333120,178120883699712,270479860432896,365037860421632,554153860399104,747667906887680,1134695999864832,1530520185864192,2322168557862912,3131409115906048,4749890231992320,6403555720167424
mov $1,$0
mul $1,2
mov $2,$0
lpb $2,1
add $1,$3
mov $3,$0
mov $0,$1
sub $0,$3
sub $2,1
lpe
|
<%
from pwnlib.shellcraft import i386
from pwnlib.context import context as ctx # Ugly hack, mako will not let it be called context
%>
<%page args="value"/>
<%docstring>
Thin wrapper around :func:`pwnlib.shellcraft.i386.push`, which sets
`context.os` to `'freebsd'` before calling.
Example:
>>> print pwnlib.shellcraft.i386.freebsd.push('SYS_execve').rstrip()
/* push 'SYS_execve' */
push 0x3b
</%docstring>
% with ctx.local(os = 'freebsd'):
${i386.push(value)}
% endwith
|
; A231688: a(n) = Sum_{i=0..n} digsum(i)^3, where digsum(i) = A007953(i).
; 0,1,9,36,100,225,441,784,1296,2025,2026,2034,2061,2125,2250,2466,2809,3321,4050,5050,5058,5085,5149,5274,5490,5833,6345,7074,8074,9405,9432,9496,9621,9837,10180,10692,11421,12421,13752,15480,15544,15669,15885,16228,16740,17469,18469,19800,21528,23725,23850,24066,24409,24921,25650,26650,27981,29709,31906,34650,34866,35209,35721,36450,37450,38781,40509,42706,45450,48825,49168,49680,50409,51409,52740,54468,56665,59409,62784,66880,67392,68121,69121,70452,72180,74377,77121,80496,84592,89505,90234,91234,92565,94293,96490,99234,102609,106705,111618,117450,117451,117459,117486,117550,117675,117891,118234,118746,119475,120475,120483,120510,120574,120699,120915,121258,121770,122499,123499,124830,124857,124921,125046,125262,125605,126117,126846,127846,129177,130905,130969,131094,131310,131653,132165,132894,133894,135225,136953,139150,139275,139491,139834,140346,141075,142075,143406,145134,147331,150075,150291,150634,151146,151875,152875,154206,155934,158131,160875,164250,164593,165105,165834,166834,168165,169893,172090,174834,178209,182305,182817,183546,184546,185877,187605,189802,192546,195921,200017,204930,205659,206659,207990,209718,211915,214659,218034,222130,227043,232875,233875,235206,236934,239131,241875,245250,249346,254259,260091,266950,266958,266985,267049,267174,267390,267733,268245,268974,269974,271305,271332,271396,271521,271737,272080,272592,273321,274321,275652,277380,277444,277569,277785,278128,278640,279369,280369,281700,283428,285625,285750,285966,286309,286821,287550,288550,289881,291609,293806,296550,296766,297109,297621,298350,299350,300681,302409,304606,307350,310725
mov $7,$0
mov $9,$0
lpb $9,1
clr $0,7
mov $0,$7
sub $9,1
sub $0,$9
lpb $0,1
mov $2,$0
div $0,10
mod $2,10
add $3,1
add $4,1
add $4,$2
lpe
sub $4,$3
pow $4,3
mov $6,$4
mul $6,3
mov $1,$6
div $1,3
add $8,$1
lpe
mov $1,$8
|
org 0x7e00
jmp 0x0000:start
titulo db 'O LABIRINTO CEGO', 0
inst db ' Pressione qualquer tecla para iniciar', 0
comando db ' Movimento: W, S, A, D ', 0
inst1 db ' Leve o tempo que precisar para ', 0
inst2 db ' memorizar cada mapa! ', 0
inst3 db ' Quando estiver pronto, ', 0
inst4 db ' pressione qualquer tecla ', 0
inst5 db ' A tela ficara preta e voce deve ', 0
inst6 db ' alcancar o final de cada fase ', 0
inst7 db ' Boa sorte :) ', 0
pontuacao1 db ' Parabens, voce terminou o jogo com ', 0
score dw 0
pontuacao2 db ' mortes. ', 0
pontuacao3 db ' Deseja jogar novamente ? ', 0
pontuacao4 db ' Pressione qualquer tecla para ', 0
pontuacao5 db ' voltar ao menu inicial. ', 0
white equ 15
darkgreen equ 2
green equ 10
blue equ 1
black equ 0
brown equ 6
red equ 12
grey equ 7
dark_red equ 4
yellow equ 14
leftarrow equ $1E
rightarrow equ $20
uparrow equ $11
downarrow equ $1F
start:
call initVideo
ini:
mov ax, 0
mov [score], ax
call menu
call tutorial
call nv1
call nv2
call nv3
call nv4
call nv5
call nv6
call nv7
call nv8
call scoreboard
jmp ini
initVideo:
mov al, 13h
mov ah, 0
int 10h
ret
print_pixel:
mov ah, 0Ch
int 10h
ret
read_char:
mov ah, 0
int 16h
ret
print_char:
mov ah, 0eh
int 10h
ret
printString:
lodsb
mov cl, 0
cmp cl, al
je .done
mov ah, 0xe
int 0x10
jmp printString
.done:
ret
menu:
mov al, black
call LimpaArea
mov dl, 12
mov dh, 9
mov bh, 0
mov bl, yellow
mov ah, 02h
int 10h
mov si, titulo
call printString
mov dl, 0
mov dh, 22
mov ah, 02h
int 10h
mov si, inst
call printString
call read_char
ret
tutorial:
call DrawMaze1
mov al, red
mov cx, 10
mov dx, 10
call DrawPers
mov bl, yellow
mov dl, 8
mov dh, 8
mov ah, 02h
int 10h
mov si, comando
call printString
mov dl, 4
mov dh, 13
mov ah, 02h
int 10h
mov si, inst1
call printString
mov dl, 9
mov dh, 14
mov ah, 02h
int 10h
mov si, inst2
call printString
mov dl, 8
mov dh, 16
mov ah, 02h
int 10h
mov si, inst3
call printString
mov dl, 7
mov dh, 17
mov ah, 02h
int 10h
mov si, inst4
call printString
mov dl, 4
mov dh, 19
mov ah, 02h
int 10h
mov si, inst5
call printString
mov dl, 5
mov dh, 20
mov ah, 02h
int 10h
mov si, inst6
call printString
mov dl, 13
mov dh, 22
mov ah, 02h
int 10h
mov si, inst7
call printString
call read_char
ret
scoreboard:
mov al, black
call LimpaArea
mov bl, yellow
mov dl, 2
mov dh, 5
mov ah, 02h
int 10h
mov si, pontuacao1
call printString
mov dl, 18
mov dh, 7
mov ah, 02h
int 10h
mov ax, [score]
sub ax, 8
cmp ax, 10
jl umdig
mov dx, 0
mov bx, 10
div bx
add al, '0'
mov bl, yellow
call print_char
mov al, dl
umdig:
mov bl, yellow
add al, '0'
call print_char
mov dl, 15
mov dh, 9
mov ah, 02h
int 10h
mov si, pontuacao2
call printString
mov dl, 7
mov dh, 16
mov ah, 02h
int 10h
mov si, pontuacao3
call printString
mov dl, 4
mov dh, 20
mov ah, 02h
int 10h
mov si, pontuacao4
call printString
mov dl, 7
mov dh, 21
mov ah, 02h
int 10h
mov si, pontuacao5
call printString
call read_char
ret
nv1:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze1
mov al, red
mov cx, 10
mov dx, 10
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
call DrawPers
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, downarrow
jne nv1
call move_down
call read_char
cmp ah, downarrow
jne nv1
call move_down
call read_char
cmp ah, leftarrow
jne nv1
call move_left
call read_char
cmp ah, downarrow
jne nv1
call move_down
call read_char
cmp ah, downarrow
jne nv1
call move_down
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, uparrow
jne nv1
call move_up
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, downarrow
jne nv1
call move_down
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, uparrow
jne nv1
call move_up
call read_char
cmp ah, uparrow
jne nv1
call move_up
call read_char
cmp ah, leftarrow
jne nv1
call move_left
call read_char
cmp ah, uparrow
jne nv1
call move_up
call read_char
cmp ah, uparrow
jne nv1
call move_up
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, rightarrow
jne nv1
call move_right
call read_char
cmp ah, downarrow
jne nv1
call move_down
mov al, green
call LimpaArea
ret
nv2:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze2
mov al, red
mov cx, 290
mov dx, 50
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 290
mov dx, 50
call DrawPers
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, uparrow
jne nv2
call move_up
call read_char
cmp ah, uparrow
jne nv2
call move_up
call read_char
cmp ah, rightarrow
jne nv2
call move_right
call read_char
cmp ah, rightarrow
jne nv2
call move_right
call read_char
cmp ah, uparrow
jne nv2
call move_up
call read_char
cmp ah, uparrow
jne nv2
call move_up
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, leftarrow
jne nv2
call move_left
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, downarrow
jne nv2
call move_down
call read_char
cmp ah, rightarrow
jne nv2
call move_right
call read_char
cmp ah, downarrow
jne nv2
call move_down
mov al, green
call LimpaArea
ret
nv3:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze3
mov al, red
mov cx, 50
mov dx, 170
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 50
mov dx, 170
call DrawPers
call read_char
cmp ah, leftarrow
jne nv3
call move_left
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, downarrow
jne nv3
call move_down
call read_char
cmp ah, downarrow
jne nv3
call move_down
call read_char
cmp ah, leftarrow
jne nv3
call move_left
call read_char
cmp ah, leftarrow
jne nv3
call move_left
call read_char
cmp ah, downarrow
jne nv3
call move_down
call read_char
cmp ah, downarrow
jne nv3
call move_down
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, rightarrow
jne nv3
call move_right
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, uparrow
jne nv3
call move_up
call read_char
cmp ah, uparrow
jne nv3
call move_up
mov al, green
call LimpaArea
ret
nv4:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze4
mov al, red
mov dx, 10
mov cx, 290
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 290
mov dx, 10
call DrawPers
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, uparrow
jne nv4
call move_up
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, leftarrow
jne nv4
call move_left
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, uparrow
jne nv4
call move_up
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, downarrow
jne nv4
call move_down
call read_char
cmp ah, rightarrow
jne nv4
call move_right
call read_char
cmp ah, rightarrow
jne nv4
call move_right
mov al, green
call LimpaArea
ret
nv5:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze5
mov al, red
mov dx, 170
mov cx, 290
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 290
mov dx, 170
call DrawPers
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, rightarrow
jne nv5
call move_right
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, downarrow
jne nv5
call move_down
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, downarrow
jne nv5
call move_down
call read_char
cmp ah, downarrow
jne nv5
call move_down
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, downarrow
jne nv5
call move_down
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, leftarrow
jne nv5
call move_left
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, rightarrow
jne nv5
call move_right
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, uparrow
jne nv5
call move_up
call read_char
cmp ah, leftarrow
jne nv5
call move_left
mov al, green
call LimpaArea
ret
nv6:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze6
mov al, red
mov dx, 10
mov cx, 10
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 10
mov dx, 10
call DrawPers
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, uparrow
jne nv6
call move_up
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, uparrow
jne nv6
call move_up
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, rightarrow
jne nv6
call move_right
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, uparrow
jne nv6
call move_up
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, downarrow
jne nv6
call move_down
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, leftarrow
jne nv6
call move_left
call read_char
cmp ah, leftarrow
jne nv6
call move_left
mov al, green
call LimpaArea
ret
nv7:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze7
mov al, red
mov dx, 170
mov cx, 10
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 10
mov dx, 170
call DrawPers
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, downarrow
jne nv7
call move_down
call read_char
cmp ah, downarrow
jne nv7
call move_down
call read_char
cmp ah, downarrow
jne nv7
call move_down
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, downarrow
jne nv7
call move_down
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, leftarrow
jne nv7
call move_left
call read_char
cmp ah, leftarrow
jne nv7
call move_left
call read_char
cmp ah, leftarrow
jne nv7
call move_left
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, uparrow
jne nv7
call move_up
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
call read_char
cmp ah, rightarrow
jne nv7
call move_right
mov al, green
call LimpaArea
ret
nv8:
push ax
mov ax, [score]
inc ax
mov [score], ax
pop ax
call DrawMaze8
mov al, red
mov dx, 10
mov cx, 290
call DrawPers
call read_char
mov al, black
call LimpaArea
mov al, red
mov cx, 290
mov dx, 10
call DrawPers
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, uparrow
jne nv8
call move_up
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, uparrow
jne nv8
call move_up
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, leftarrow
jne nv8
call move_left
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, downarrow
jne nv8
call move_down
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, rightarrow
jne nv8
call move_right
call read_char
cmp ah, uparrow
jne nv8
call move_up
call read_char
cmp ah, uparrow
jne nv8
call move_up
mov al, green
call LimpaArea
ret
move_left:
call clean_move
sub cx, 40
call make_move
ret
move_right:
call clean_move
add cx, 40
call make_move
ret
move_up:
call clean_move
sub dx, 40
call make_move
ret
move_down:
call clean_move
add dx, 40
call make_move
ret
clean_move:
mov al, black
call DrawPers
ret
make_move:
mov al, red
call DrawPers
ret
DrawMaze1:
mov al, grey
call LimpaArea
mov al, brown
mov dx, 40
mov cx, 0
call DrawWall
mov dx, 0
mov cx, 80
call DrawWall
mov dx, 40
call DrawWall
mov dx, 80
call DrawWall
mov dx, 120
mov cx, 40
call DrawWall
mov cx, 120
mov dx, 0
call DrawWall
mov dx, 40
call DrawWall
mov dx, 80
call DrawWall
mov dx, 160
call DrawWall
mov cx, 160
mov dx, 0
call DrawWall
mov dx, 40
call DrawWall
mov dx, 80
call DrawWall
mov cx, 200
mov dx, 120
call DrawWall
mov dx, 40
mov cx, 240
call DrawWall
mov dx, 80
mov cx, 280
call DrawWall
mov dx, 120
call DrawWall
mov dx, 160
call DrawWall
mov cx, 280
mov dx, 40
mov al, green
call DrawWall
ret
DrawMaze2:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 0
mov dx, 0
call DrawWall
mov dx, 160
call DrawWall
mov cx, 40
mov dx, 0
call DrawWall
mov dx, 80
call DrawWall
mov cx, 80
call DrawWall
mov dx, 120
call DrawWall
mov dx, 160
call DrawWall
mov cx, 120
mov dx, 40
call DrawWall
mov cx, 160
call DrawWall
mov dx, 120
call DrawWall
mov cx, 200
call DrawWall
mov cx, 240
call DrawWall
mov dx, 80
call DrawWall
mov dx, 40
call DrawWall
mov dx, 0
call DrawWall
mov cx, 280
call DrawWall
mov cx, 40
mov dx, 160
mov al, green
call DrawWall
ret
DrawMaze3:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 0
mov dx, 0
call DrawWall
mov cx, 240
call DrawWall
mov dx, 40
call DrawWall
mov cx, 160
call DrawWall
mov cx, 120
call DrawWall
mov cx, 80
call DrawWall
mov dx, 80
call DrawWall
mov dx, 120
call DrawWall
mov dx, 80
mov cx, 240
call DrawWall
mov cx, 40
call DrawWall
mov dx, 120
call DrawWall
mov cx, 160
call DrawWall
mov cx, 200
call DrawWall
mov dx, 160
mov cx, 80
call DrawWall
mov cx, 280
call DrawWall
mov cx, 280
mov dx, 0
mov al, green
call DrawWall
ret
DrawMaze4:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 0
mov dx, 0
call DrawWall
mov cx, 160
call DrawWall
mov dx, 80
call DrawWall
mov cx, 40
call DrawWall
mov cx, 80
call DrawWall
mov cx, 120
call DrawWall
mov cx, 200
call DrawWall
mov cx, 240
call DrawWall
mov cx, 280
call DrawWall
mov dx, 40
call DrawWall
mov cx, 240
call DrawWall
mov dx, 120
call DrawWall
mov cx, 280
call DrawWall
mov cx, 80
call DrawWall
mov dx, 40
call DrawWall
mov dx, 160
mov cx, 0
call DrawWall
mov cx, 160
call DrawWall
mov cx, 280
mov al, green
call DrawWall
ret
DrawMaze5:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 80
mov dx, 0
call DrawWall
mov cx, 120
call DrawWall
mov cx, 280
call DrawWall
mov dx, 40
call DrawWall
mov cx, 200
call DrawWall
mov cx, 0
call DrawWall
mov cx, 80
call DrawWall
mov dx, 80
call DrawWall
mov cx, 160
call DrawWall
mov cx, 280
call DrawWall
mov dx, 120
call DrawWall
mov cx, 240
call DrawWall
mov cx, 40
call DrawWall
mov cx, 160
call DrawWall
mov dx, 160
call DrawWall
mov cx, 120
call DrawWall
mov cx, 0
mov dx, 0
mov al, green
call DrawWall
ret
DrawMaze6:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 40
mov dx, 0
call DrawWall
mov cx, 80
call DrawWall
mov cx, 280
call DrawWall
mov dx, 40
call DrawWall
mov cx, 200
call DrawWall
mov cx, 40
call DrawWall
mov cx, 160
call DrawWall
mov dx, 80
call DrawWall
mov cx, 120
call DrawWall
mov cx, 200
call DrawWall
mov dx, 120
mov cx, 0
call DrawWall
mov cx, 40
call DrawWall
mov cx, 80
call DrawWall
mov cx, 240
call DrawWall
mov dx, 160
mov cx, 160
call DrawWall
mov cx, 0
mov al, green
call DrawWall
ret
DrawMaze7:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 120
mov dx, 0
call DrawWall
mov dx, 40
call DrawWall
mov cx, 280
call DrawWall
mov cx, 240
call DrawWall
mov cx, 200
call DrawWall
mov cx, 40
call DrawWall
mov dx, 80
call DrawWall
mov dx, 120
call DrawWall
mov dx, 160
call DrawWall
mov cx, 80
call DrawWall
mov dx, 120
mov cx, 160
call DrawWall
mov cx, 200
call DrawWall
mov cx, 240
call DrawWall
mov dx, 80
mov cx, 120
call DrawWall
mov dx, 0
mov cx, 280
mov al, green
call DrawWall
ret
DrawMaze8:
mov al, grey
call LimpaArea
mov al, brown
mov cx, 120
mov dx, 0
call DrawWall
mov cx, 160
call DrawWall
mov dx, 40
call DrawWall
mov cx, 40
call DrawWall
mov cx, 240
call DrawWall
mov dx, 80
call DrawWall
mov cx, 80
call DrawWall
mov dx, 120
call DrawWall
mov cx, 120
call DrawWall
mov cx, 160
call DrawWall
mov cx, 200
call DrawWall
mov cx, 240
call DrawWall
mov cx, 0
call DrawWall
mov dx, 160
call DrawWall
mov dx, 40
mov cx, 280
call DrawWall
mov dx, 80
mov al, green
call DrawWall
ret
;funcao que desenha um bloco 40x40 a partir da posicao cx e dx
;dx = linha // cx = coluna // janela: 200x320
DrawWall:
mov bx, dx
add bx, 40
.forwall:
cmp dx, bx
je .endforwall
push bx
mov bx, cx
add bx, 40
.forwall2:
cmp cx, bx
je .endforwall2
call print_pixel
inc cx
jmp .forwall2
.endforwall2:
sub cx, 40
pop bx
inc dx
jmp .forwall
.endforwall:
sub dx, 40
ret
;Desenha um quadradinho 20x20
DrawPers:
mov bx, dx
add bx, 20
.forpers:
cmp dx, bx
je .endforpers
push bx
mov bx, cx
add bx, 20
.forpers2:
cmp cx, bx
je .endforpers2
call print_pixel
inc cx
jmp .forpers2
.endforpers2:
sub cx, 20
pop bx
inc dx
jmp .forpers
.endforpers:
sub dx, 20
ret
;Desenha em toda janela com a cor em al
LimpaArea:
push dx
push cx
mov dx, 0
.ForLA:
cmp dx, 200
je .endForLA
mov cx, 0
.forinLA:
cmp cx, 320
je .endForinLA
call print_pixel
inc cx
jmp .forinLA
.endForinLA:
inc dx
jmp .ForLA
.endForLA:
pop cx
pop dx
ret
done:
jmp $ |
; A027769: a(n) = (n+1)*binomial(n+1, 9).
; 9,100,605,2640,9295,28028,75075,183040,413270,875160,1755182,3359200,6172530,10943240,18795370,31380096,51074375,81238300,126544275,193393200,290435145,429214500,624962325,897561600,1272714300,1783342704,2471261100,3389158080,4602933940,6194442320,8264690148,10937555200,14364086165,18727456020,24248645785,31192942352,39877341075,50678951180,64044509815,80501118720,100668326066,125271685000,155157929850,191311920800,234875518150,287168558040,349712112750,424254230400,512798361075,617634689100,741374604399,886988559600,1057847573805,1257768658740,1491064458345,1762597408768,2077838742200,2442932675040,2864766138520,3351044428160,3910373167272,4552346999200,5287645443080,6128136368640,7086987566945,8178786916036,9419671663125,10827467368400,12421837079575,14224441331100,16259109587435,18552023776000,21131914582350,24030271207800,27281565318150,30923489941344,34997214101850,39547654010280,44623761658290,50278831701120,56570827543263,63562727576700,71322892555915,79925455129520,89450732584785,99985663898692,111624272227325,124468154004480,138626995860340,154219120611920,171372063618756,190223180840000,210920289972700,233622346095600,258500153288300,285737113742080,315530015926125,348089863421300,383642746083025,422430755245200
mov $1,$0
add $0,9
bin $0,$1
add $1,9
mul $0,$1
|
; A030123: Most likely total for a roll of n 6-sided dice, choosing the smallest if there is a choice.
; 0,1,7,10,14,17,21,24,28,31,35,38,42,45,49,52,56,59,63,66,70,73,77,80,84,87,91,94,98,101,105,108,112,115,119,122,126,129,133,136,140,143,147,150,154,157,161,164,168,171,175,178,182,185,189,192,196,199,203,206,210,213,217,220,224,227,231,234,238,241,245,248,252,255,259,262,266,269,273,276,280,283,287,290,294,297,301,304,308,311,315,318,322,325,329,332,336,339,343,346,350,353,357,360,364,367,371,374,378,381,385,388,392,395,399,402,406,409,413,416,420,423,427,430,434,437,441,444,448,451,455,458,462,465,469,472,476,479,483,486,490,493,497,500,504,507,511,514,518,521,525,528,532,535,539,542,546,549,553,556,560,563,567,570,574,577,581,584,588,591,595,598,602,605,609,612,616,619,623,626,630,633,637,640,644,647,651,654,658,661,665,668,672,675,679,682,686,689,693,696,700,703,707,710,714,717,721,724,728,731,735,738,742,745,749,752,756,759,763,766,770,773,777,780,784,787,791,794,798,801,805,808,812,815,819,822,826,829,833,836,840,843,847,850,854,857,861,864,868,871
mov $1,$0
mov $2,$0
lpb $2
mul $1,7
div $1,2
pow $2,$3
lpe
|
db 0 ; species ID placeholder
db 80, 92, 65, 68, 65, 80
; hp atk def spd sat sdf
db WATER, WATER ; type
db 60 ; catch rate
db 170 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/seaking/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_WATER_2, EGG_WATER_2 ; egg groups
; tm/hm learnset
tmhm CURSE, TOXIC, HIDDEN_POWER, SNORE, BLIZZARD, HYPER_BEAM, ICY_WIND, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, REST, ATTRACT, SURF, WATERFALL, ICE_BEAM
; end
|
; A007088: The binary numbers (or binary words, or binary vectors): numbers written in base 2.
; 0,1,10,11,100,101,110,111,1000,1001,1010,1011,1100,1101,1110,1111,10000,10001,10010,10011,10100,10101,10110,10111,11000,11001,11010,11011,11100,11101,11110,11111,100000,100001,100010,100011,100100,100101,100110,100111,101000,101001,101010,101011,101100,101101,101110,101111,110000,110001,110010,110011,110100,110101,110110,110111,111000,111001,111010,111011,111100,111101,111110,111111,1000000,1000001,1000010,1000011,1000100,1000101,1000110,1000111,1001000,1001001,1001010,1001011,1001100,1001101,1001110,1001111,1010000,1010001,1010010,1010011,1010100,1010101,1010110,1010111,1011000,1011001,1011010,1011011,1011100,1011101,1011110,1011111,1100000,1100001,1100010,1100011,1100100,1100101,1100110,1100111,1101000,1101001,1101010,1101011,1101100,1101101,1101110,1101111,1110000,1110001,1110010,1110011,1110100,1110101,1110110,1110111,1111000,1111001,1111010,1111011,1111100,1111101,1111110,1111111,10000000,10000001,10000010,10000011,10000100,10000101,10000110,10000111,10001000,10001001,10001010,10001011,10001100,10001101,10001110,10001111,10010000,10010001,10010010,10010011,10010100,10010101,10010110,10010111,10011000,10011001,10011010,10011011,10011100,10011101,10011110,10011111,10100000,10100001,10100010,10100011,10100100,10100101,10100110,10100111,10101000,10101001,10101010,10101011,10101100,10101101,10101110,10101111,10110000,10110001,10110010,10110011,10110100,10110101,10110110,10110111,10111000,10111001,10111010,10111011,10111100,10111101,10111110,10111111,11000000,11000001,11000010,11000011,11000100,11000101,11000110,11000111,11001000,11001001,11001010,11001011,11001100,11001101,11001110,11001111,11010000,11010001,11010010,11010011,11010100,11010101,11010110,11010111,11011000,11011001,11011010,11011011,11011100,11011101,11011110,11011111,11100000,11100001,11100010,11100011,11100100,11100101,11100110,11100111,11101000,11101001,11101010,11101011,11101100,11101101,11101110,11101111,11110000,11110001,11110010,11110011,11110100,11110101,11110110,11110111,11111000,11111001
cal $0,99820 ; Even nonnegative integers in base 2 (bisection of A007088).
mov $1,$0
div $1,10
|
; compile with nasm -felf64 foo.asm; ld foo.o -o foo.out
bits 64
section .start
global _start
_start:
call func1 ; should see the address of `pop rax`
; because call implicitly pushes the
; address of pc onto the stack
; exit
mov rax, 60
syscall
func1:
push rbp ; this should be 0 initially,
mov rbp, rsp ; because there is no stack
; frame yet
call func2
mov rsp, rbp
pop rbp
ret
func2:
push rbp
mov rbp, rsp
; should be able to see on the stack
; at this point the return address,
; or the address of the above mov rax, 60
; followed by the saved ebp
mov rsp, rbp
pop rbp
ret
|
; A138849: a(n) = AlexanderPolynomial[n] defined as Det[Transpose[S]-n S] where S is Kronecker Product of two 2 X 2 Seifert matrices {{-1, 1}, {0, -1}} [X] {{-1, 1}, {0, -1}} = {{1, -1, -1, 1}, {0, 1, 0, -1}, {0, 0, 1, -1}, {0, 0, 0, 1}}.
; 1,0,7,52,189,496,1075,2052,3577,5824,8991,13300,18997,26352,35659,47236,61425,78592,99127,123444,151981,185200,223587,267652,317929,374976,439375,511732,592677,682864,782971,893700,1015777,1149952,1296999,1457716,1632925
mov $1,$0
pow $0,3
sub $1,1
mul $0,$1
sub $0,$1
|
; A192908: Constant term in the reduction by (x^2 -> x + 1) of the polynomial p(n,x) defined below at Comments.
; 1,1,3,7,17,43,111,289,755,1975,5169,13531,35423,92737,242787,635623,1664081,4356619,11405775,29860705,78176339,204668311,535828593,1402817467,3672623807,9615053953,25172538051,65902560199,172535142545,451702867435,1182573459759,3096017511841,8105479075763,21220419715447,55555780070577,145446920496283,380784981418271,996908023758529,2609939089857315,6832909245813415
sub $0,1
mov $2,2
lpb $0
sub $0,1
add $1,$2
add $2,$1
lpe
add $1,1
|
.data
message: .asciiz "Fim da Execução"
space: .asciiz ", "
.text
main:
addi $t0,$zero,0
loop:
bgt $t0,9,exit
addi $t0,$t0,1
li $v0, 5 # chama função para ler
syscall
la $t7, ($v0) # carrega o inteiro lido em $t7
add $t1,$t1,$t7
j loop
exit:
jal intSoma
li $v0, 4
la $a0, message
syscall
#fim da execução
li $v0, 10
syscall
intSoma:
li $v0, 1
add $a0,$t1,$zero
syscall
li $v0, 4
la $a0,space
syscall
jr $ra
|
; A033762: Product t2(q^d); d | 3, where t2 = theta2(q) / (2 * q^(1/4)).
; Submitted by Jamie Morken(s3)
; 1,1,0,2,1,0,2,0,0,2,2,0,1,1,0,2,0,0,2,2,0,2,0,0,3,0,0,0,2,0,2,2,0,2,0,0,2,1,0,2,1,0,0,0,0,4,2,0,2,0,0,2,0,0,2,2,0,0,2,0,1,0,0,2,2,0,4,0,0,2,0,0,0,3,0,2,0,0,2,0,0,2,0,0,3,2,0,2,0,0,2,2,0,0,2,0,2,0,0,2
mul $0,2
add $0,1
lpb $0
dif $0,3
lpe
seq $0,217219 ; Theta series of planar hexagonal lattice with respect to deep hole.
div $0,6
|
[bits 16]
[org 0x7c00]
start:
xor ax, ax
mov ds, ax
mov es, ax
mov bx, 0x8000
mov dx, [VGA_MEM]
mov es, dx
call clear_screen
mov si,PRINT_STRING
call print_str
ret
print_str:
._next_char:
lodsb
cmp al, 0
je ._done
mov di, word[VGA_INDEX]
mov [es:di], al
add word[VGA_INDEX], 2
jmp ._next_char
._done:
ret
clear_screen:
mov di, 0
._clr_loop:
cmp di, word[MAX_VGA_INDEX]
je ._done
mov al, 0
mov [es:di], al
add di, 2
jmp ._clr_loop
._done:
ret
VGA_MEM dw 0xB800
MAX_VGA_INDEX dw 0xF9E
VGA_INDEX dw 0x00
PRINT_STRING db "Hello World!", 0
times (510-($-$$)) db 0x00
dw 0xAA55
|
/****************************************************************************************
* Copyright (c) 2017 Korea Electronics Technology Institute. *
* All rights reserved. This program and the accompanying materials *
* are made available under the terms of *
* - Eclipse Public License v1.0(http://www.eclipse.org/legal/epl-v10.html), *
* - BSD-3 Clause Licence(http://www.iotocean.org/license/), *
* - MIT License (https://github.com/open-source-parsers/jsoncpp/blob/master/LICENSE), *
* - zlib License (https://github.com/leethomason/tinyxml2#license). *
* *
* Contributors: *
* JaeYoung Hwang - forest62590@gmail.com *
* Nak-Myoung Sung - nmsung@keti.re.kr *
* Updated: 2018-03-25 *
****************************************************************************************/
#include <string>
#include "json.h"
#include "json-forwards.h"
#include "External_function.hh"
#include "OneM2M_DualFaceMapping.hh"
using namespace tinyxml2;
using namespace Json;
using namespace std;
namespace OneM2M__DualFaceMapping {
CHARSTRING acp_JSON_Enc_Parser(const CHARSTRING& p__source){
Value elemName;
Value elemObj(objectValue);
Value subElemObj(objectValue);
Value resourceRoot(objectValue);
Value jsonRoot(objectValue);
Reader jsonReader;
std::string name_short;
const char* p_body = (const char*)p__source;
CHARSTRING encoded_message = "";
// 1. Make the JSOn object from the string data
bool parsingSuccessful = jsonReader.parse(p_body, jsonRoot, false);
if ( !parsingSuccessful ) {
TTCN_Logger::log(TTCN_DEBUG, "JsonCPP API parsing error!");
return "JsonCPP API parsing error!";
}
// 2. Save the root name "accessControlPolicy" -> m2m:acp (changed)"
CHARSTRING rootName = "m2m:acp";
// 3. extract the accessControlPolicy element
jsonRoot = jsonRoot.get("accessControlPolicy", "");
for (Value::iterator iter = jsonRoot.begin(); iter != jsonRoot.end(); ++iter) {
elemName = iter.key();
elemObj = jsonRoot.get(elemName.asString(), "");
name_short = getShortName(elemName.asString());
if(name_short == ""){
name_short = elemName.asString();
}
if(elemObj.isObject()) { // object
subElemObj = acp_JSON_Enc_Parser_Deep(elemObj, subElemObj, elemName);
} else if (elemObj.isArray()) { // array
Value elemArrayObj(arrayValue);
for(unsigned int index = 0; index < elemObj.size(); index++){
Value tempObj = elemObj[index];
if(tempObj.isString()){
elemArrayObj.append(tempObj.asString());
}else if(tempObj.isBool()){
elemArrayObj.append(tempObj.asBool());
}else if(tempObj.isDouble()){
elemArrayObj.append(tempObj.asDouble());
}else if(tempObj.isInt64()){
elemArrayObj.append(tempObj.asInt64());
}
}
subElemObj[name_short.c_str()] = elemArrayObj;
} else if (elemObj.isString()) { // string
subElemObj[name_short.c_str()] = elemObj;
}
}
resourceRoot[rootName] = subElemObj;
TTCN_Logger::log(TTCN_DEBUG, "Pretty print of DECODED JSON message:\n%s", resourceRoot.toStyledString().c_str());
StyledWriter writer;
std::string json_str = writer.write(resourceRoot);
CHARSTRING temp_cs(json_str.c_str());
encoded_message = temp_cs;
return encoded_message;
}
Json::Value acp_JSON_Enc_Parser_Deep (Json::Value objectSource, Json::Value objectRoot, Json::Value elemName) {
// Constant variables for the resource and attributes name
static const std::string ACCESS_CONTROL_OPERATION("acop"), ACCESS_CONTROL_RULE("acr");
std::string name_short;
std::string rootName;
Value subElemObj(objectValue);
Value containerForSubElem(objectValue);
for (Value::iterator iter = objectSource.begin(); iter != objectSource.end(); ++iter) {
Value elemName;
Value elemObj(objectValue);
// 1. Select the attribute with KEY
elemName = iter.key();
elemObj = objectSource.get(elemName.asString(), "");
// 2. Change the oneM2M long name to short name for SUT
name_short = getShortName(elemName.asString());
if(name_short == ""){
name_short = elemName.asString();
}
// CHARSTRING tmp_for_name_checking(elemName.asCString());
// TTCN_Logger::log(TTCN_DEBUG, "**************root*********************");
// TTCN_Logger::log(TTCN_DEBUG, (const char*)tmp_for_name_checking);
// TTCN_Logger::log(TTCN_DEBUG, "**************root*********************\n");
if (elemObj.isArray()) { // array
Value elemArrayObj(arrayValue);
if(elemObj.size() != 0) {
for(unsigned int index = 0; index < elemObj.size(); index++){
Value tempObj = elemObj[index];
if (tempObj.isObject()) {
Value subElemObj(objectValue);
subElemObj = acp_JSON_Enc_Parser_Deep(tempObj, subElemObj, elemName);
elemArrayObj.append(subElemObj);
} else if(tempObj.isString()){
elemArrayObj.append(tempObj);
} else if (tempObj.isBool()){
elemArrayObj.append(tempObj.asBool());
} else if (tempObj.isDouble()){
int convertedIntValue = float2int(tempObj.asDouble());
std::string tmp_str((const char*)(int2str(convertedIntValue)));
std::string attr_val = getLongName(tmp_str);
elemArrayObj.append(attr_val);
} else if(tempObj.isInt64()){
std::string tmp_str((const char*)(int2str(tempObj.asInt())));
std::string attr_val = getLongName(tmp_str);
elemArrayObj.append(tempObj.asInt());
} else {
TTCN_Logger::log(TTCN_DEBUG, "Unexpected flow");
}
}
containerForSubElem[name_short.c_str()] = elemArrayObj;
}
} else if(elemObj.isString()) { // string
if(ACCESS_CONTROL_OPERATION == name_short){ // add all enumerated type here
std::string attr_val = getShortName(elemObj.asString());
int tmp_int = atoi(attr_val.c_str());
containerForSubElem[name_short.c_str()] = tmp_int;
} else {
containerForSubElem[name_short.c_str()] = elemObj;
}
}
}
// 3. RootName: Change the oneM2M short name to long name for the TTCN-3
rootName = getShortName(elemName.asString());
if(rootName == ""){
rootName = elemName.asString();
}
if(rootName != ACCESS_CONTROL_RULE) {
objectRoot[rootName.c_str()] = containerForSubElem;
return objectRoot;
} else {
return containerForSubElem;
}
}
}
|
; A114182: F(4n) - 2n - 1 where F(n) = Fibonacci numbers. Also, the floor of the log base phi of sequence A090162 (phi = (1+Sqrt(5))/2).
; 0,16,137,978,6754,46355,317796,2178292,14930333,102334134,701408710,4807526951,32951280072,225851433688,1548008755889,10610209857690,72723460248106,498454011879227,3416454622906668,23416728348467644
seq $0,99922 ; a(n) = F(4n) - 2n, where F(n) = Fibonacci numbers A000045.
sub $0,1
|
%ifndef proj_e_stdio_asm
%define proj_e_stdio_asm
bits 16
%include "std/macros.asm"
nl db 13, 10, 0
; Routine for outputting a string on the screen
; INPUT : SI (containing address of the string)
; OUTPUT : none
proj_e_print:
mov ah, 0x0e ; specify int 0x10 (teletype output)
.printchar:
lodsb ; load byte from si into al, increment si
cmp al, 0 ; is it the end of the string ?
je .done ; yes => quit ; no => continue
int 0x10 ; print the character
jmp .printchar
.done:
ret
; Routine to reboot the machine
; INPUT : none
; OUTPUT : none
proj_e_reboot:
db 0x0ea ; sending us to the end of the memory, to reboot
dw 0x0000
dw 0xffff
; Routine to wait for any key press
; INPUT : none
; OUTPUT : none
proj_e_waitkeypress:
mov ah, 0
int 0x16 ; BIOS keyboard service
ret
; Routine to print an hexadecimal word to screen
; INPUT : AX (number)
; OUTPUT : none
proj_e_print_hex:
push ax
call proj_e_print_hex_word
; cleanup stack after call
add sp, 2
ret
; Routine to print an hexadecimal word to screen
; INPUT : number on the stack
; OUTPUT : none
proj_e_print_hex_word:
push bp
mov bp, sp ; BP=SP, on 8086 can't use sp in memory operand
push dx ; Save all registers we clobber
push cx
push bx
push ax
mov cx, 0x0404 ; CH = number of nibbles to process = 4 (4*4=16 bits)
; CL = Number of bits to rotate each iteration = 4 (a nibble)
mov dx, [bp+4] ; DX = word parameter on stack at [bp+4] to print
mov bx, [bp+6] ; BX = page / foreground attr is at [bp+6]
.loop:
rol dx, cl ; Roll 4 bits left. Lower nibble is value to print
mov ax, 0x0e0f ; AH=0E (BIOS tty print),AL=mask to get lower nibble
and al, dl ; AL=copy of lower nibble
add al, 0x90 ; Work as if we are packed BCD
daa ; Decimal adjust after add.
; If nibble in AL was between 0 and 9, then CF=0 and
; AL=0x90 to 0x99
; If nibble in AL was between A and F, then CF=1 and
; AL=0x00 to 0x05
adc al, 0x40 ; AL=0xD0 to 0xD9
; or AL=0x41 to 0x46
daa ; AL=0x30 to 0x39 (ASCII '0' to '9')
; or AL=0x41 to 0x46 (ASCII 'A' to 'F')
int 0x10 ; Print ASCII character in AL
dec ch
jnz .loop ; Go back if more nibbles to process
pop ax ; Restore registers
pop bx
pop cx
pop dx
pop bp
ret
%endif
|
// -----------------------------------------------------------------------------
// native.c
// -----------------------------------------------------------------------------
#include "low.h"
#include "duktape.h"
// -----------------------------------------------------------------------------
// native_method_simple_add - add method
// -----------------------------------------------------------------------------
int native_method_simple_add(duk_context *ctx)
{
double a = duk_get_number_default(ctx, 0, 0);
double b = duk_get_number_default(ctx, 1, 0);
duk_push_number(ctx, a + b);
return 1;
}
// -----------------------------------------------------------------------------
// module_main - on stack: [module exports]
// -----------------------------------------------------------------------------
bool module_load(duk_context *ctx, const char *module_path)
{
duk_function_list_entry methods[] = {{"simple_add", native_method_simple_add, 2},
{NULL, NULL, 0}};
duk_put_function_list(ctx, 1, methods);
return true;
}
|
/**
* @file
* Declares the string type.
*/
#pragma once
#include "../values/forward.hpp"
#include <limits>
#include <ostream>
namespace puppet { namespace runtime { namespace types {
// Forward declaration of recursion_guard
struct recursion_guard;
// Forward declaration of integer
struct integer;
/**
* Represents the Puppet String type.
*/
struct string
{
/**
* Constructs a string type.
* @param from The "from" type parameter.
* @param to The "to" type parameter.
*/
explicit string(int64_t from = 0, int64_t to = std::numeric_limits<int64_t>::max());
/**
* Constructs a string from an integer range.
* @param range The integer type describing the string's range.
*/
explicit string(integer const& range);
/**
* Gets the "from" type parameter.
* @return Returns the "from" type parameter.
*/
int64_t from() const;
/**
* Gets the "to" type parameter.
* @return Returns the "to" type parameter.
*/
int64_t to() const;
/**
* Gets the name of the type.
* @return Returns the name of the type (i.e. String).
*/
static char const* name();
/**
* Creates a generalized version of the type.
* @return Returns the generalized type.
*/
values::type generalize() const;
/**
* Determines if the given value is an instance of this type.
* @param value The value to determine if it is an instance of this type.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given value is an instance of this type or false if not.
*/
bool is_instance(values::value const& value, recursion_guard& guard) const;
/**
* Determines if the given type is assignable to this type.
* @param other The other type to check for assignability.
* @param guard The recursion guard to use for aliases.
* @return Returns true if the given type is assignable to this type or false if the given type is not assignable to this type.
*/
bool is_assignable(values::type const& other, recursion_guard& guard) const;
/**
* Writes a representation of the type to the given stream.
* @param stream The stream to write to.
* @param expand True to specify that type aliases should be expanded or false if not.
*/
void write(std::ostream& stream, bool expand = true) const;
/**
* Stores a default shared instance used internally by other Puppet types.
*/
static string const instance;
private:
int64_t _from;
int64_t _to;
};
/**
* Stream insertion operator for string type.
* @param os The output stream to write the type to.
* @param type The type to write.
* @return Returns the given output stream.
*/
std::ostream& operator<<(std::ostream& os, string const& type);
/**
* Equality operator for string.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Returns true if the two types are equal or false if not.
*/
bool operator==(string const& left, string const& right);
/**
* Inequality operator for string.
* @param left The left type to compare.
* @param right The right type to compare.
* @return Returns true if the two types are not equal or false if they are equal.
*/
bool operator!=(string const& left, string const& right);
/**
* Hashes the string type.
* @param type The string type to hash.
* @return Returns the hash value for the type.
*/
size_t hash_value(string const& type);
}}} // namespace puppet::runtime::types
|
;THIS IS A PART OF FROST 4k INTRO
S4L
DB #F7,#02,#00,#8F,#77,#03,#00,#8F
DB #77,#04,#00,#8F,#77,#05,#00,#8F
DB #77,#06,#00,#8E,#77,#07,#00,#8D
DB #77,#08,#00,#8C,#77,#09,#00,#8B
DB #77,#0A,#00,#8A,#F7,#0A,#00,#88
DB #77,#0B,#00,#85,#F7,#0B,#00,#81
DB #77,#00,#00,#80,#FF
S5L
DB #09,#00,#00,#0D,#DF,#01,#00,#4C
DB #DF,#01,#00,#4C,#DF,#01,#00,#4B
DB #DF,#01,#00,#4B,#DF,#01,#00,#4A
DB #DF,#01,#00,#49,#DF,#01,#00,#48
DB #DF,#01,#00,#46,#DF,#01,#00,#45
DB #DF,#01,#00,#43,#DF,#01,#00,#41
DB #DF,#01,#00,#00,#FF
S6L
DB #77,#01,#06,#0F,#BF,#01,#04,#0E
DB #F1,#01,#05,#0E,#23,#02,#03,#0D
DB #87,#02,#04,#0C,#B9,#02,#07,#0B
DB #EB,#02,#03,#4A,#77,#00,#0F,#48
DB #77,#00,#0B,#47,#77,#00,#01,#45
DB #77,#00,#06,#44,#77,#00,#08,#43
DB #77,#00,#13,#42,#77,#00,#00,#00
DB #FF
SBL
DB #09,#00,#00,#0C,#DF,#01,#00,#00
DB #FF
TXTU
DB #00,#88,#88,#AA,#EE,#FF,#FF,#FF
DB #00,#00,#22,#44,#55,#55,#DD,#FF
SINN
DB #00,#03,#06,#09,#0C,#0F,#12,#15
DB #18,#1B,#1F,#22,#25,#27,#2A,#2D
DB #30,#33,#36,#39,#3C,#3F,#41,#44
DB #46,#49,#4B,#4E,#50,#53,#55,#57
DB #5A,#5C,#5F,#60,#62,#64,#66,#68
DB #6A,#6B,#6D,#6E,#70,#71,#73,#74
DB #75,#76,#78,#79,#7A,#7A,#7B,#7C
DB #7D,#7D,#7E,#7E,#7E,#7F,#7F,#7F
PATTERNS
DUP 7
DB #10,#20
EDUP
DB #10,#33,#14,#24,#14,#24,#14,#24,#14,#33
DB #14,#24,#14,#24,#14,#24,#33,#33
DB #14,#11,#33,#23,#13,#14,#33,#42,#14,#11,#33
DB #23,#13,#14,#31,#43,#14,#11
DB #33,#23,#13,#14,#33,#42,#14,#11,#33,#23,#13,#14
DB #31,#33
DB #10,#40,#20,#10,#30,#20,#30,#20,#10,#10
DB #40,#10,#30,#20,#30,#30,#10,#40,#20,#10
DB #30,#20,#30,#20,#10,#10,#40,#10,#30,#20,#30,#30
DB #10,#40,#20,#10,#30,#20,#30,#20,#10,#10,#40
DB #10,#30,#20,#30,#30,#10,#40,#20,#10,#30,#20
DB #30,#20,#10,#10,#40,#10,#30,#20,#33,#33
EPAT EQU $-PATTERNS
|
;*!
;* \copy
;* Copyright (c) 2009-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.
;*
;*************************************************************************/
%include "asm_inc.asm"
;***********************************************************************
; Local Data (Read Only)
;***********************************************************************
SECTION .rodata align=16
ALIGN 16
mv_x_inc_x4 dw 0x10, 0x10, 0x10, 0x10
mv_y_inc_x4 dw 0x04, 0x04, 0x04, 0x04
mx_x_offset_x4 dw 0x00, 0x04, 0x08, 0x0C
SECTION .text
%ifdef X86_32
;**********************************************************************************************************************
;void SumOf8x8BlockOfFrame_sse2(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;*********************************************************************************************************************
WELS_EXTERN SumOf8x8BlockOfFrame_sse2
%define pushsize 16
%define localsize 4
%define ref esp + pushsize + localsize + 4
%define sum_ref esp + pushsize + localsize + 20
%define times_of_sum esp + pushsize + localsize + 24
%define width esp + pushsize + localsize + 8
%define height esp + pushsize + localsize + 12
%define linesize esp + pushsize + localsize + 16
%define tmp_width esp + 0
push ebx
push ebp
push esi
push edi
sub esp, localsize
pxor xmm0, xmm0
mov esi, [ref]
mov edi, [sum_ref]
mov edx, [times_of_sum]
mov ebx, [linesize]
mov eax, [width]
lea ecx, [ebx+ebx*2] ; 3*linesize
mov [tmp_width], eax
lea ebp, [esi+ebx*4]
FIRST_ROW:
movq xmm1, [esi]
movq xmm2, [esi+ebx]
movq xmm3, [esi+ebx*2]
movq xmm4, [esi+ecx]
shufps xmm1, xmm2, 01000100b
shufps xmm3, xmm4, 01000100b
psadbw xmm1, xmm0
psadbw xmm3, xmm0
paddd xmm1, xmm3
movq xmm2, [ebp]
movq xmm3, [ebp+ebx]
movq xmm4, [ebp+ebx*2]
movq xmm5, [ebp+ecx]
shufps xmm2, xmm3, 01000100b
shufps xmm4, xmm5, 01000100b
psadbw xmm2, xmm0
psadbw xmm4, xmm0
paddd xmm2, xmm4
paddd xmm1, xmm2
pshufd xmm2, xmm1, 00001110b
paddd xmm1, xmm2
movd eax, xmm1
mov [edi], ax
inc dword [edx+eax*4]
inc esi
inc ebp
add edi, 2
dec dword [tmp_width]
jg FIRST_ROW
mov esi, [ref]
mov edi, [sum_ref]
mov ebp, [width]
dec dword [height]
HEIGHT_LOOP:
mov [tmp_width], ebp
WIDTH_LOOP:
movq xmm1, [esi+ebx*8]
movq xmm2, [esi]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psubd xmm1, xmm2
movd eax, xmm1
mov cx, [edi]
add eax, ecx
mov [edi+ebp*2], ax
inc dword [edx+eax*4]
inc esi
add edi, 2
dec dword [tmp_width]
jg WIDTH_LOOP
add esi, ebx
sub esi, ebp
dec dword [height]
jg HEIGHT_LOOP
add esp, localsize
pop edi
pop esi
pop ebp
pop ebx
%undef pushsize
%undef localsize
%undef ref
%undef sum_ref
%undef times_of_sum
%undef width
%undef height
%undef linesize
%undef tmp_width
ret
%macro COUNT_SUM 3
%define xmm_reg %1
%define tmp_reg %2
movd tmp_reg, xmm_reg
inc dword [edx+tmp_reg*4]
%if %3 == 1
psrldq xmm_reg, 4
%endif
%endmacro
;-----------------------------------------------------------------------------
; requires: width % 8 == 0 && height > 1
;-----------------------------------------------------------------------------
;void SumOf8x8BlockOfFrame_sse4(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;-----------------------------------------------------------------------------
; read extra (16 - (width % 8) ) mod 16 bytes of every line
; write extra (16 - (width % 8)*2 ) mod 16 bytes in the end of sum_ref
WELS_EXTERN SumOf8x8BlockOfFrame_sse4
%define pushsize 16
%define localsize 4
%define ref esp + pushsize + localsize + 4
%define sum_ref esp + pushsize + localsize + 20
%define times_of_sum esp + pushsize + localsize + 24
%define width esp + pushsize + localsize + 8
%define height esp + pushsize + localsize + 12
%define linesize esp + pushsize + localsize + 16
%define tmp_width esp + 0
push ebx
push ebp
push esi
push edi
sub esp, localsize
pxor xmm0, xmm0
mov esi, [ref]
mov edi, [sum_ref]
mov edx, [times_of_sum]
mov ebx, [linesize]
mov eax, [width]
lea ecx, [ebx+ebx*2] ; 3*linesize
mov [tmp_width], eax
lea ebp, [esi+ebx*4]
FIRST_ROW_SSE4:
movdqu xmm1, [esi]
movdqu xmm3, [esi+ebx]
movdqu xmm5, [esi+ebx*2]
movdqu xmm7, [esi+ecx]
movdqa xmm2, xmm1
mpsadbw xmm1, xmm0, 000b
mpsadbw xmm2, xmm0, 100b
paddw xmm1, xmm2 ; 8 sums of line1
movdqa xmm4, xmm3
mpsadbw xmm3, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm3, xmm4 ; 8 sums of line2
movdqa xmm2, xmm5
mpsadbw xmm5, xmm0, 000b
mpsadbw xmm2, xmm0, 100b
paddw xmm5, xmm2 ; 8 sums of line3
movdqa xmm4, xmm7
mpsadbw xmm7, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm7, xmm4 ; 8 sums of line4
paddw xmm1, xmm3
paddw xmm5, xmm7
paddw xmm1, xmm5 ; sum the upper 4 lines first
movdqu xmm2, [ebp]
movdqu xmm3, [ebp+ebx]
movdqu xmm4, [ebp+ebx*2]
movdqu xmm5, [ebp+ecx]
movdqa xmm6, xmm2
mpsadbw xmm2, xmm0, 000b
mpsadbw xmm6, xmm0, 100b
paddw xmm2, xmm6
movdqa xmm7, xmm3
mpsadbw xmm3, xmm0, 000b
mpsadbw xmm7, xmm0, 100b
paddw xmm3, xmm7
movdqa xmm6, xmm4
mpsadbw xmm4, xmm0, 000b
mpsadbw xmm6, xmm0, 100b
paddw xmm4, xmm6
movdqa xmm7, xmm5
mpsadbw xmm5, xmm0, 000b
mpsadbw xmm7, xmm0, 100b
paddw xmm5, xmm7
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm1, xmm2
paddw xmm1, xmm4 ; sum of lines 1- 8
movdqu [edi], xmm1
movdqa xmm2, xmm1
punpcklwd xmm1, xmm0
punpckhwd xmm2, xmm0
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 0
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 0
lea esi, [esi+8]
lea ebp, [ebp+8]
lea edi, [edi+16] ; element size is 2
sub dword [tmp_width], 8
jg near FIRST_ROW_SSE4
mov esi, [ref]
mov edi, [sum_ref]
mov ebp, [width]
dec dword [height]
HEIGHT_LOOP_SSE4:
mov ecx, ebp
WIDTH_LOOP_SSE4:
movdqu xmm1, [esi+ebx*8]
movdqu xmm2, [esi]
movdqu xmm7, [edi]
movdqa xmm3, xmm1
mpsadbw xmm1, xmm0, 000b
mpsadbw xmm3, xmm0, 100b
paddw xmm1, xmm3
movdqa xmm4, xmm2
mpsadbw xmm2, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm2, xmm4
paddw xmm7, xmm1
psubw xmm7, xmm2
movdqu [edi+ebp*2], xmm7
movdqa xmm6, xmm7
punpcklwd xmm7, xmm0
punpckhwd xmm6, xmm0
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 0
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 0
lea esi, [esi+8]
lea edi, [edi+16]
sub ecx, 8
jg near WIDTH_LOOP_SSE4
lea esi, [esi+ebx]
sub esi, ebp
dec dword [height]
jg near HEIGHT_LOOP_SSE4
add esp, localsize
pop edi
pop esi
pop ebp
pop ebx
%undef pushsize
%undef localsize
%undef ref
%undef sum_ref
%undef times_of_sum
%undef width
%undef height
%undef linesize
%undef tmp_width
ret
;****************************************************************************************************************************************************
;void SumOf16x16BlockOfFrame_sse2(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;****************************************************************************************************************************************************
WELS_EXTERN SumOf16x16BlockOfFrame_sse2
%define pushsize 16
%define localsize 4
%define ref esp + pushsize + localsize + 4
%define sum_ref esp + pushsize + localsize + 20
%define times_of_sum esp + pushsize + localsize + 24
%define width esp + pushsize + localsize + 8
%define height esp + pushsize + localsize + 12
%define linesize esp + pushsize + localsize + 16
%define tmp_width esp
push ebx
push ebp
push esi
push edi
sub esp, localsize
pxor xmm0, xmm0
mov esi, [ref]
mov edi, [sum_ref]
mov edx, [times_of_sum]
mov ebx, [linesize]
mov eax, [width]
lea ecx, [ebx+ebx*2]
mov [tmp_width], eax
FIRST_ROW_X16H:
movdqu xmm1, [esi]
movdqu xmm2, [esi+ebx]
movdqu xmm3, [esi+ebx*2]
movdqu xmm4, [esi+ecx]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
lea ebp, [esi+ebx*4]
movdqu xmm2, [ebp]
movdqu xmm3, [ebp+ebx]
movdqu xmm4, [ebp+ebx*2]
movdqu xmm5, [ebp+ecx]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea ebp, [ebp+ebx*4]
movdqu xmm2, [ebp]
movdqu xmm3, [ebp+ebx]
movdqu xmm4, [ebp+ebx*2]
movdqu xmm5, [ebp+ecx]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea ebp, [ebp+ebx*4]
movdqu xmm2, [ebp]
movdqu xmm3, [ebp+ebx]
movdqu xmm4, [ebp+ebx*2]
movdqu xmm5, [ebp+ecx]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd eax, xmm1
mov [edi], ax
inc dword [edx+eax*4]
inc esi
lea edi, [edi+2]
dec dword [tmp_width]
jg near FIRST_ROW_X16H
mov esi, [ref]
mov edi, [sum_ref]
mov ebp, [width]
dec dword [height]
mov ecx, ebx
sal ecx, 4 ; succeeded 16th line
HEIGHT_LOOP_X16:
mov [tmp_width], ebp
WIDTH_LOOP_X16:
movdqu xmm1, [esi+ecx]
movdqu xmm2, [esi]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psubw xmm1, xmm2
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd eax, xmm1
add ax, word [edi]
mov [edi+ebp*2], ax
inc dword [edx+eax*4]
inc esi
add edi, 2
dec dword [tmp_width]
jg near WIDTH_LOOP_X16
add esi, ebx
sub esi, ebp
dec dword [height]
jg near HEIGHT_LOOP_X16
add esp, localsize
pop edi
pop esi
pop ebp
pop ebx
%undef pushsize
%undef localsize
%undef ref
%undef sum_ref
%undef times_of_sum
%undef width
%undef height
%undef linesize
%undef tmp_width
ret
; requires: width % 16 == 0 && height > 1
;-----------------------------------------------------------------------------------------------------------------------------
;void SumOf16x16BlockOfFrame_sse4(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;-----------------------------------------------------------------------------------------------------------------------------
; try 8 mv via offset
%macro SUM_LINE_X16_SSE41 5 ; ref, dst0, dst1, tmp0, tmp1
movdqu %2, [%1]
movdqu %3, [%1+8h]
movdqa %4, %2
movdqa %5, %3
mpsadbw %2, xmm0, 0 ; 000 B
mpsadbw %4, xmm0, 5 ; 101 B
mpsadbw %3, xmm0, 2 ; 010 B
mpsadbw %5, xmm0, 7 ; 111 B
paddw %2, %4
paddw %3, %5
paddw %2, %3 ; accumulate cost
%endmacro ; end of SAD_16x16_LINE_SSE41
WELS_EXTERN SumOf16x16BlockOfFrame_sse4
%define pushsize 16
%define localsize 4
%define ref esp + pushsize + localsize + 4
%define sum_ref esp + pushsize + localsize + 20
%define times_of_sum esp + pushsize + localsize + 24
%define width esp + pushsize + localsize + 8
%define height esp + pushsize + localsize + 12
%define linesize esp + pushsize + localsize + 16
%define tmp_width esp
push ebx
push ebp
push esi
push edi
sub esp, localsize
pxor xmm0, xmm0
mov esi, [ref]
mov edi, [sum_ref]
mov edx, [times_of_sum]
mov ebx, [linesize]
mov eax, [width]
lea ecx, [ebx+ebx*2]
mov [tmp_width], eax
FIRST_ROW_X16_SSE4:
SUM_LINE_X16_SSE41 esi, xmm1, xmm2, xmm3, xmm4
SUM_LINE_X16_SSE41 esi+ebx, xmm2, xmm3, xmm4, xmm5
SUM_LINE_X16_SSE41 esi+ebx*2, xmm3, xmm4, xmm5, xmm6
SUM_LINE_X16_SSE41 esi+ecx, xmm4, xmm5, xmm6, xmm7
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
lea ebp, [esi+ebx*4]
SUM_LINE_X16_SSE41 ebp, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ecx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
lea ebp, [ebp+ebx*4]
SUM_LINE_X16_SSE41 ebp, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ecx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
lea ebp, [ebp+ebx*4]
SUM_LINE_X16_SSE41 ebp, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ebx*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 ebp+ecx, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
movdqa [edi], xmm1
movdqa xmm2, xmm1
punpcklwd xmm1, xmm0
punpckhwd xmm2, xmm0
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 1
COUNT_SUM xmm1, eax, 0
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 1
COUNT_SUM xmm2, eax, 0
lea esi, [esi+8]
lea edi, [edi+16] ; element size is 2
sub dword [tmp_width], 8
jg near FIRST_ROW_X16_SSE4
mov esi, [ref]
mov edi, [sum_ref]
mov ebp, [width]
dec dword [height]
mov ecx, ebx
sal ecx, 4 ; succeeded 16th line
HEIGHT_LOOP_X16_SSE4:
mov [tmp_width], ebp
WIDTH_LOOP_X16_SSE4:
movdqa xmm7, [edi]
SUM_LINE_X16_SSE41 esi+ecx, xmm1, xmm2, xmm3, xmm4
SUM_LINE_X16_SSE41 esi, xmm2, xmm3, xmm4, xmm5
paddw xmm7, xmm1
psubw xmm7, xmm2
movdqa [edi+ebp*2], xmm7
movdqa xmm6, xmm7
punpcklwd xmm7, xmm0
punpckhwd xmm6, xmm0
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 1
COUNT_SUM xmm7, eax, 0
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 1
COUNT_SUM xmm6, eax, 0
lea esi, [esi+8]
lea edi, [edi+16]
sub dword [tmp_width], 8
jg near WIDTH_LOOP_X16_SSE4
add esi, ebx
sub esi, ebp
dec dword [height]
jg near HEIGHT_LOOP_X16_SSE4
add esp, localsize
pop edi
pop esi
pop ebp
pop ebx
%undef pushsize
%undef localsize
%undef ref
%undef sum_ref
%undef times_of_sum
%undef width
%undef height
%undef linesize
%undef tmp_width
ret
;-----------------------------------------------------------------------------------------------------------------------------
; void FillQpelLocationByFeatureValue_sse2(uint16_t* pFeatureOfBlock, const int32_t kiWidth, const int32_t kiHeight, uint16_t** pFeatureValuePointerList)
;-----------------------------------------------------------------------------------------------------------------------------
WELS_EXTERN FillQpelLocationByFeatureValue_sse2
push esi
push edi
push ebx
push ebp
%define _ps 16 ; push size
%define _ls 4 ; local size
%define sum_ref esp+_ps+_ls+4
%define pos_list esp+_ps+_ls+16
%define width esp+_ps+_ls+8
%define height esp+_ps+_ls+12
%define i_height esp
sub esp, _ls
mov esi, [sum_ref]
mov edi, [pos_list]
mov ebp, [width]
mov ebx, [height]
mov [i_height], ebx
movq xmm7, [mv_x_inc_x4] ; x_qpel inc
movq xmm6, [mv_y_inc_x4] ; y_qpel inc
movq xmm5, [mx_x_offset_x4] ; x_qpel vector
pxor xmm4, xmm4
pxor xmm3, xmm3 ; y_qpel vector
HASH_HEIGHT_LOOP_SSE2:
movdqa xmm2, xmm5 ; x_qpel vector
mov ecx, ebp
HASH_WIDTH_LOOP_SSE2:
movq xmm0, [esi] ; load x8 sum
punpcklwd xmm0, xmm4
movdqa xmm1, xmm2
punpcklwd xmm1, xmm3
%rep 3
movd edx, xmm0
lea ebx, [edi+edx*4]
mov eax, [ebx]
movd [eax], xmm1
mov edx, [eax+4] ; explictly load eax+4 due cache miss from vtune observation
lea eax, [eax+4]
mov [ebx], eax
psrldq xmm1, 4
psrldq xmm0, 4
%endrep
movd edx, xmm0
lea ebx, [edi+edx*4]
mov eax, [ebx]
movd [eax], xmm1
mov edx, [eax+4] ; explictly load eax+4 due cache miss from vtune observation
lea eax, [eax+4]
mov [ebx], eax
paddw xmm2, xmm7
lea esi, [esi+8]
sub ecx, 4
jnz near HASH_WIDTH_LOOP_SSE2
paddw xmm3, xmm6
dec dword [i_height]
jnz near HASH_HEIGHT_LOOP_SSE2
add esp, _ls
%undef _ps
%undef _ls
%undef sum_ref
%undef pos_list
%undef width
%undef height
%undef i_height
pop ebp
pop ebx
pop edi
pop esi
ret
;---------------------------------------------------------------------------------------------------------------------------------------------------
; void InitializeHashforFeature_sse2( uint32_t* pTimesOfFeatureValue, uint16_t* pBuf, const int32_t kiListSize,
; uint16_t** pLocationOfFeature, uint16_t** pFeatureValuePointerList )
;---------------------------------------------------------------------------------------------------------------------------------------------------
WELS_EXTERN InitializeHashforFeature_sse2
push ebx
push esi
push edi
push ebp
%define _ps 16 ; push size
mov edi, [esp+_ps+16] ; pPositionOfSum
mov ebp, [esp+_ps+20] ; sum_idx_list
mov esi, [esp+_ps+4] ; pTimesOfSum
mov ebx, [esp+_ps+8] ; pBuf
mov edx, [esp+_ps+12] ; list_sz
sar edx, 2
mov ecx, 0
pxor xmm7, xmm7
hash_assign_loop_x4_sse2:
movdqa xmm0, [esi+ecx]
pslld xmm0, 2
movdqa xmm1, xmm0
pcmpeqd xmm1, xmm7
movmskps eax, xmm1
cmp eax, 0x0f
je near hash_assign_with_copy_sse2
%assign x 0
%rep 4
lea eax, [edi+ecx+x]
mov [eax], ebx
lea eax, [ebp+ecx+x]
mov [eax], ebx
movd eax, xmm0
add ebx, eax
psrldq xmm0, 4
%assign x x+4
%endrep
jmp near assign_next_sse2
hash_assign_with_copy_sse2:
movd xmm1, ebx
pshufd xmm2, xmm1, 0
movdqa [edi+ecx], xmm2
movdqa [ebp+ecx], xmm2
assign_next_sse2:
add ecx, 16
dec edx
jnz near hash_assign_loop_x4_sse2
mov edx, [esp+_ps+12] ; list_sz
and edx, 3
jz near hash_assign_no_rem_sse2
hash_assign_loop_x4_rem_sse2:
lea eax, [edi+ecx]
mov [eax], ebx
lea eax, [ebp+ecx]
mov [eax], ebx
mov eax, [esi+ecx]
sal eax, 2
add ebx, eax
add ecx, 4
dec edx
jnz near hash_assign_loop_x4_rem_sse2
hash_assign_no_rem_sse2:
%undef _ps
pop ebp
pop edi
pop esi
pop ebx
ret
%else
;**********************************************************************************************************************
;void SumOf8x8BlockOfFrame_sse2(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;*********************************************************************************************************************
WELS_EXTERN SumOf8x8BlockOfFrame_sse2
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 6
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r2, r2d
SIGN_EXTENSION r3, r3d
push r12
push r13
push r0
push r2
push r4
pxor xmm0, xmm0
lea r6, [r3+r3*2]
mov r12, r1 ;r12:tmp_width
lea r13, [r0+r3*4] ;rbp:r13
FIRST_ROW:
movq xmm1, [r0]
movq xmm2, [r0+r3]
movq xmm3, [r0+r3*2]
movq xmm4, [r0+r6]
shufps xmm1, xmm2, 01000100b
shufps xmm3, xmm4, 01000100b
psadbw xmm1, xmm0
psadbw xmm3, xmm0
paddd xmm1, xmm3
movq xmm2, [r13]
movq xmm3, [r13+r3]
movq xmm4, [r13+r3*2]
movq xmm5, [r13+r6]
shufps xmm2, xmm3, 01000100b
shufps xmm4, xmm5, 01000100b
psadbw xmm2, xmm0
psadbw xmm4, xmm0
paddd xmm2, xmm4
paddd xmm1, xmm2
pshufd xmm2, xmm1, 00001110b
paddd xmm1, xmm2
movd r2d, xmm1
mov [r4], r2w
inc dword [r5+r2*4]
inc r0
inc r13
add r4, 2
dec r12
jg FIRST_ROW
pop r4
pop r2
pop r0
mov r13, r2
dec r13
HEIGHT_LOOP:
mov r12, r1
WIDTH_LOOP:
movq xmm1, [r0+r3*8]
movq xmm2, [r0]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psubd xmm1, xmm2
movd r2d, xmm1
mov r6w, [r4]
add r2d, r6d
mov [r4+r1*2], r2w
inc dword [r5+r2*4]
inc r0
add r4, 2
dec r12
jg WIDTH_LOOP
add r0, r3
sub r0, r1
dec r13
jg HEIGHT_LOOP
pop r13
pop r12
POP_XMM
LOAD_6_PARA_POP
ret
%macro COUNT_SUM 4
%define xmm_reg %1
%define tmp_dreg %2
%define tmp_qreg %3
movd tmp_dreg, xmm_reg
inc dword [r5+tmp_qreg*4]
%if %4 == 1
psrldq xmm_reg, 4
%endif
%endmacro
;-----------------------------------------------------------------------------
; requires: width % 8 == 0 && height > 1
;-----------------------------------------------------------------------------
;void SumOf8x8BlockOfFrame_sse4(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;-----------------------------------------------------------------------------
; read extra (16 - (width % 8) ) mod 16 bytes of every line
; write extra (16 - (width % 8)*2 ) mod 16 bytes in the end of sum_ref
WELS_EXTERN SumOf8x8BlockOfFrame_sse4
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 8
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r2, r2d
SIGN_EXTENSION r3, r3d
push r12
push r13
push r0
push r2
push r4
pxor xmm0, xmm0
lea r6, [r3+r3*2]
mov r12, r1 ;r12:tmp_width
lea r13, [r0+r3*4] ;rbp:r13
FIRST_ROW_SSE4:
movdqu xmm1, [r0]
movdqu xmm3, [r0+r3]
movdqu xmm5, [r0+r3*2]
movdqu xmm7, [r0+r6]
movdqa xmm2, xmm1
mpsadbw xmm1, xmm0, 000b
mpsadbw xmm2, xmm0, 100b
paddw xmm1, xmm2 ; 8 sums of line1
movdqa xmm4, xmm3
mpsadbw xmm3, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm3, xmm4 ; 8 sums of line2
movdqa xmm2, xmm5
mpsadbw xmm5, xmm0, 000b
mpsadbw xmm2, xmm0, 100b
paddw xmm5, xmm2 ; 8 sums of line3
movdqa xmm4, xmm7
mpsadbw xmm7, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm7, xmm4 ; 8 sums of line4
paddw xmm1, xmm3
paddw xmm5, xmm7
paddw xmm1, xmm5 ; sum the upper 4 lines first
movdqu xmm2, [r13]
movdqu xmm3, [r13+r3]
movdqu xmm4, [r13+r3*2]
movdqu xmm5, [r13+r6]
movdqa xmm6, xmm2
mpsadbw xmm2, xmm0, 000b
mpsadbw xmm6, xmm0, 100b
paddw xmm2, xmm6
movdqa xmm7, xmm3
mpsadbw xmm3, xmm0, 000b
mpsadbw xmm7, xmm0, 100b
paddw xmm3, xmm7
movdqa xmm6, xmm4
mpsadbw xmm4, xmm0, 000b
mpsadbw xmm6, xmm0, 100b
paddw xmm4, xmm6
movdqa xmm7, xmm5
mpsadbw xmm5, xmm0, 000b
mpsadbw xmm7, xmm0, 100b
paddw xmm5, xmm7
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm1, xmm2
paddw xmm1, xmm4 ; sum of lines 1- 8
movdqu [r4], xmm1
movdqa xmm2, xmm1
punpcklwd xmm1, xmm0
punpckhwd xmm2, xmm0
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 0
COUNT_SUM xmm2, r2d, r2 ,1
COUNT_SUM xmm2, r2d, r2 ,1
COUNT_SUM xmm2, r2d, r2 ,1
COUNT_SUM xmm2, r2d, r2 ,0
lea r0, [r0+8]
lea r13, [r13+8]
lea r4, [r4+16] ; element size is 2
sub r12, 8
jg near FIRST_ROW_SSE4
pop r4
pop r2
pop r0
mov r13, r2
dec r13
HEIGHT_LOOP_SSE4:
mov r12, r1
WIDTH_LOOP_SSE4:
movdqu xmm1, [r0+r3*8]
movdqu xmm2, [r0]
movdqu xmm7, [r4]
movdqa xmm3, xmm1
mpsadbw xmm1, xmm0, 000b
mpsadbw xmm3, xmm0, 100b
paddw xmm1, xmm3
movdqa xmm4, xmm2
mpsadbw xmm2, xmm0, 000b
mpsadbw xmm4, xmm0, 100b
paddw xmm2, xmm4
paddw xmm7, xmm1
psubw xmm7, xmm2
movdqu [r4+r1*2], xmm7
movdqa xmm6, xmm7
punpcklwd xmm7, xmm0
punpckhwd xmm6, xmm0
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 0
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 0
lea r0, [r0+8]
lea r4, [r4+16]
sub r12, 8
jg near WIDTH_LOOP_SSE4
lea r0, [r0+r3]
sub r0, r1
dec r13
jg near HEIGHT_LOOP_SSE4
pop r13
pop r12
POP_XMM
LOAD_6_PARA_POP
ret
;****************************************************************************************************************************************************
;void SumOf16x16BlockOfFrame_sse2(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;****************************************************************************************************************************************************
WELS_EXTERN SumOf16x16BlockOfFrame_sse2
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 6
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r2, r2d
SIGN_EXTENSION r3, r3d
push r12
push r13
push r0
push r2
push r4
pxor xmm0, xmm0
lea r6, [r3+r3*2]
mov r12, r1 ;r12:tmp_width
FIRST_ROW_X16H:
movdqu xmm1, [r0]
movdqu xmm2, [r0+r3]
movdqu xmm3, [r0+r3*2]
movdqu xmm4, [r0+r6]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
lea r13, [r0+r3*4] ;ebp:r13
movdqu xmm2, [r13]
movdqu xmm3, [r13+r3]
movdqu xmm4, [r13+r3*2]
movdqu xmm5, [r13+r6]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea r13, [r13+r3*4]
movdqu xmm2, [r13]
movdqu xmm3, [r13+r3]
movdqu xmm4, [r13+r3*2]
movdqu xmm5, [r13+r6]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea r13, [r13+r3*4]
movdqu xmm2, [r13]
movdqu xmm3, [r13+r3]
movdqu xmm4, [r13+r3*2]
movdqu xmm5, [r13+r6]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd r2d, xmm1
mov [r4], r2w
inc dword [r5+r2*4]
inc r0
lea r4, [r4+2]
dec r12
jg near FIRST_ROW_X16H
pop r4
pop r2
pop r0
mov r13, r2
dec r13
mov r6, r3
sal r6, 4 ; succeeded 16th line
HEIGHT_LOOP_X16:
mov r12, r1
WIDTH_LOOP_X16:
movdqu xmm1, [r0+r6]
movdqu xmm2, [r0]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psubw xmm1, xmm2
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd r2d, xmm1
add r2w, word [r4]
mov [r4+r1*2], r2w
inc dword [r5+r2*4]
inc r0
add r4, 2
dec r12
jg near WIDTH_LOOP_X16
add r0, r3
sub r0, r1
dec r13
jg near HEIGHT_LOOP_X16
pop r13
pop r12
POP_XMM
LOAD_6_PARA_POP
ret
; requires: width % 16 == 0 && height > 1
;-----------------------------------------------------------------------------------------------------------------------------
;void SumOf16x16BlockOfFrame_sse4(uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight, const int32_t kiRefStride,
; uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]);
;-----------------------------------------------------------------------------------------------------------------------------
; try 8 mv via offset
%macro SUM_LINE_X16_SSE41 5 ; ref, dst0, dst1, tmp0, tmp1
movdqu %2, [%1]
movdqu %3, [%1+8h]
movdqa %4, %2
movdqa %5, %3
mpsadbw %2, xmm0, 0 ; 000 B
mpsadbw %4, xmm0, 5 ; 101 B
mpsadbw %3, xmm0, 2 ; 010 B
mpsadbw %5, xmm0, 7 ; 111 B
paddw %2, %4
paddw %3, %5
paddw %2, %3 ; accumulate cost
%endmacro ; end of SAD_16x16_LINE_SSE41
WELS_EXTERN SumOf16x16BlockOfFrame_sse4
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 8
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r2, r2d
SIGN_EXTENSION r3, r3d
push r12
push r13
push r0
push r2
push r4
pxor xmm0, xmm0
lea r6, [r3+r3*2]
mov r12, r1 ;r12:tmp_width
FIRST_ROW_X16_SSE4:
SUM_LINE_X16_SSE41 r0, xmm1, xmm2, xmm3, xmm4
SUM_LINE_X16_SSE41 r0+r3, xmm2, xmm3, xmm4, xmm5
SUM_LINE_X16_SSE41 r0+r3*2,xmm3, xmm4, xmm5, xmm6
SUM_LINE_X16_SSE41 r0+r6, xmm4, xmm5, xmm6, xmm7
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
lea r13, [r0+r3*4]
SUM_LINE_X16_SSE41 r13, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r6, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
lea r13, [r13+r3*4]
SUM_LINE_X16_SSE41 r13, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r6, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
lea r13, [r13+r3*4]
SUM_LINE_X16_SSE41 r13, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r3*2, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
SUM_LINE_X16_SSE41 r13+r6, xmm2, xmm3, xmm4, xmm5
paddw xmm1, xmm2
movdqa [r4], xmm1
movdqa xmm2, xmm1
punpcklwd xmm1, xmm0
punpckhwd xmm2, xmm0
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 1
COUNT_SUM xmm1, r2d, r2, 0
COUNT_SUM xmm2, r2d, r2, 1
COUNT_SUM xmm2, r2d, r2, 1
COUNT_SUM xmm2, r2d, r2, 1
COUNT_SUM xmm2, r2d, r2, 0
lea r0, [r0+8]
lea r4, [r4+16] ; element size is 2
sub r12, 8
jg near FIRST_ROW_X16_SSE4
pop r4
pop r2
pop r0
mov r13, r2
dec r13
mov r6, r3
sal r6, 4 ; succeeded 16th line
HEIGHT_LOOP_X16_SSE4:
mov r12, r1
WIDTH_LOOP_X16_SSE4:
movdqa xmm7, [r4]
SUM_LINE_X16_SSE41 r0+r6, xmm1, xmm2, xmm3, xmm4
SUM_LINE_X16_SSE41 r0, xmm2, xmm3, xmm4, xmm5
paddw xmm7, xmm1
psubw xmm7, xmm2
movdqa [r4+r1*2], xmm7
movdqa xmm6, xmm7
punpcklwd xmm7, xmm0
punpckhwd xmm6, xmm0
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 1
COUNT_SUM xmm7, r2d, r2, 0
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 1
COUNT_SUM xmm6, r2d, r2, 0
lea r0, [r0+8]
lea r4, [r4+16]
sub r12, 8
jg near WIDTH_LOOP_X16_SSE4
add r0, r3
sub r0, r1
dec r13
jg near HEIGHT_LOOP_X16_SSE4
pop r13
pop r12
POP_XMM
LOAD_6_PARA_POP
ret
;-----------------------------------------------------------------------------------------------------------------------------
; void FillQpelLocationByFeatureValue_sse2(uint16_t* pFeatureOfBlock, const int32_t kiWidth, const int32_t kiHeight, uint16_t** pFeatureValuePointerList)
;-----------------------------------------------------------------------------------------------------------------------------
WELS_EXTERN FillQpelLocationByFeatureValue_sse2
%assign push_num 0
LOAD_4_PARA
PUSH_XMM 8
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r2, r2d
push r12
push r13
mov r12, r2
movq xmm7, [mv_x_inc_x4] ; x_qpel inc
movq xmm6, [mv_y_inc_x4] ; y_qpel inc
movq xmm5, [mx_x_offset_x4] ; x_qpel vector
pxor xmm4, xmm4
pxor xmm3, xmm3 ; y_qpel vector
HASH_HEIGHT_LOOP_SSE2:
movdqa xmm2, xmm5 ; x_qpel vector
mov r4, r1
HASH_WIDTH_LOOP_SSE2:
movq xmm0, [r0] ; load x8 sum
punpcklwd xmm0, xmm4
movdqa xmm1, xmm2
punpcklwd xmm1, xmm3
%rep 3
movd r2d, xmm0 ;edx:r3
lea r5, [r3+r2*8] ;ebx:r5
mov r6, [r5] ;eax:r6
movd [r6], xmm1
mov r13, [r6+4] ; explictly load eax+4 due cache miss from vtune observation
lea r6, [r6+4]
mov [r5], r6
psrldq xmm1, 4
psrldq xmm0, 4
%endrep
movd r2d, xmm0
lea r5, [r3+r2*8] ;ebx:r5
mov r6, [r5] ;eax:r6
movd [r6], xmm1
mov r13, [r6+4] ; explictly load eax+4 due cache miss from vtune observation
lea r6, [r6+4]
mov [r5], r6
paddw xmm2, xmm7
lea r0, [r0+8]
sub r4, 4
jnz near HASH_WIDTH_LOOP_SSE2
paddw xmm3, xmm6
dec r12
jnz near HASH_HEIGHT_LOOP_SSE2
pop r13
pop r12
POP_XMM
ret
;---------------------------------------------------------------------------------------------------------------------------------------------------
; void InitializeHashforFeature_sse2( uint32_t* pTimesOfFeatureValue, uint16_t* pBuf, const int32_t kiListSize,
; uint16_t** pLocationOfFeature, uint16_t** pFeatureValuePointerList);
;uint16_t** pPositionOfSum, uint16_t** sum_idx_list, uint32_t* pTimesOfSum, uint16_t* pBuf, const int32_t list_sz )
;---------------------------------------------------------------------------------------------------------------------------------------------------
WELS_EXTERN InitializeHashforFeature_sse2
%assign push_num 0
LOAD_5_PARA
SIGN_EXTENSION r2, r2d
push r12
push r13
mov r12, r2
sar r2, 2
mov r5, 0 ;r5:ecx
xor r6, r6
pxor xmm3, xmm3
hash_assign_loop_x4_sse2:
movdqa xmm0, [r0+r5]
pslld xmm0, 2
movdqa xmm1, xmm0
pcmpeqd xmm1, xmm3
movmskps r6, xmm1
cmp r6, 0x0f
jz near hash_assign_with_copy_sse2
%assign x 0
%rep 4
lea r13, [r3+r5*2+x]
mov [r13], r1
lea r13, [r4+r5*2+x]
mov [r13], r1
movd r6d, xmm0
add r1, r6
psrldq xmm0, 4
%assign x x+8
%endrep
jmp near assign_next_sse2
hash_assign_with_copy_sse2:
movq xmm1, r1
pshufd xmm2, xmm1, 01000100b
movdqa [r3+r5*2], xmm2
movdqa [r4+r5*2], xmm2
movdqa [r3+r5*2+16], xmm2
movdqa [r4+r5*2+16], xmm2
assign_next_sse2:
add r5, 16
dec r2
jnz near hash_assign_loop_x4_sse2
and r12, 3
jz near hash_assign_no_rem_sse2
hash_assign_loop_x4_rem_sse2:
lea r13, [r3+r5*2]
mov [r13], r1
lea r13, [r4+r5*2]
mov [r13], r1
mov r6d, [r0+r5]
sal r6, 2
add r1, r6
add r5, 4
dec r12
jnz near hash_assign_loop_x4_rem_sse2
hash_assign_no_rem_sse2:
pop r13
pop r12
ret
%endif
;**********************************************************************************************************************************
; int32_t SumOf8x8SingleBlock_sse2(uint8_t* ref0, int32_t linesize)
;**********************************************************************************************************************************
WELS_EXTERN SumOf8x8SingleBlock_sse2
%assign push_num 0
LOAD_2_PARA
SIGN_EXTENSION r1, r1d
pxor xmm0, xmm0
movq xmm1, [r0]
movhps xmm1, [r0+r1]
lea r0, [r0+2*r1]
movq xmm2, [r0]
movhps xmm2, [r0+r1]
lea r0, [r0+2*r1]
movq xmm3, [r0]
movhps xmm3, [r0+r1]
lea r0, [r0+2*r1]
movq xmm4, [r0]
movhps xmm4, [r0+r1]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd retrd, xmm1
ret
;**********************************************************************************************************************************
; int32_t SumOf16x16SingleBlock_sse2(uint8_t* ref0, int32_t linesize)
;**********************************************************************************************************************************
WELS_EXTERN SumOf16x16SingleBlock_sse2
%assign push_num 0
LOAD_2_PARA
PUSH_XMM 6
SIGN_EXTENSION r1, r1d
pxor xmm0, xmm0
movdqa xmm1, [r0]
movdqa xmm2, [r0+r1]
lea r0, [r0+2*r1]
movdqa xmm3, [r0]
movdqa xmm4, [r0+r1]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
paddw xmm1, xmm2
paddw xmm3, xmm4
paddw xmm1, xmm3
lea r0, [r0+2*r1]
movdqa xmm2, [r0]
movdqa xmm3, [r0+r1]
lea r0, [r0+2*r1]
movdqa xmm4, [r0]
movdqa xmm5, [r0+r1]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea r0, [r0+2*r1]
movdqa xmm2, [r0]
movdqa xmm3, [r0+r1]
lea r0, [r0+2*r1]
movdqa xmm4, [r0]
movdqa xmm5, [r0+r1]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
lea r0, [r0+2*r1]
movdqa xmm2, [r0]
movdqa xmm3, [r0+r1]
lea r0, [r0+2*r1]
movdqa xmm4, [r0]
movdqa xmm5, [r0+r1]
psadbw xmm2, xmm0
psadbw xmm3, xmm0
psadbw xmm4, xmm0
psadbw xmm5, xmm0
paddw xmm2, xmm3
paddw xmm4, xmm5
paddw xmm2, xmm4
paddw xmm1, xmm2
movdqa xmm2, xmm1
punpckhwd xmm2, xmm0
paddw xmm1, xmm2
movd retrd, xmm1
POP_XMM
ret
;**********************************************************************************************************************************
;
; uint32_t SampleSad16x16Hor8_sse41( uint8_t *src, int32_t stride_src, uint8_t *ref, int32_t stride_ref, uint16 base_cost[8], int32_t *index_min_cost )
;
; \note:
; src need align with 16 bytes, ref is optional
; \return value:
; return minimal SAD cost, according index carried by index_min_cost
;**********************************************************************************************************************************
; try 8 mv via offset
; xmm7 store sad costs
%macro SAD_16x16_LINE_SSE41 4 ; src, ref, stride_src, stride_ref
movdqa xmm0, [%1]
movdqu xmm1, [%2]
movdqu xmm2, [%2+8h]
movdqa xmm3, xmm1
movdqa xmm4, xmm2
mpsadbw xmm1, xmm0, 0 ; 000 B
paddw xmm7, xmm1 ; accumulate cost
mpsadbw xmm3, xmm0, 5 ; 101 B
paddw xmm7, xmm3 ; accumulate cost
mpsadbw xmm2, xmm0, 2 ; 010 B
paddw xmm7, xmm2 ; accumulate cost
mpsadbw xmm4, xmm0, 7 ; 111 B
paddw xmm7, xmm4 ; accumulate cost
add %1, %3
add %2, %4
%endmacro ; end of SAD_16x16_LINE_SSE41
%macro SAD_16x16_LINE_SSE41E 4 ; src, ref, stride_src, stride_ref
movdqa xmm0, [%1]
movdqu xmm1, [%2]
movdqu xmm2, [%2+8h]
movdqa xmm3, xmm1
movdqa xmm4, xmm2
mpsadbw xmm1, xmm0, 0 ; 000 B
paddw xmm7, xmm1 ; accumulate cost
mpsadbw xmm3, xmm0, 5 ; 101 B
paddw xmm7, xmm3 ; accumulate cost
mpsadbw xmm2, xmm0, 2 ; 010 B
paddw xmm7, xmm2 ; accumulate cost
mpsadbw xmm4, xmm0, 7 ; 111 B
paddw xmm7, xmm4 ; accumulate cost
%endmacro ; end of SAD_16x16_LINE_SSE41E
WELS_EXTERN SampleSad16x16Hor8_sse41
;push ebx
;push esi
;mov eax, [esp+12] ; src
;mov ecx, [esp+16] ; stride_src
;mov ebx, [esp+20] ; ref
;mov edx, [esp+24] ; stride_ref
;mov esi, [esp+28] ; base_cost
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 8
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r3, r3d
pxor xmm7, xmm7
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41 r0, r2, r1, r3
SAD_16x16_LINE_SSE41E r0, r2, r1, r3
pxor xmm0, xmm0
movdqa xmm6, xmm7
punpcklwd xmm6, xmm0
punpckhwd xmm7, xmm0
movdqa xmm5, [r4]
movdqa xmm4, xmm5
punpcklwd xmm4, xmm0
punpckhwd xmm5, xmm0
paddd xmm4, xmm6
paddd xmm5, xmm7
movdqa xmm3, xmm4
pminud xmm3, xmm5
pshufd xmm2, xmm3, 01001110B
pminud xmm2, xmm3
pshufd xmm3, xmm2, 10110001B
pminud xmm2, xmm3
movd retrd, xmm2
pcmpeqd xmm4, xmm2
movmskps r2d, xmm4
bsf r1d, r2d
jnz near WRITE_INDEX
pcmpeqd xmm5, xmm2
movmskps r2d, xmm5
bsf r1d, r2d
add r1d, 4
WRITE_INDEX:
mov [r5], r1d
POP_XMM
LOAD_6_PARA_POP
ret
;**********************************************************************************************************************************
;
; uint32_t SampleSad8x8Hor8_sse41( uint8_t *src, int32_t stride_src, uint8_t *ref, int32_t stride_ref, uint16_t base_cost[8], int32_t *index_min_cost )
;
; \note:
; src and ref is optional to align with 16 due inter 8x8
; \return value:
; return minimal SAD cost, according index carried by index_min_cost
;
;**********************************************************************************************************************************
; try 8 mv via offset
; xmm7 store sad costs
%macro SAD_8x8_LINE_SSE41 4 ; src, ref, stride_src, stride_ref
movdqu xmm0, [%1]
movdqu xmm1, [%2]
movdqa xmm2, xmm1
mpsadbw xmm1, xmm0, 0 ; 000 B
paddw xmm7, xmm1 ; accumulate cost
mpsadbw xmm2, xmm0, 5 ; 101 B
paddw xmm7, xmm2 ; accumulate cost
add %1, %3
add %2, %4
%endmacro ; end of SAD_8x8_LINE_SSE41
%macro SAD_8x8_LINE_SSE41E 4 ; src, ref, stride_src, stride_ref
movdqu xmm0, [%1]
movdqu xmm1, [%2]
movdqa xmm2, xmm1
mpsadbw xmm1, xmm0, 0 ; 000 B
paddw xmm7, xmm1 ; accumulate cost
mpsadbw xmm2, xmm0, 5 ; 101 B
paddw xmm7, xmm2 ; accumulate cost
%endmacro ; end of SAD_8x8_LINE_SSE41E
WELS_EXTERN SampleSad8x8Hor8_sse41
%assign push_num 0
LOAD_6_PARA
PUSH_XMM 8
SIGN_EXTENSION r1, r1d
SIGN_EXTENSION r3, r3d
movdqa xmm7, [r4] ; load base cost list
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41 r0, r2, r1, r3
SAD_8x8_LINE_SSE41E r0, r2, r1, r3
phminposuw xmm0, xmm7 ; horizon search the minimal sad cost and its index
movd retrd, xmm0 ; for return: DEST[15:0] <- MIN, DEST[31:16] <- INDEX
mov r1d, retrd
and retrd, 0xFFFF
sar r1d, 16
mov [r5], r1d
POP_XMM
LOAD_6_PARA_POP
ret
|
dnl mpn_nand_n
dnl Copyright 2009 Jason Moxham
dnl This file is part of the MPIR Library.
dnl The MPIR Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 2.1 of the License, or (at
dnl your option) any later version.
dnl The MPIR Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the MPIR Library; see the file COPYING.LIB. If not, write
dnl to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
dnl Boston, MA 02110-1301, USA.
include(`../config.m4')
C ret mpn_nand_n(mp_ptr,mp_srcptr,mp_srcptr,mp_size_t)
C rax rdi, rsi, rdx, rcx
ASM_START()
PROLOGUE(mpn_nand_n)
mov $3,%r8
lea -24(%rsi,%rcx,8),%rsi
lea -24(%rdx,%rcx,8),%rdx
lea -24(%rdi,%rcx,8),%rdi
pcmpeqb %xmm4,%xmm4
sub %rcx,%r8
jnc skiplp
ALIGN(16)
lp:
movdqu (%rdx,%r8,8),%xmm0
movdqu 16(%rdx,%r8,8),%xmm1
movdqu (%rsi,%r8,8),%xmm2
add $4,%r8
movdqu 16-32(%rsi,%r8,8),%xmm3
pand %xmm3,%xmm1
pand %xmm2,%xmm0
pxor %xmm4,%xmm0
movdqu %xmm0,-32(%rdi,%r8,8)
pxor %xmm4,%xmm1
movdqu %xmm1,16-32(%rdi,%r8,8)
jnc lp
skiplp:
cmp $2,%r8
ja case0
je case1
jp case2
case3: movdqu (%rdx,%r8,8),%xmm0
mov 16(%rdx,%r8,8),%rax
movdqu (%rsi,%r8,8),%xmm2
mov 16(%rsi,%r8,8),%rcx
and %rcx,%rax
pand %xmm2,%xmm0
pxor %xmm4,%xmm0
movdqu %xmm0,(%rdi,%r8,8)
not %rax
mov %rax,16(%rdi,%r8,8)
case0: ret
case2: movdqu (%rdx,%r8,8),%xmm0
movdqu (%rsi,%r8,8),%xmm2
pand %xmm2,%xmm0
pxor %xmm4,%xmm0
movdqu %xmm0,(%rdi,%r8,8)
ret
case1: mov (%rdx,%r8,8),%rax
mov (%rsi,%r8,8),%rcx
and %rcx,%rax
not %rax
mov %rax,(%rdi,%r8,8)
ret
EPILOGUE()
|
; A159920: Sums of the antidiagonals of Sundaram's sieve (A159919).
; 4,14,32,60,100,154,224,312,420,550,704,884,1092,1330,1600,1904,2244,2622,3040,3500,4004,4554,5152,5800,6500,7254,8064,8932,9860,10850,11904,13024,14212,15470,16800,18204,19684,21242,22880,24600,26404
add $0,4
mov $1,$0
bin $1,3
sub $1,$0
mul $1,2
add $1,4
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "android_webview/native/android_webview_jni_registrar.h"
#include "base/android/jni_android.h"
#include "base/test/test_suite.h"
int main(int argc, char** argv) {
android_webview::RegisterJni(base::android::AttachCurrentThread());
return base::TestSuite(argc, argv).Run();
}
|
ReinitBattleAnimFrameset:
ld hl, BATTLEANIMSTRUCT_FRAMESET_ID
add hl, bc
ld [hl], a
ld hl, BATTLEANIMSTRUCT_DURATION
add hl, bc
ld [hl], 0
ld hl, BATTLEANIMSTRUCT_FRAME
add hl, bc
ld [hl], -1
ret
GetBattleAnimFrame:
.loop
ld hl, BATTLEANIMSTRUCT_DURATION
add hl, bc
ld a, [hl]
and a
jr z, .next_frame
dec [hl]
call .GetPointer
ld a, [hli]
push af
jr .okay
.next_frame
ld hl, BATTLEANIMSTRUCT_FRAME
add hl, bc
inc [hl]
call .GetPointer
ld a, [hli]
cp dorestart_command
jr z, .restart
cp endanim_command
jr z, .repeat_last
push af
ld a, [hl]
push hl
and $ff ^ (Y_FLIP << 1 | X_FLIP << 1)
ld hl, BATTLEANIMSTRUCT_DURATION
add hl, bc
ld [hl], a
pop hl
.okay
ld a, [hl]
and Y_FLIP << 1 | X_FLIP << 1 ; The << 1 is compensated in the "frame" macro
srl a
ld [wBattleAnimTempFrameOAMFlags], a
pop af
ret
.repeat_last
xor a
ld hl, BATTLEANIMSTRUCT_DURATION
add hl, bc
ld [hl], a
ld hl, BATTLEANIMSTRUCT_FRAME
add hl, bc
dec [hl]
dec [hl]
jr .loop
.restart
xor a
ld hl, BATTLEANIMSTRUCT_DURATION
add hl, bc
ld [hl], a
dec a
ld hl, BATTLEANIMSTRUCT_FRAME
add hl, bc
ld [hl], a
jr .loop
.GetPointer:
ld hl, BATTLEANIMSTRUCT_FRAMESET_ID
add hl, bc
ld e, [hl]
ld d, 0
ld hl, BattleAnimFrameData
add hl, de
add hl, de
ld e, [hl]
inc hl
ld d, [hl]
ld hl, BATTLEANIMSTRUCT_FRAME
add hl, bc
ld l, [hl]
ld h, $0
add hl, hl
add hl, de
ret
GetBattleAnimOAMPointer:
ld l, a
ld h, 0
ld de, BattleAnimOAMData
add hl, hl
add hl, hl
add hl, de
ret
LoadBattleAnimGFX:
push hl
ld l, a
ld h, 0
add hl, hl
add hl, hl
ld de, AnimObjGFX
add hl, de
ld c, [hl]
inc hl
ld b, [hl]
inc hl
ld a, [hli]
ld h, [hl]
ld l, a
pop de
push bc
call DecompressRequest2bpp
pop bc
ret
|
; A152016: a(n) = n^4 - n^3 - n^2 - n.
; 0,-2,2,42,172,470,1038,2002,3512,5742,8890,13178,18852,26182,35462,47010,61168,78302,98802,123082,151580,184758,223102,267122,317352,374350,438698,511002,591892,682022,782070,892738,1014752,1148862
mov $1,$0
bin $0,2
pow $1,2
mov $2,$1
add $1,1
mul $1,$0
sub $1,$2
mov $0,$1
mul $0,2
|
; A005056: a(n) = 3^n + 2^n - 1.
; 1,4,12,34,96,274,792,2314,6816,20194,60072,179194,535536,1602514,4799352,14381674,43112256,129271234,387682632,1162785754,3487832976,10462450354,31385253912,94151567434,282446313696,847322163874,2541932937192,7625731702714,22877060890416,68630914235794,205892205836472,617675543767594,1853024483819136,5559069156490114
mov $1,2
lpb $0
sub $0,1
mov $2,$1
trn $3,3
add $2,$3
add $4,$3
sub $1,$4
mul $1,2
sub $2,1
add $1,$2
mul $3,2
add $3,4
mov $4,0
lpe
sub $1,1
|
GLOBAL _cli
GLOBAL _sti
GLOBAL picMasterMask
GLOBAL picSlaveMask
GLOBAL haltcpu
GLOBAL _hlt
GLOBAL spoof_tick
GLOBAL _irq00Handler
GLOBAL _irq01Handler
GLOBAL _irq02Handler
GLOBAL _irq03Handler
GLOBAL _irq04Handler
GLOBAL _irq05Handler
GLOBAL _divideByZeroHandler
GLOBAL _overflowHandler
GLOBAL _opcodeHandler
GLOBAL _generalProtection
EXTERN irqDispatcher
EXTERN exceptionDispatcher
EXTERN schedule
EXTERN printInt
EXTERN debug
SECTION .text
%include "./asm/macros.m"
%macro irqHandlerMaster 1
pushState
mov rdi, %1 ; pasaje de parametro
call irqDispatcher
; signal pic EOI (End of Interrupt)
mov al, 20h
out 20h, al
popState
iretq
%endmacro
%macro exceptionHandler 1
pushState
mov rdi, %1 ; first parameter
mov rsi, rsp ; second parameter
call exceptionDispatcher
popState
mov qword [rsp],0x400000
iretq
%endmacro
_hlt:
sti
hlt
ret
_cli:
cli
ret
_sti:
sti
ret
picMasterMask:
push rbp
mov rbp, rsp
mov ax, di
out 21h,al
pop rbp
retn
picSlaveMask:
push rbp
mov rbp, rsp
mov ax, di ; ax = mascara de 16 bits
out 0A1h,al
pop rbp
retn
;8254 Timer (Timer Tick)
_irq00Handler:
push rax
pushaqlite
mov rdi,rsp ;rsp of previous process
call schedule
mov rsp, rax ;set rsp to next process
mov al, 20h
out 20h, al
popaqlite
pop rax
iretq
;Keyboard
_irq01Handler:
irqHandlerMaster 1
;Cascade pic never called
_irq02Handler:
irqHandlerMaster 2
;Serial Port 2 and 4
_irq03Handler:
irqHandlerMaster 3
;Serial Port 1 and 3
_irq04Handler:
irqHandlerMaster 4
;USB
_irq05Handler:
irqHandlerMaster 5
;Zero Division Exception
_divideByZeroHandler:
exceptionHandler 0
;Overflow Exception
_overflowHandler:
exceptionHandler 4
;Opcode Exception
_opcodeHandler:
exceptionHandler 6
_generalProtection:
exceptionHandler 13
haltcpu:
cli
hlt
ret
_tick_handler:
pushaq
mov rdi,rsp
;optionally change to kernel stack here for security reasons.
call schedule
mov rsp, rax
popaq
mov al, 20h
out 20h, al
iretq
spoof_tick:
int 0x20
ret
SECTION .bss
aux resq 1
|
;LW x1, 0(x1)
LW x4, 1(x1)
ADD x4, x4, x2
SW x4, 1(x1)
LW x4, 2(x1)
ADD x4, x4, x2
SW x4, 2(x1)
LW x4, 3(x1)
ADD x4, x4, x2
SW x4, 3(x1)
LW x4, 4(x1)
ADD x4, x4, x2
SW x4, 4(x1)
LW x4, 5(x1)
ADD x4, x4, x2
SW x4, 5(x1)
|
org 0x100
cpu 8086
slop equ 0
jmp loader
videoDisplayCombination: ; Don't bother with subfunction 1
mov al,0x1a ; mode.com checks this to see if VGA services are available
mov bl,8 ;VGA (2 for CGA card)
iret
videoSubsystemConfiguration: ; Don't actually need to do anything here
mov al,12
xor bx,bx
mov cx,9
iret
characterGeneratorRoutine:
push ds
push ax
xor ax,ax
mov ds,ax
pop ax
push ax
cmp al,0x30
je .getInfo
and al,0x0f
cmp al,0x02
je .eightLineFont
mov byte[0x485],16
jmp .done
.eightLineFont:
mov byte[0x485],8
.done:
pop ax
push ax
test al,0x10
jz .noModeSet
mov ah,0
mov al,[0x449] ; Current screen mode
int 0x10
.noModeSet:
pop ax
pop ds
iret
.getInfo:
mov cl,byte[0x485]
mov ch,0
mov dl,byte[0x484]
pop ax
pop ds
iret
setCursorType:
push ds
push ax
xor ax,ax
mov ds,ax
mov [0x460],cx
push dx
mov dx,0x3d4
mov al,0x0a
mov ah,ch
and ah,0x1e
out dx,ax
inc ax
mov ah,cl
and ah,0x1e
out dx,ax
pop dx
pop ax
pop ds
iret
int10Routine:
sti
cmp ah,0
; je setMode
jne notSetMode
jmp setMode
notSetMode:
cmp ah,1
je setCursorType
cmp ah,0xe
; je writeTTY
jne notWriteTTY
jmp writeTTY
notWriteTTY:
cmp ah,0x10
; jl oldInterrupt10
jge notOldInterrupt10
jmp oldInterrupt10
notOldInterrupt10:
%if 0
push bx
push ax
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
push ax
shr al,1
shr al,1
shr al,1
shr al,1
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
push ax
mov al,ah
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
push ax
mov al,ah
shr al,1
shr al,1
shr al,1
shr al,1
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
pop bx
push bx
push ax
mov al,bl
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
pop bx
push bx
push ax
mov al,bl
shr al,1
shr al,1
shr al,1
shr al,1
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
pop bx
push bx
push ax
mov al,bh
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
pop ax
pop bx
push bx
push ax
mov al,bh
shr al,1
shr al,1
shr al,1
shr al,1
and al,0x0f
add al,'0'
mov ah,0x0e
mov bh,0
int 0x10
mov ah,0
int 0x16
pop ax
pop bx
%endif
cmp ah,0x11
; je characterGeneratorRoutine
jne notCharacterGeneratorRoutine
jmp characterGeneratorRoutine
notCharacterGeneratorRoutine:
cmp ah,0x12
; je videoSubsystemConfiguration
jne notVideoSubsystemConfiguration
jmp videoSubsystemConfiguration
notVideoSubsystemConfiguration:
cmp ah,0x1a
; je videoDisplayCombination
jne notVideoDisplayCombination
jmp videoDisplayCombination
notVideoDisplayCombination:
cmp ah,0x1b
je videoBIOSFunctionalityAndStateInformation
oldInterrupt10:
jmp far 0x9999:0x9999
videoBIOSFunctionalityAndStateInformation:
mov ax,cs
; mov es,ax
; mov di,dynamicVideoStateTable+4
push ds
push si
push cx
push di
mov ax,cs
mov ds,ax
mov si,dynamicVideoStateTable
mov cx,32
rep movsw
pop di
push di
add di,4
xor ax,ax
mov ds,ax
mov cx,16
mov si,0x449
rep movsw
mov ax,[0x485]
pop di
mov [es:di+0x23],ax
pop cx
pop si
pop ds
; mov di,dynamicVideoStateTable
mov al,0x1b
iret
setMode:
push ds
push ax
call stopISAV
pop ax
push ax
pushf
call far [cs:oldInterrupt10+1]
pop ax
cmp al,4
jge doneInt10 ; Don't start ISAV for graphics modes
push ax
xor ax,ax
mov ds,ax
cmp byte[0x485],16
je lines25
pop ax
push ax
test al,2
jnz isav80
mov ax,0x2d11
jmp isavPatch
isav80:
mov ax,0x5a21
isavPatch:
mov [cs:isav1_patch+2],al
mov [cs:isav2_patch+2],ah
mov [cs:isav4_patch+2],al
mov [cs:isav5_patch+2],ah
call startISAV
.safeWaitLoop:
cmp byte[cs:isavActive],0
je .safeWaitLoop
; push es
; push di
; push cx
; ; Clear screen
; mov ax,0xb800
; mov es,ax
; mov ax,0x100
; xor di,di
; mov cx,80*50
;loopTop:
; stosw
; inc ax
; loop loopTop
; pop cx
; pop di
; pop es
;
; mov ah,0
; int 0x16
mov byte[0x484],49 ; Number of rows-1
mov ax,0x2000
test byte[0x449],2 ; Requested video mode
jnz doneCols
mov ax,0x1000
jmp doneCols
lines25:
mov byte[0x484],24 ; Number of lines-1
mov ax,0x800
test byte[0x449],2 ; Requested video mode
jnz doneCols
mov ax,0x1000
doneCols:
mov word[0x44c],ax
pop ax
doneInt10:
pop ds
iret
writeTTY:
push ds
push bx
push cx
push dx
push ax
push ax
xor ax,ax
mov ds,ax
mov ah,3
mov bh,[0x462] ; current active page
int 0x10 ; get cursor position in dx
pop ax
cmp al,8
je .doBackspace
cmp al,13
je .doCarriageReturn
cmp al,10
je .doLineFeed
cmp al,7
je .doBell
mov ah,10
mov cx,1
int 0x10 ; write character
inc dx
cmp dl,[0x44a] ; columns
jnz .setCursor
mov dl,0
cmp dh,[0x484] ; rows - 1
jnz .setCursorInc
.scroll:
mov ah,2
int 0x10 ; Set cursor
mov al,[0x449] ; Current mode
cmp al,4
jb .readCursor
mov bh,0
cmp al,7
jne .scrollUp
.readCursor:
mov ah,8
int 0x10 ; Read character and attribute
mov bh,ah
.scrollUp:
mov ax,0x0601 ; Scroll, one row
xor cx,cx ; Upper left
mov dh,[0x484] ; Bottom row
mov dl,[0x44a]
dec dx ; Right column
.videoCallReturn:
int 0x10
.videoReturn:
pop ax
pop dx
pop cx
pop bx
pop ds
iret
.setCursorInc:
inc dh
.setCursor:
mov ah,2
jmp .videoCallReturn
.doBackspace:
cmp dl,0
je .setCursor ; Do nothing if we're at the left of the screen
dec dx
jmp .setCursor
.doCarriageReturn:
mov dl,0
jmp .setCursor
.doLineFeed:
cmp dh,[0x484] ; bottom row
jne .setCursorInc
jmp .scroll
.doBell:
mov ah,0xe
pushf
call far [cs:oldInterrupt10+1] ; Use original BIOS's bell
jmp .videoReturn
; Want to override:
; ah = 0 set mode
; Check if VIDMAXROW > 24, if so use interlacing, otherwise defer to BIOS
; ah=0x12, bl=0x10: get EGA info
; r.x.ax = 0x1a00; /* get VGA display combination - VGA install check */ needs to return al=0x1a
; r.x.ax = 0x1112; /* activate 8x8 default font */
; r.x.ax = (lines == 16) ? 0x1114 : 0x1111; /* 8x16 and 8x14 font */
; r.h.ah = 0x12; /* set resolution (with BL 0x30) */
%macro waitForVerticalSync 0
%%waitForVerticalSync:
in al,dx
test al,8
jz %%waitForVerticalSync
%endmacro
%macro waitForNoVerticalSync 0
%%waitForNoVerticalSync:
in al,dx
test al,8
jnz %%waitForNoVerticalSync
%endmacro
; ISAV code starts here.
startISAV:
push ds
; ; Mode 09
; ; 1 +HRES 1
; ; 2 +GRPH 0
; ; 4 +BW 0
; ; 8 +VIDEO ENABLE 8
; ; 0x10 +1BPP 0
; ; 0x20 +ENABLE BLINK 0
; mov dx,0x3d8
; mov al,0x09
; out dx,al
;
; ; Palette 00
; ; 1 +OVERSCAN B 0
; ; 2 +OVERSCAN G 2
; ; 4 +OVERSCAN R 4
; ; 8 +OVERSCAN I 0
; ; 0x10 +BACKGROUND I 0
; ; 0x20 +COLOR SEL 0
; inc dx
; mov al,0
; out dx,al
mov dx,0x3d4
; ; 0xff Horizontal Total 71
; mov ax,0x7100
; out dx,ax
;
; ; 0xff Horizontal Displayed 50
; mov ax,0x5001
; out dx,ax
;
; ; 0xff Horizontal Sync Position 5a
; mov ax,0x5a02
; out dx,ax
;
; ; 0x0f Horizontal Sync Width 0a
; mov ax,0x0f03 ;0x0a03
; out dx,ax
; 0x7f Vertical Total 01 vertical total = 2 rows
mov ax,0x0104
out dx,ax
; 0x1f Vertical Total Adjust 00 vertical total adjust = 0
mov ax,0x0005
out dx,ax
; 0x7f Vertical Displayed 01 vertical displayed = 1
mov ax,0x0106
out dx,ax
; 0x7f Vertical Sync Position 1c vertical sync position = 28 rows
mov ax,0x1c07
out dx,ax
; 0x03 Interlace Mode 00 0 = non interlaced, 1 = interlace sync, 3 = interlace sync and video
mov ax,0x0008
out dx,ax
; 0x1f Max Scan Line Address 00 scanlines per row = 1
mov ax,0x0009
out dx,ax
; Cursor Start 06
; 0x1f Cursor Start 6
; 0x60 Cursor Mode 0
; mov ax,0x060a
mov al,0x0a
mov ah,[0x461]
; dec ah
; or ah,1
and ah,0x1e
out dx,ax
; 0x1f Cursor End 08
; mov ax,0x080b
mov al,0x0b
mov ah,[0x460]
; or ah,1
and ah,0x1e
out dx,ax
; 0x3f Start Address (H) 00
mov ax,0x000c
out dx,ax
; 0xff Start Address (L) 00
mov ax,0x000d
out dx,ax
; 0x3f Cursor (H) 03
mov ax,0x030e
out dx,ax
; 0xff Cursor (L) c0
mov ax,0xc00f
out dx,ax
mov dl,0xda
cli
mov al,0x34
out 0x43,al
mov al,0
out 0x40,al
out 0x40,al
mov al,76*2 + 1
out 0x40,al
mov al,0
out 0x40,al
; xor ax,ax
; mov ds,ax
mov ax,[0x20]
mov [cs:originalInterrupt8],ax
mov ax,[0x22]
mov [cs:originalInterrupt8+2],ax
mov word[0x20],int8_oe0
mov [0x22],cs
in al,0x21
mov [cs:originalIMR],al
mov al,0xfe
out 0x21,al
sti
setupLoop:
hlt
jmp setupLoop
originalInterrupt8:
dw 0, 0
originalIMR:
db 0
timerCount:
dw 0
isavActive:
db 0
; Step 0 - don't do anything (we've just completed wait for CRTC stabilization)
int8_oe0:
mov word[0x20],int8_oe1
mov al,0x20
out 0x20,al
iret
; Step 1, wait until display is disabled, then change interrupts
int8_oe1:
in al,dx
test al,1
jz .noInterruptChange ; jump if not -DISPEN, finish if -DISPEN
mov word[0x20],int8_oe2
.noInterruptChange:
mov al,0x20
out 0x20,al
iret
; Step 2, wait until display is enabled - then we'll be at the start of the active area
int8_oe2:
in al,dx
test al,1
jnz .noInterruptChange ; jump if -DISPEN, finish if +DISPEN
mov word[0x20],int8_oe3
mov cx,2
.noInterruptChange:
mov al,0x20
out 0x20,al
iret
; Step 3 - this interrupt occurs one timer cycle into the active area.
; The pattern of scanlines on the screen is +-+-- As the interrupt runs every other scanline, the pattern of scanlines in terms of what is seen from the interrupt is ++---.
int8_oe3:
mov dl,0xd4
mov ax,0x0308 ; Set interlace mode to ISAV
out dx,ax
mov dl,0xda
loop .noInterruptChange
mov word[0x20],int8_oe4
.noInterruptChange:
mov al,76*2
out 0x40,al
mov al,0
out 0x40,al
mov al,0x20
out 0x20,al
iret
; Step 4 - this interrupt occurs two timer cycles into the active area.
int8_oe4:
in al,dx
test al,1
jnz .noInterruptChange ; jump if -DISPEN, finish if +DISPEN
mov word[0x20],int8_oe5
.noInterruptChange:
mov al,0x20
out 0x20,al
iret
; Step 5
int8_oe5:
in al,dx
test al,1
jz .noInterruptChange ; jump if not -DISPEN, finish if -DISPEN (i.e. scanline 4)
mov word[0x20],int8_oe6
mov al,76*2 - 3
out 0x40,al
mov al,0
out 0x40,al
.noInterruptChange:
mov al,0x20
out 0x20,al
iret
; Step 6. This occurs on scanline 1. The next interrupt will be on scanline 3.
int8_oe6:
mov word[0x20],int8_oe7
mov al,76*2
out 0x40,al
mov al,0
out 0x40,al
mov al,0x20
out 0x20,al
iret
; Step 7. This occurs on scanline 3 (one timer cycle before the active area starts). The next interrupt will be on scanline 0.
int8_oe7:
mov word[0x20],int8_oe8
mov al,0x20
out 0x20,al
iret
; Step 8 - scanline 0, next interrupt on scanline 2
int8_oe8:
mov al,(20*76) & 0xff
out 0x40,al
mov al,(20*76) >> 8
out 0x40,al
mov word[0x20],int8_oe9
mov dl,0xd4
mov al,0x20
out 0x20,al
add sp,6
sti
pop ds
ret
; Step 9 - initial short (odd) field
int8_oe9:
push ax
push dx
mov dx,0x3d4
mov ax,0x0309 ; Scanlines per row = 4 (2 on each field)
out dx,ax
mov ax,0x0106 ; Vertical displayed = 1 row (actually 2)
out dx,ax
mov ax,0x0304 ; Vertical total = 4 rows
out dx,ax
mov ax,0x0305 ; Vertical total adjust = 3
out dx,ax
pop dx
mov al,(223*76 + 27 - slop) & 0xff
out 0x40,al
mov al,(223*76 + 27 - slop) >> 8
out 0x40,al
mov al,[cs:originalIMR]
out 0x21,al
push ds
xor ax,ax
mov ds,ax
mov word[0x20],int8_oe10
pop ds
mov al,0x20
out 0x20,al
pop ax
iret
; Step 10 - set up CRTC registers for full screen - scanline 0
int8_oe10:
push ax
push dx
mov dx,0x3d4
mov ax,0x0709 ; Scanlines per row = 8 (4 on each field)
out dx,ax
mov ax,0x1906 ; Vertical displayed = 25 rows (actually 50)
out dx,ax
mov ax,0x1f04 ; Vertical total = 32 rows (actually 64)
out dx,ax
mov ax,0x0605 ; Vertical total adjust = 6
out dx,ax
pop dx
mov al,(525*76) & 0xff
out 0x40,al
mov al,(525*76) >> 8
out 0x40,al
push ds
xor ax,ax
mov ds,ax
mov word[0x20],int8_isav
pop ds
mov byte[cs:isavActive],1
mov al,0x20
out 0x20,al
pop ax
iret
; Final - scanline 224
int8_isav:
push ax
push dx
push bx
mov dx,0x3d4
isav1_patch:
mov ax,0x2102 ; Horizontal sync position early
out dx,ax
mov dx,0x40
mov bx,524*76 + slop
.loopTop1:
mov al,0x04
out 0x43,al
in al,dx
mov ah,al
in al,dx
xchg al,ah
cmp ax,bx
jae .loopTop1
mov dx,0x3d4
isav2_patch:
mov ax,0x5a02 ; Horizontal sync position normal
out dx,ax
mov dx,0x40
mov bx,522*76 + slop
.loopTop2:
mov al,0x04
out 0x43,al
in al,dx
mov ah,al
in al,dx
xchg al,ah
cmp ax,bx
jae .loopTop2
mov dx,0x3d4
isav4_patch:
mov ax,0x2102 ; Horizontal sync position early
out dx,ax
mov dx,0x40
mov bx,521*76 + slop
.loopTop3:
mov al,0x04
out 0x43,al
in al,dx
mov ah,al
in al,dx
xchg al,ah
cmp ax,bx
jae .loopTop3
mov dx,0x3d4
isav5_patch:
mov ax,0x5a02 ; Horizontal sync position normal
out dx,ax
pop bx
pop dx
add word[cs:timerCount],76*525
jnc doneInterrupt8
pop ax
jmp far [cs:originalInterrupt8]
doneInterrupt8:
mov al,0x20
out 0x20,al
pop ax
iret
; Returns the CGA to normal mode
stopISAV:
cmp byte[cs:isavActive],0
je .done
cli
xor ax,ax
mov ds,ax
mov ax,[cs:originalInterrupt8]
mov [8*4],ax
mov ax,[cs:originalInterrupt8+2]
mov [8*4+2],ax
mov al,0x34
out 0x43,al
mov al,0
out 0x40,al
out 0x40,al
sti
mov byte[cs:isavActive],0
; Set the CGA back to a normal mode so we don't risk breaking anything
.done:
ret
dynamicVideoStateTable:
dw staticFunctionalityTable
dw 0 ; Segment of static functionality table - filled in by loader
db 0 ; Video mode - filled in by int 10,1b
dw 0 ; Number of columns - filled in by int 10,1b
dw 0 ; length of displayed video buffer - filled in by int 10,1b
dw 0 ; start address of upper left corner of video buffer - filled in by int 10,1b
dw 0,0,0,0,0,0,0,0 ; cursor position table - filled in by int 10,1b
db 0 ; cursor end line - filled in by int 10,1b
db 0 ; cursor start line - filled in by int 10,1b
db 0 ; active video page - filled in by int 10,1b
dw 0x3d4 ; IO port for CRTC address register
db 0 ; current value for mode register - filled in by int 10,1b
db 0 ; current value for palette register - filled in by int 10,1b
dw 0 ; height of character matrix - filled in by int 10,1b
db 8 ; active display combination code (pretend to be VGA)
db 0 ; inactive display combination code (none)
dw 16 ; number of displayed colours
db 8 ; number of supported video pages
db 2 ; raster scan lines = 400
db 0 ; text character table used
db 0 ; text character table used
db 0xe0 ; state information byte
db 0,0,0 ; reserved
db 0 ; video RAM available (actually only 16kB but 64kB is the lowest that this table supports)
db 0xc0 ; save area status
dw 0,0 ; reserved
staticFunctionalityTable:
db 0x7f ; modes 0-6 supported, mode 7 not supported
db 0 ; modes 8-0x0f not supported
db 0 ; modes 0x10-0x13 not supported
dw 0,0 ; reserved
db 0xfc ; 400 lines
db 1 ; max number of displayable text character sets
db 1 ; # of text definition tables in char generator RAM
db 0 ; other capability flags
db 5 ; other capability flags (light pen supported, blinking/background intensity supported)
dw 0 ; reserved
db 0 ; save area capabilities
db 0 ; reserved
; Non-resident portion
loader:
mov [dynamicVideoStateTable+2],cs
xor ax,ax
mov ds,ax
push ds
%macro setResidentInterrupt 2
mov word [%1*4], %2
mov [%1*4 + 2], cs
%endmacro
cli
mov ax,[0x10*4]
mov cx,[0x10*4 + 2]
mov [cs:oldInterrupt10+1],ax
mov [cs:oldInterrupt10+3],cx
setResidentInterrupt 0x10, int10Routine
sti
mov ah,0
mov al,[0x449] ; Current screen mode
mov byte[0x485],8 ; Request 50 line mode
mov byte[0x489],0x11 ; Set flags to say VGA available
mov byte[0x48a],0x0b ; DCC for VGA
int 0x10 ; Start ISAV
pop ds
mov dx,(loader + 15) >> 4
mov ax,0x3100
int 0x21 ; Go resident
loopTop:
mov al,0x04
out 0x43,al
in al,dx
mov ah,al
in al,dx
xchg al,ah
cmp ax,bx
jae loopTop ; Average 90.9 cycles
|
sll $0, $0, 0
or $t0, $0, $0
ori $t3, $0, 0
ori $t1, $0, 5
LOOP:
addi $t0, $t0, 1
subu $t2, $t0, $t1
bne $t2, $0, LOOP
ori $t1, $0, 5
hlt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.